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