DefaultBolusCalcRootView.swift 18 KB

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