DefaultBolusCalcRootView.swift 17 KB

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