DefaultBolusCalcRootView.swift 17 KB

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