DefaultBolusCalcRootView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import SwiftUI
  2. import Swinject
  3. extension Bolus {
  4. struct DefaultBolusCalcRootView: BaseView {
  5. let resolver: Resolver
  6. let waitForSuggestion: Bool
  7. let fetch: Bool
  8. @StateObject var state = StateModel()
  9. @State private var isAddInsulinAlertPresented = false
  10. @State private var presentInfo = false
  11. @State private var displayError = false
  12. @State private var keepForNextWiew: Bool = false
  13. @Environment(\.colorScheme) var colorScheme
  14. @FetchRequest(
  15. entity: Meals.entity(),
  16. sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
  17. ) var meal: FetchedResults<Meals>
  18. private var formatter: NumberFormatter {
  19. let formatter = NumberFormatter()
  20. formatter.numberStyle = .decimal
  21. formatter.maximumFractionDigits = 2
  22. return formatter
  23. }
  24. private var fractionDigits: Int {
  25. if state.units == .mmolL {
  26. return 1
  27. } else { return 0 }
  28. }
  29. var body: some View {
  30. Form {
  31. if fetch {
  32. Section {
  33. VStack {
  34. if let carbs = meal.first?.carbs, carbs > 0 {
  35. HStack {
  36. Text("Carbs")
  37. Spacer()
  38. Text(carbs.formatted())
  39. Text("g")
  40. }.foregroundColor(.secondary)
  41. }
  42. if let fat = meal.first?.fat, fat > 0 {
  43. HStack {
  44. Text("Fat")
  45. Spacer()
  46. Text(fat.formatted())
  47. Text("g")
  48. }.foregroundColor(.secondary)
  49. }
  50. if let protein = meal.first?.protein, protein > 0 {
  51. HStack {
  52. Text("Protein")
  53. Spacer()
  54. Text(protein.formatted())
  55. Text("g")
  56. }.foregroundColor(.secondary)
  57. }
  58. if let note = meal.first?.note, note != "" {
  59. HStack {
  60. Text("Note")
  61. Spacer()
  62. Text(note)
  63. }.foregroundColor(.secondary)
  64. }
  65. }
  66. } header: { Text("Meal Summary") }
  67. }
  68. Section {
  69. Button {
  70. let id_ = meal.first?.id ?? ""
  71. if fetch {
  72. keepForNextWiew = true
  73. state.backToCarbsView(complexEntry: fetch, id_)
  74. } else {
  75. state.showModal(for: .addCarbs(editMode: false))
  76. }
  77. }
  78. label: { Text(fetch ? "Edit Meal" : "Add Meal") }.frame(maxWidth: .infinity, alignment: .center)
  79. } header: { Text(!fetch ? "Meal Summary" : "") }
  80. Section {
  81. if state.waitForSuggestion {
  82. HStack {
  83. Text("Wait please").foregroundColor(.secondary)
  84. Spacer()
  85. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  86. }
  87. } else {
  88. HStack {
  89. Text("Insulin recommended")
  90. Image(systemName: "info.bubble")
  91. .symbolRenderingMode(.palette)
  92. .foregroundStyle(.primary, .blue)
  93. .onTapGesture {
  94. presentInfo.toggle()
  95. }
  96. Spacer()
  97. Text(
  98. formatter
  99. .string(from: state.insulinRecommended as NSNumber)! +
  100. NSLocalizedString(" U", comment: "Insulin unit")
  101. ).foregroundColor((state.error && state.insulinRecommended > 0) ? .red : .secondary)
  102. .onTapGesture {
  103. if state.error, state.insulinRecommended > 0 { displayError = true }
  104. else { state.amount = state.insulinRecommended }
  105. }
  106. }.contentShape(Rectangle())
  107. }
  108. }
  109. header: { Text("Recommendation") }
  110. if !state.waitForSuggestion {
  111. Section {
  112. HStack {
  113. Text("Amount")
  114. Spacer()
  115. DecimalTextField(
  116. "0",
  117. value: $state.amount,
  118. formatter: formatter,
  119. autofocus: true,
  120. cleanInput: true
  121. )
  122. Text(!(state.amount > state.maxBolus) ? "U" : "😵").foregroundColor(.secondary)
  123. }
  124. }
  125. header: { Text("Bolus") }
  126. Section {
  127. Button {
  128. keepForNextWiew = true
  129. state.add()
  130. }
  131. label: { Text(!(state.amount > state.maxBolus) ? "Enact bolus" : "Max Bolus exceeded!") }
  132. .frame(maxWidth: .infinity, alignment: .center)
  133. .disabled(
  134. state.amount <= 0 || state.amount > state.maxBolus
  135. )
  136. }
  137. if waitForSuggestion {
  138. Section {
  139. Button {
  140. keepForNextWiew = true
  141. state.showModal(for: nil)
  142. }
  143. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  144. }
  145. }
  146. }
  147. }
  148. .alert(isPresented: $displayError) {
  149. Alert(
  150. title: Text("Warning!"),
  151. message: Text("\n" + alertString() + "\n"),
  152. primaryButton: .destructive(
  153. Text("Add"),
  154. action: {
  155. state.amount = state.insulinRecommended
  156. displayError = false
  157. }
  158. ),
  159. secondaryButton: .cancel()
  160. )
  161. }.onAppear {
  162. configureView {
  163. state.waitForSuggestionInitial = waitForSuggestion
  164. state.waitForSuggestion = waitForSuggestion
  165. }
  166. }
  167. .onDisappear {
  168. if fetch, hasFatOrProtein, !keepForNextWiew, !state.useCalc {
  169. state.delete(deleteTwice: true, id: meal.first?.id ?? "")
  170. } else if fetch, !keepForNextWiew, !state.useCalc {
  171. state.delete(deleteTwice: false, id: meal.first?.id ?? "")
  172. }
  173. }
  174. .navigationTitle("Enact Bolus")
  175. .navigationBarTitleDisplayMode(.inline)
  176. .navigationBarItems(leading: Button("Close", action: state.hideModal))
  177. .popup(isPresented: presentInfo, alignment: .center, direction: .bottom) {
  178. bolusInfo
  179. }
  180. }
  181. var changed: Bool {
  182. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  183. }
  184. var hasFatOrProtein: Bool {
  185. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  186. }
  187. var bolusInfo: some View {
  188. VStack {
  189. // Variables
  190. VStack(spacing: 3) {
  191. HStack {
  192. Text("Eventual Glucose").foregroundColor(.secondary)
  193. let evg = state.units == .mmolL ? Decimal(state.evBG).asMmolL : Decimal(state.evBG)
  194. Text(evg.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  195. Text(state.units.rawValue).foregroundColor(.secondary)
  196. }
  197. HStack {
  198. Text("Target Glucose").foregroundColor(.secondary)
  199. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  200. Text(target.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))))
  201. Text(state.units.rawValue).foregroundColor(.secondary)
  202. }
  203. HStack {
  204. Text("ISF").foregroundColor(.secondary)
  205. let isf = state.isf
  206. Text(isf.formatted())
  207. Text(state.units.rawValue + NSLocalizedString("/U", comment: "/Insulin unit"))
  208. .foregroundColor(.secondary)
  209. }
  210. HStack {
  211. Text("ISF:")
  212. Text("Insulin Sensitivity")
  213. }.foregroundColor(.secondary).italic()
  214. if state.percentage != 100 {
  215. HStack {
  216. Text("Percentage setting").foregroundColor(.secondary)
  217. let percentage = state.percentage
  218. Text(percentage.formatted())
  219. Text("%").foregroundColor(.secondary)
  220. }
  221. }
  222. HStack {
  223. Text("Formula:")
  224. Text("(Eventual Glucose - Target) / ISF")
  225. }.foregroundColor(.secondary).italic().padding(.top, 5)
  226. }
  227. .font(.footnote)
  228. .padding(.top, 10)
  229. Divider()
  230. // Formula
  231. VStack(spacing: 5) {
  232. let unit = NSLocalizedString(
  233. " U",
  234. comment: "Unit in number of units delivered (keep the space character!)"
  235. )
  236. let color: Color = (state.percentage != 100 && state.insulin > 0) ? .secondary : .blue
  237. let fontWeight: Font.Weight = (state.percentage != 100 && state.insulin > 0) ? .regular : .bold
  238. HStack {
  239. Text(NSLocalizedString("Insulin recommended", comment: "") + ":").font(.callout)
  240. Text(state.insulin.formatted() + unit).font(.callout).foregroundColor(color).fontWeight(fontWeight)
  241. }
  242. if state.percentage != 100, state.insulin > 0 {
  243. Divider()
  244. HStack { Text(state.percentage.formatted() + " % ->").font(.callout).foregroundColor(.secondary)
  245. Text(
  246. state.insulinRecommended.formatted() + unit
  247. ).font(.callout).foregroundColor(.blue).bold()
  248. }
  249. }
  250. }
  251. // Warning
  252. if state.error, state.insulinRecommended > 0 {
  253. VStack(spacing: 5) {
  254. Divider()
  255. Text("Warning!").font(.callout).bold().foregroundColor(.orange)
  256. Text(alertString()).font(.footnote)
  257. Divider()
  258. }.padding(.horizontal, 10)
  259. }
  260. // Footer
  261. if !(state.error && state.insulinRecommended > 0) {
  262. VStack {
  263. Text(
  264. "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."
  265. ).font(.caption2).foregroundColor(.secondary)
  266. }.padding(20)
  267. }
  268. // Hide button
  269. VStack {
  270. Button { presentInfo = false }
  271. label: { Text("Hide") }.frame(maxWidth: .infinity, alignment: .center).font(.callout)
  272. .foregroundColor(.blue)
  273. }.padding(.bottom, 10)
  274. }
  275. .background(
  276. RoundedRectangle(cornerRadius: 8, style: .continuous)
  277. .fill(Color(colorScheme == .dark ? UIColor.systemGray4 : UIColor.systemGray4))
  278. )
  279. }
  280. // Localize the Oref0 error/warning strings. The default should never be returned
  281. private func alertString() -> String {
  282. switch state.errorString {
  283. case 1,
  284. 2:
  285. return NSLocalizedString(
  286. "Eventual Glucose > Target Glucose, but glucose is predicted to first drop down to ",
  287. comment: "Bolus pop-up / Alert string. Make translations concise!"
  288. ) + state.minGuardBG
  289. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state.units
  290. .rawValue + ", " +
  291. NSLocalizedString(
  292. "which is below your Threshold (",
  293. comment: "Bolus pop-up / Alert string. Make translations concise!"
  294. ) + state
  295. .threshold.formatted() + " " + state.units.rawValue + ")"
  296. case 3:
  297. return NSLocalizedString(
  298. "Eventual Glucose > Target Glucose, but glucose is climbing slower than expected. Expected: ",
  299. comment: "Bolus pop-up / Alert string. Make translations concise!"
  300. ) +
  301. state.expectedDelta
  302. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  303. NSLocalizedString(". Climbing: ", comment: "Bolus pop-up / Alert string. Make translatons concise!") + state
  304. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  305. case 4:
  306. return NSLocalizedString(
  307. "Eventual Glucose > Target Glucose, but glucose is falling faster than expected. Expected: ",
  308. comment: "Bolus pop-up / Alert string. Make translations concise!"
  309. ) +
  310. state.expectedDelta
  311. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  312. NSLocalizedString(". Falling: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  313. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  314. case 5:
  315. return NSLocalizedString(
  316. "Eventual Glucose > Target Glucose, but glucose is changing faster than expected. Expected: ",
  317. comment: "Bolus pop-up / Alert string. Make translations concise!"
  318. ) +
  319. state.expectedDelta
  320. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  321. NSLocalizedString(". Changing: ", comment: "Bolus pop-up / Alert string. Make translations concise!") + state
  322. .minDelta.formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  323. case 6:
  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
  328. .minPredBG
  329. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) + " " + state
  330. .units
  331. .rawValue
  332. default:
  333. return "Ignore Warning..."
  334. }
  335. }
  336. }
  337. }