DefaultBolusCalcRootView.swift 17 KB

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