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. @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(.inline)
  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. else {
  169. Button {
  170. state.hideModal()
  171. } label: {
  172. Text("Close")
  173. }
  174. }
  175. }
  176. }
  177. .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
  178. bolusInfo
  179. }
  180. }
  181. var disabled: Bool {
  182. state.amount <= 0 || state.amount > state.maxBolus
  183. }
  184. var predictionChart: some View {
  185. ZStack {
  186. PredictionView(
  187. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  188. displayPredictions: $state.displayPredictions
  189. )
  190. }
  191. }
  192. var changed: Bool {
  193. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  194. }
  195. var hasFatOrProtein: Bool {
  196. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  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. }