DefaultBolusCalcRootView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. extension Bolus {
  6. struct DefaultBolusCalcRootView: BaseView {
  7. let resolver: Resolver
  8. let waitForSuggestion: Bool
  9. let fetch: Bool
  10. @StateObject var state = StateModel()
  11. @State private var isAddInsulinAlertPresented = false
  12. @State private var presentInfo = false
  13. @State private var displayError = false
  14. @State private var keepForNextWiew: Bool = false
  15. @Environment(\.colorScheme) var colorScheme
  16. @FetchRequest(
  17. entity: Meals.entity(),
  18. sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
  19. ) var meal: FetchedResults<Meals>
  20. private var formatter: NumberFormatter {
  21. let formatter = NumberFormatter()
  22. formatter.numberStyle = .decimal
  23. formatter.maximumFractionDigits = 2
  24. return formatter
  25. }
  26. private var fractionDigits: Int {
  27. if state.units == .mmolL {
  28. return 1
  29. } else { return 0 }
  30. }
  31. var body: some View {
  32. Form {
  33. if state.displayPredictions {
  34. Section {
  35. if state.waitForSuggestion {
  36. Text("Please wait")
  37. } else {
  38. predictionChart
  39. }
  40. } header: { Text("Predictions") }
  41. }
  42. if fetch {
  43. Section {
  44. mealEntries
  45. } header: { Text("Meal Summary") }
  46. }
  47. Section {
  48. if state.waitForSuggestion {
  49. HStack {
  50. Text("Wait please").foregroundColor(.secondary)
  51. Spacer()
  52. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  53. }
  54. } else {
  55. HStack {
  56. Text("Insulin recommended")
  57. Image(systemName: "info.bubble")
  58. .symbolRenderingMode(.palette)
  59. .foregroundStyle(.primary, .blue)
  60. .onTapGesture {
  61. presentInfo.toggle()
  62. }
  63. Spacer()
  64. Text(
  65. formatter
  66. .string(from: state.insulinRecommended as NSNumber)! +
  67. NSLocalizedString(" U", comment: "Insulin unit")
  68. ).foregroundColor((state.error && state.insulinRecommended > 0) ? .red : .secondary)
  69. .onTapGesture {
  70. if state.error, state.insulinRecommended > 0 { displayError = true }
  71. else { state.amount = state.insulinRecommended }
  72. }
  73. }.contentShape(Rectangle())
  74. }
  75. HStack {
  76. Text("Amount")
  77. Spacer()
  78. DecimalTextField(
  79. "0",
  80. value: $state.amount,
  81. formatter: formatter,
  82. autofocus: true,
  83. cleanInput: true
  84. )
  85. Text(!(state.amount > state.maxBolus) ? "U" : "😵").foregroundColor(.secondary)
  86. }
  87. } header: { Text("Bolus") }
  88. if state.amount > 0 {
  89. Section {
  90. Button {
  91. keepForNextWiew = true
  92. state.add()
  93. }
  94. label: { Text(!(state.amount > state.maxBolus) ? "Enact bolus" : "Max Bolus exceeded!") }
  95. .frame(maxWidth: .infinity, alignment: .center)
  96. .disabled(disabled)
  97. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  98. .tint(.white)
  99. }
  100. }
  101. if state.amount <= 0 {
  102. Section {
  103. Button {
  104. keepForNextWiew = true
  105. state.showModal(for: nil)
  106. }
  107. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  108. }
  109. }
  110. }
  111. .alert(isPresented: $displayError) {
  112. Alert(
  113. title: Text("Warning!"),
  114. message: Text("\n" + alertString() + "\n"),
  115. primaryButton: .destructive(
  116. Text("Add"),
  117. action: {
  118. state.amount = state.insulinRecommended
  119. displayError = false
  120. }
  121. ),
  122. secondaryButton: .cancel()
  123. )
  124. }.onAppear {
  125. configureView {
  126. state.waitForSuggestionInitial = waitForSuggestion
  127. state.waitForSuggestion = waitForSuggestion
  128. }
  129. }
  130. .onDisappear {
  131. if fetch, hasFatOrProtein, !keepForNextWiew, !state.useCalc {
  132. state.delete(deleteTwice: true, id: meal.first?.id ?? "")
  133. } else if fetch, !keepForNextWiew, !state.useCalc {
  134. state.delete(deleteTwice: false, id: meal.first?.id ?? "")
  135. }
  136. }
  137. .navigationTitle("Enact Bolus")
  138. .navigationBarTitleDisplayMode(.inline)
  139. .navigationBarItems(
  140. leading: Button {
  141. carbsView()
  142. }
  143. label: {
  144. HStack {
  145. Image(systemName: "chevron.backward")
  146. Text("Meal")
  147. }
  148. },
  149. trailing: Button { state.hideModal() }
  150. label: { Text("Close") }
  151. )
  152. .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
  153. bolusInfo
  154. }
  155. }
  156. var disabled: Bool {
  157. state.amount <= 0 || state.amount > state.maxBolus
  158. }
  159. var predictionChart: some View {
  160. ZStack {
  161. PredictionView(
  162. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target
  163. )
  164. }
  165. }
  166. var changed: Bool {
  167. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  168. }
  169. var hasFatOrProtein: Bool {
  170. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  171. }
  172. func carbsView() {
  173. let id_ = meal.first?.id ?? ""
  174. if fetch {
  175. keepForNextWiew = true
  176. state.backToCarbsView(complexEntry: fetch, id_, override: false)
  177. } else {
  178. state.backToCarbsView(complexEntry: false, id_, override: true)
  179. }
  180. }
  181. var mealEntries: some View {
  182. VStack {
  183. if let carbs = meal.first?.carbs, carbs > 0 {
  184. HStack {
  185. Text("Carbs")
  186. Spacer()
  187. Text(carbs.formatted())
  188. Text("g")
  189. }.foregroundColor(.secondary)
  190. }
  191. if let fat = meal.first?.fat, fat > 0 {
  192. HStack {
  193. Text("Fat")
  194. Spacer()
  195. Text(fat.formatted())
  196. Text("g")
  197. }.foregroundColor(.secondary)
  198. }
  199. if let protein = meal.first?.protein, protein > 0 {
  200. HStack {
  201. Text("Protein")
  202. Spacer()
  203. Text(protein.formatted())
  204. Text("g")
  205. }.foregroundColor(.secondary)
  206. }
  207. if let note = meal.first?.note, note != "" {
  208. HStack {
  209. Text("Note")
  210. Spacer()
  211. Text(note)
  212. }.foregroundColor(.secondary)
  213. }
  214. }
  215. }
  216. var bolusInfo: some View {
  217. VStack {
  218. // Variables
  219. VStack(spacing: 3) {
  220. HStack {
  221. Text("Eventual Glucose").foregroundColor(.secondary)
  222. let evg = state.units == .mmolL ? Decimal(state.evBG).asMmolL : Decimal(state.evBG)
  223. Text(evg.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  224. Text(state.units.rawValue).foregroundColor(.secondary)
  225. }
  226. HStack {
  227. Text("Target Glucose").foregroundColor(.secondary)
  228. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  229. Text(target.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  230. Text(state.units.rawValue).foregroundColor(.secondary)
  231. }
  232. HStack {
  233. Text("ISF").foregroundColor(.secondary)
  234. let isf = state.isf
  235. Text(isf.formatted())
  236. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  237. .foregroundColor(.secondary)
  238. }
  239. HStack {
  240. Text("ISF:")
  241. Text("Insulin Sensitivity")
  242. }.foregroundColor(.secondary).italic()
  243. if state.percentage != 100 {
  244. HStack {
  245. Text("Percentage setting").foregroundColor(.secondary)
  246. let percentage = state.percentage
  247. Text(percentage.formatted())
  248. Text("%").foregroundColor(.secondary)
  249. }
  250. }
  251. HStack {
  252. Text("Formula:")
  253. Text("(Eventual Glucose - Target) / ISF")
  254. }.foregroundColor(.secondary).italic().padding(.top, 5)
  255. }
  256. .font(.footnote)
  257. .padding(.top, 10)
  258. Divider()
  259. // Formula
  260. VStack(spacing: 5) {
  261. let unit = NSLocalizedString(
  262. " U",
  263. comment: "Unit in number of units delivered (keep the space character!)"
  264. )
  265. let color: Color = (state.percentage != 100 && state.insulin > 0) ? .secondary : .blue
  266. let fontWeight: Font.Weight = (state.percentage != 100 && state.insulin > 0) ? .regular : .bold
  267. HStack {
  268. Text(NSLocalizedString("Insulin recommended", comment: "") + ":").font(.callout)
  269. Text(state.insulin.formatted() + unit).font(.callout).foregroundColor(color).fontWeight(fontWeight)
  270. }
  271. if state.percentage != 100, state.insulin > 0 {
  272. Divider()
  273. HStack { Text(state.percentage.formatted() + " % ->").font(.callout).foregroundColor(.secondary)
  274. Text(
  275. state.insulinRecommended.formatted() + unit
  276. ).font(.callout).foregroundColor(.blue).bold()
  277. }
  278. }
  279. }
  280. // Warning
  281. if state.error, state.insulinRecommended > 0 {
  282. VStack(spacing: 5) {
  283. Divider()
  284. Text("Warning!").font(.callout).bold().foregroundColor(.orange)
  285. Text(alertString()).font(.footnote)
  286. Divider()
  287. }.padding(.horizontal, 10)
  288. }
  289. // Footer
  290. if !(state.error && state.insulinRecommended > 0) {
  291. VStack {
  292. Text(
  293. "Carbs and previous insulin are included in the glucose prediction, but if the Eventual Glucose is lower than the Target Glucose, a bolus will not be recommended."
  294. ).font(.caption2).foregroundColor(.secondary)
  295. }.padding(20)
  296. }
  297. // Hide button
  298. VStack {
  299. Button { presentInfo = false }
  300. label: { Text("Hide") }.frame(maxWidth: .infinity, alignment: .center).font(.callout)
  301. .foregroundColor(.blue)
  302. }.padding(.bottom, 10)
  303. }
  304. .background(
  305. RoundedRectangle(cornerRadius: 8, style: .continuous)
  306. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4))
  307. )
  308. }
  309. // Localize the Oref0 error/warning strings. The default should never be returned
  310. private func alertString() -> String {
  311. switch state.errorString {
  312. case 1,
  313. 2:
  314. return NSLocalizedString(
  315. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  316. comment: "Bolus pop-up / Alert string. Make translations concise!"
  317. ) + state.minGuardBG
  318. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state.units
  319. .rawValue + ", " +
  320. NSLocalizedString(
  321. "which is below your Threshold (",
  322. comment: "Bolus pop-up / Alert string. Make translations concise!"
  323. ) + state
  324. .threshold.formatted() + " " + state.units.rawValue + ")"
  325. case 3:
  326. return NSLocalizedString(
  327. "Eventual Glucose > Target Glucose, but glucose is climbing slower than expected. Expected: ",
  328. comment: "Bolus pop-up / Alert string. Make translations concise!"
  329. ) +
  330. state.expectedDelta
  331. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  332. NSLocalizedString(". Climbing: ", comment: "Bolus pop-up / Alert string. Make translatons concise!") + state
  333. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  334. case 4:
  335. return NSLocalizedString(
  336. "Eventual Glucose > Target Glucose, but glucose is falling faster than expected. Expected: ",
  337. comment: "Bolus pop-up / Alert string. Make translations concise!"
  338. ) +
  339. state.expectedDelta
  340. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  341. NSLocalizedString(". Falling: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  342. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  343. case 5:
  344. return NSLocalizedString(
  345. "Eventual Glucose > Target Glucose, but glucose is changing faster than expected. Expected: ",
  346. comment: "Bolus pop-up / Alert string. Make translations concise!"
  347. ) +
  348. state.expectedDelta
  349. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  350. NSLocalizedString(". Changing: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  351. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  352. case 6:
  353. return NSLocalizedString(
  354. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  355. comment: "Bolus pop-up / Alert string. Make translations concise!"
  356. ) + state
  357. .minPredBG
  358. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state
  359. .units
  360. .rawValue
  361. default:
  362. return "Ignore Warning..."
  363. }
  364. }
  365. }
  366. }