DefaultBolusCalcRootView.swift 18 KB

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