DefaultBolusCalcRootView.swift 18 KB

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