DefaultBolusCalcRootView.swift 18 KB

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