DefaultBolusCalcRootView.swift 18 KB

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