DefaultBolusCalcRootView.swift 17 KB

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