DefaultBolusCalcRootView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. HStack {
  73. Text("Amount")
  74. Spacer()
  75. DecimalTextField(
  76. "0",
  77. value: $state.amount,
  78. formatter: formatter,
  79. autofocus: true,
  80. cleanInput: true
  81. )
  82. Text(!(state.amount > state.maxBolus) ? "U" : "😵").foregroundColor(.secondary)
  83. }
  84. }
  85. } header: { Text("Bolus") }
  86. if !state.waitForSuggestion {
  87. if state.amount > 0 {
  88. Section {
  89. Button {
  90. keepForNextWiew = true
  91. state.add()
  92. }
  93. label: { Text(!(state.amount > state.maxBolus) ? "Enact bolus" : "Max Bolus exceeded!") }
  94. .frame(maxWidth: .infinity, alignment: .center)
  95. .disabled(disabled)
  96. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  97. .tint(.white)
  98. }
  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. carbssView()
  142. }
  143. label: { Text(fetch ? "Back" : "Meal") },
  144. trailing: Button { state.hideModal() }
  145. label: { Text("Close") }
  146. )
  147. .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
  148. bolusInfo
  149. }
  150. }
  151. var disabled: Bool {
  152. state.amount <= 0 || state.amount > state.maxBolus
  153. }
  154. var predictionChart: some View {
  155. ZStack {
  156. PredictionView(
  157. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target
  158. )
  159. }
  160. }
  161. var changed: Bool {
  162. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  163. }
  164. var hasFatOrProtein: Bool {
  165. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  166. }
  167. func carbssView() {
  168. let id_ = meal.first?.id ?? ""
  169. if fetch {
  170. keepForNextWiew = true
  171. state.backToCarbsView(complexEntry: fetch, id_)
  172. } else {
  173. state.showModal(for: .addCarbs(editMode: false))
  174. }
  175. }
  176. var mealEntries: some View {
  177. VStack {
  178. if let carbs = meal.first?.carbs, carbs > 0 {
  179. HStack {
  180. Text("Carbs")
  181. Spacer()
  182. Text(carbs.formatted())
  183. Text("g")
  184. }.foregroundColor(.secondary)
  185. }
  186. if let fat = meal.first?.fat, fat > 0 {
  187. HStack {
  188. Text("Fat")
  189. Spacer()
  190. Text(fat.formatted())
  191. Text("g")
  192. }.foregroundColor(.secondary)
  193. }
  194. if let protein = meal.first?.protein, protein > 0 {
  195. HStack {
  196. Text("Protein")
  197. Spacer()
  198. Text(protein.formatted())
  199. Text("g")
  200. }.foregroundColor(.secondary)
  201. }
  202. if let note = meal.first?.note, note != "" {
  203. HStack {
  204. Text("Note")
  205. Spacer()
  206. Text(note)
  207. }.foregroundColor(.secondary)
  208. }
  209. }
  210. }
  211. var bolusInfo: some View {
  212. VStack {
  213. // Variables
  214. VStack(spacing: 3) {
  215. HStack {
  216. Text("Eventual Glucose").foregroundColor(.secondary)
  217. let evg = state.units == .mmolL ? Decimal(state.evBG).asMmolL : Decimal(state.evBG)
  218. Text(evg.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  219. Text(state.units.rawValue).foregroundColor(.secondary)
  220. }
  221. HStack {
  222. Text("Target Glucose").foregroundColor(.secondary)
  223. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  224. Text(target.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  225. Text(state.units.rawValue).foregroundColor(.secondary)
  226. }
  227. HStack {
  228. Text("ISF").foregroundColor(.secondary)
  229. let isf = state.isf
  230. Text(isf.formatted())
  231. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  232. .foregroundColor(.secondary)
  233. }
  234. HStack {
  235. Text("ISF:")
  236. Text("Insulin Sensitivity")
  237. }.foregroundColor(.secondary).italic()
  238. if state.percentage != 100 {
  239. HStack {
  240. Text("Percentage setting").foregroundColor(.secondary)
  241. let percentage = state.percentage
  242. Text(percentage.formatted())
  243. Text("%").foregroundColor(.secondary)
  244. }
  245. }
  246. HStack {
  247. Text("Formula:")
  248. Text("(Eventual Glucose - Target) / ISF")
  249. }.foregroundColor(.secondary).italic().padding(.top, 5)
  250. }
  251. .font(.footnote)
  252. .padding(.top, 10)
  253. Divider()
  254. // Formula
  255. VStack(spacing: 5) {
  256. let unit = NSLocalizedString(
  257. " U",
  258. comment: "Unit in number of units delivered (keep the space character!)"
  259. )
  260. let color: Color = (state.percentage != 100 && state.insulin > 0) ? .secondary : .blue
  261. let fontWeight: Font.Weight = (state.percentage != 100 && state.insulin > 0) ? .regular : .bold
  262. HStack {
  263. Text(NSLocalizedString("Insulin recommended", comment: "") + ":").font(.callout)
  264. Text(state.insulin.formatted() + unit).font(.callout).foregroundColor(color).fontWeight(fontWeight)
  265. }
  266. if state.percentage != 100, state.insulin > 0 {
  267. Divider()
  268. HStack { Text(state.percentage.formatted() + " % ->").font(.callout).foregroundColor(.secondary)
  269. Text(
  270. state.insulinRecommended.formatted() + unit
  271. ).font(.callout).foregroundColor(.blue).bold()
  272. }
  273. }
  274. }
  275. // Warning
  276. if state.error, state.insulinRecommended > 0 {
  277. VStack(spacing: 5) {
  278. Divider()
  279. Text("Warning!").font(.callout).bold().foregroundColor(.orange)
  280. Text(alertString()).font(.footnote)
  281. Divider()
  282. }.padding(.horizontal, 10)
  283. }
  284. // Footer
  285. if !(state.error && state.insulinRecommended > 0) {
  286. VStack {
  287. Text(
  288. "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."
  289. ).font(.caption2).foregroundColor(.secondary)
  290. }.padding(20)
  291. }
  292. // Hide button
  293. VStack {
  294. Button { presentInfo = false }
  295. label: { Text("Hide") }.frame(maxWidth: .infinity, alignment: .center).font(.callout)
  296. .foregroundColor(.blue)
  297. }.padding(.bottom, 10)
  298. }
  299. .background(
  300. RoundedRectangle(cornerRadius: 8, style: .continuous)
  301. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4))
  302. )
  303. }
  304. // Localize the Oref0 error/warning strings. The default should never be returned
  305. private func alertString() -> String {
  306. switch state.errorString {
  307. case 1,
  308. 2:
  309. return NSLocalizedString(
  310. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  311. comment: "Bolus pop-up / Alert string. Make translations concise!"
  312. ) + state.minGuardBG
  313. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state.units
  314. .rawValue + ", " +
  315. NSLocalizedString(
  316. "which is below your Threshold (",
  317. comment: "Bolus pop-up / Alert string. Make translations concise!"
  318. ) + state
  319. .threshold.formatted() + " " + state.units.rawValue + ")"
  320. case 3:
  321. return NSLocalizedString(
  322. "Eventual Glucose > Target Glucose, but glucose is climbing slower than expected. Expected: ",
  323. comment: "Bolus pop-up / Alert string. Make translations concise!"
  324. ) +
  325. state.expectedDelta
  326. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  327. NSLocalizedString(". Climbing: ", comment: "Bolus pop-up / Alert string. Make translatons concise!") + state
  328. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  329. case 4:
  330. return NSLocalizedString(
  331. "Eventual Glucose > Target Glucose, but glucose is falling faster than expected. Expected: ",
  332. comment: "Bolus pop-up / Alert string. Make translations concise!"
  333. ) +
  334. state.expectedDelta
  335. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  336. NSLocalizedString(". Falling: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  337. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  338. case 5:
  339. return NSLocalizedString(
  340. "Eventual Glucose > Target Glucose, but glucose is changing faster than expected. Expected: ",
  341. comment: "Bolus pop-up / Alert string. Make translations concise!"
  342. ) +
  343. state.expectedDelta
  344. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  345. NSLocalizedString(". Changing: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  346. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  347. case 6:
  348. return NSLocalizedString(
  349. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  350. comment: "Bolus pop-up / Alert string. Make translations concise!"
  351. ) + state
  352. .minPredBG
  353. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state
  354. .units
  355. .rawValue
  356. default:
  357. return "Ignore Warning..."
  358. }
  359. }
  360. }
  361. }