DefaultBolusCalcRootView.swift 17 KB

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