AlternativeBolusCalcRootView.swift 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. import Charts
  2. import CoreData
  3. import LoopKitUI
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. struct AlternativeBolusCalcRootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state: StateModel
  10. @State private var showInfo: Bool = false
  11. @State private var showAlert = false
  12. @State private var autofocus: Bool = true
  13. @State private var calculatorDetent = PresentationDetent.medium
  14. @State private var pushed: Bool = false
  15. @State private var isPromptPresented: Bool = false
  16. @State private var dish: String = ""
  17. @State private var saved: Bool = false
  18. @State private var debounce: DispatchWorkItem?
  19. @Environment(\.managedObjectContext) var moc
  20. private enum Config {
  21. static let dividerHeight: CGFloat = 2
  22. static let spacing: CGFloat = 3
  23. }
  24. @Environment(\.colorScheme) var colorScheme
  25. @FetchRequest(
  26. entity: Presets.entity(),
  27. sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  28. ) var carbPresets: FetchedResults<Presets>
  29. private var formatter: NumberFormatter {
  30. let formatter = NumberFormatter()
  31. formatter.numberStyle = .decimal
  32. formatter.maximumFractionDigits = 2
  33. return formatter
  34. }
  35. private var mealFormatter: NumberFormatter {
  36. let formatter = NumberFormatter()
  37. formatter.numberStyle = .decimal
  38. formatter.maximumFractionDigits = 1
  39. return formatter
  40. }
  41. private var gluoseFormatter: NumberFormatter {
  42. let formatter = NumberFormatter()
  43. formatter.numberStyle = .decimal
  44. if state.units == .mmolL {
  45. formatter.maximumFractionDigits = 1
  46. } else { formatter.maximumFractionDigits = 0 }
  47. return formatter
  48. }
  49. private var fractionDigits: Int {
  50. if state.units == .mmolL {
  51. return 1
  52. } else { return 0 }
  53. }
  54. private var color: LinearGradient {
  55. colorScheme == .dark ? LinearGradient(
  56. gradient: Gradient(colors: [
  57. Color.bgDarkBlue,
  58. Color.bgDarkerDarkBlue
  59. ]),
  60. startPoint: .top,
  61. endPoint: .bottom
  62. )
  63. :
  64. LinearGradient(
  65. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  66. startPoint: .top,
  67. endPoint: .bottom
  68. )
  69. }
  70. private var empty: Bool {
  71. state.useFPUconversion ? (state.carbs <= 0 && state.fat <= 0 && state.protein <= 0) : (state.carbs <= 0)
  72. }
  73. /// Handles macro input (carb, fat, protein) in a debounced fashion.
  74. func handleDebouncedInput() {
  75. debounce?.cancel()
  76. debounce = DispatchWorkItem { [self] in
  77. state.insulinCalculated = state.calculateInsulin()
  78. }
  79. if let debounce = debounce {
  80. DispatchQueue.main.asyncAfter(deadline: .now() + 0.35, execute: debounce)
  81. }
  82. }
  83. private var presetPopover: some View {
  84. Form {
  85. Section {
  86. TextField("Name Of Dish", text: $dish)
  87. Button {
  88. saved = true
  89. if dish != "", saved {
  90. let preset = Presets(context: moc)
  91. preset.dish = dish
  92. preset.fat = state.fat as NSDecimalNumber
  93. preset.protein = state.protein as NSDecimalNumber
  94. preset.carbs = state.carbs as NSDecimalNumber
  95. try? moc.save()
  96. state.addNewPresetToWaitersNotepad(dish)
  97. saved = false
  98. isPromptPresented = false
  99. }
  100. }
  101. label: { Text("Save") }
  102. Button {
  103. dish = ""
  104. saved = false
  105. isPromptPresented = false }
  106. label: { Text("Cancel") }
  107. } header: { Text("Enter Meal Preset Name") }
  108. }
  109. }
  110. private var minusButton: some View {
  111. Button {
  112. if state.carbs != 0,
  113. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  114. {
  115. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  116. } else { state.carbs = 0 }
  117. if state.fat != 0,
  118. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  119. {
  120. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  121. } else { state.fat = 0 }
  122. if state.protein != 0,
  123. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  124. {
  125. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  126. } else { state.protein = 0 }
  127. state.removePresetFromNewMeal()
  128. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  129. }
  130. label: { Image(systemName: "minus.circle.fill")
  131. .font(.system(size: 20))
  132. }
  133. .disabled(
  134. state
  135. .selection == nil ||
  136. (
  137. !state.summation
  138. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  139. )
  140. )
  141. .buttonStyle(.borderless)
  142. .tint(.blue)
  143. }
  144. private var plusButton: some View {
  145. Button {
  146. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  147. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  148. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  149. state.addPresetToNewMeal()
  150. }
  151. label: { Image(systemName: "plus.circle.fill")
  152. .font(.system(size: 20))
  153. }
  154. .disabled(state.selection == nil)
  155. .buttonStyle(.borderless)
  156. .tint(.blue)
  157. }
  158. private var mealPresets: some View {
  159. Section {
  160. HStack {
  161. if state.selection != nil {
  162. minusButton
  163. }
  164. Picker("Preset", selection: $state.selection) {
  165. Text("Saved Food").tag(nil as Presets?)
  166. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  167. Text(preset.dish ?? "").tag(preset as Presets?)
  168. }
  169. }
  170. .labelsHidden()
  171. .frame(maxWidth: .infinity, alignment: .center)
  172. ._onBindingChange($state.selection) { _ in
  173. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  174. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  175. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  176. state.addToSummation()
  177. }
  178. if state.selection != nil {
  179. plusButton
  180. }
  181. }
  182. HStack {
  183. Button("Delete Preset") {
  184. showAlert.toggle()
  185. }
  186. .disabled(state.selection == nil)
  187. .tint(.orange)
  188. .buttonStyle(.borderless)
  189. .alert(
  190. "Delete preset '\(state.selection?.dish ?? "")'?",
  191. isPresented: $showAlert,
  192. actions: {
  193. Button("No", role: .cancel) {}
  194. Button("Yes", role: .destructive) {
  195. state.deletePreset()
  196. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  197. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  198. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  199. state.addPresetToNewMeal()
  200. }
  201. }
  202. )
  203. Spacer()
  204. Button {
  205. isPromptPresented = true
  206. }
  207. label: { Text("Save as Preset") }
  208. .buttonStyle(.borderless)
  209. .disabled(
  210. empty ||
  211. (
  212. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  213. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  214. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  215. .protein
  216. )
  217. )
  218. }
  219. }
  220. }
  221. @ViewBuilder private func proteinAndFat() -> some View {
  222. HStack {
  223. Text("Fat").foregroundColor(.orange)
  224. Spacer()
  225. DecimalTextField(
  226. "0",
  227. value: $state.fat,
  228. formatter: formatter,
  229. autofocus: false,
  230. cleanInput: true
  231. )
  232. Text("g").foregroundColor(.secondary)
  233. }
  234. HStack {
  235. Text("Protein").foregroundColor(.red)
  236. Spacer()
  237. DecimalTextField(
  238. "0",
  239. value: $state.protein,
  240. formatter: formatter,
  241. autofocus: false,
  242. cleanInput: true
  243. ).foregroundColor(.loopRed)
  244. Text("g").foregroundColor(.secondary)
  245. }
  246. }
  247. var body: some View {
  248. ZStack(alignment: .center) {
  249. VStack {
  250. Form {
  251. Section {
  252. HStack {
  253. Text("Carbs").fontWeight(.semibold)
  254. Spacer()
  255. DecimalTextField(
  256. "0",
  257. value: $state.carbs,
  258. formatter: formatter,
  259. autofocus: false,
  260. cleanInput: true
  261. ).onChange(of: state.carbs) { _ in
  262. if state.carbs > 0 {
  263. handleDebouncedInput()
  264. }
  265. }
  266. Text("g").foregroundColor(.secondary)
  267. }
  268. if state.useFPUconversion {
  269. proteinAndFat()
  270. }
  271. // Summary when combining presets
  272. if state.waitersNotepad() != "" {
  273. HStack {
  274. Text("Total")
  275. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  276. HStack(spacing: 0) {
  277. ForEach(test, id: \.self) {
  278. Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
  279. Text($0 == test[test.count - 1] ? "" : ", ")
  280. }
  281. }.frame(maxWidth: .infinity, alignment: .trailing)
  282. }
  283. }
  284. // Time
  285. HStack {
  286. Text("Time").foregroundStyle(Color.secondary)
  287. Spacer()
  288. if !pushed {
  289. Button {
  290. pushed = true
  291. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  292. .padding(.trailing, 5)
  293. } else {
  294. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  295. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  296. DatePicker(
  297. "Time",
  298. selection: $state.date,
  299. displayedComponents: [.hourAndMinute]
  300. ).controlSize(.mini)
  301. .labelsHidden()
  302. Button {
  303. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  304. }
  305. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  306. }
  307. }
  308. .popover(isPresented: $isPromptPresented) {
  309. presetPopover
  310. }
  311. }.listRowBackground(Color.chart)
  312. if state.displayPresets {
  313. Section {
  314. mealPresets
  315. }.listRowBackground(Color.chart)
  316. }
  317. Section {
  318. HStack {
  319. Button(action: {
  320. showInfo.toggle()
  321. }, label: {
  322. Image(systemName: "info.circle")
  323. Text("Calculations")
  324. })
  325. .foregroundStyle(.blue)
  326. .font(.footnote)
  327. .buttonStyle(PlainButtonStyle())
  328. .frame(maxWidth: .infinity, alignment: .leading)
  329. if state.fattyMeals {
  330. Spacer()
  331. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  332. Text("Fatty Meal")
  333. }
  334. .toggleStyle(CheckboxToggleStyle())
  335. .font(.footnote)
  336. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  337. state.insulinCalculated = state.calculateInsulin()
  338. if state.useFattyMealCorrectionFactor {
  339. state.useSuperBolus = false
  340. }
  341. }
  342. }
  343. if state.sweetMeals {
  344. Spacer()
  345. Toggle(isOn: $state.useSuperBolus) {
  346. Text("Super Bolus")
  347. }
  348. .toggleStyle(CheckboxToggleStyle())
  349. .font(.footnote)
  350. .onChange(of: state.useSuperBolus) { _ in
  351. state.insulinCalculated = state.calculateInsulin()
  352. if state.useSuperBolus {
  353. state.useFattyMealCorrectionFactor = false
  354. }
  355. }
  356. }
  357. }
  358. HStack {
  359. Text("Recommended Bolus")
  360. Spacer()
  361. Text(
  362. formatter
  363. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  364. )
  365. Text(
  366. NSLocalizedString(
  367. " U",
  368. comment: "Unit in number of units delivered (keep the space character!)"
  369. )
  370. ).foregroundColor(.secondary)
  371. }.contentShape(Rectangle())
  372. .onTapGesture { state.amount = state.insulinCalculated }
  373. HStack {
  374. Text("Bolus")
  375. Spacer()
  376. DecimalTextField(
  377. "0",
  378. value: $state.amount,
  379. formatter: formatter,
  380. autofocus: false,
  381. cleanInput: true,
  382. textColor: .systemBlue
  383. )
  384. Text(" U").foregroundColor(.secondary)
  385. }
  386. if state.amount > 0 {
  387. HStack {
  388. Text("External insulin")
  389. Spacer()
  390. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  391. }
  392. }
  393. }.listRowBackground(Color.chart)
  394. }
  395. }.safeAreaInset(edge: .bottom, spacing: 0) {
  396. stickyButton
  397. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  398. if state.waitForSuggestion {
  399. CustomProgressView(text: progressText.rawValue)
  400. }
  401. }
  402. .scrollContentBackground(.hidden).background(color)
  403. .blur(radius: showInfo ? 3 : 0)
  404. .navigationTitle("Treatments")
  405. .navigationBarTitleDisplayMode(.inline)
  406. .toolbar(content: {
  407. ToolbarItem(placement: .topBarLeading) {
  408. Button {
  409. state.hideModal()
  410. } label: {
  411. Text("Close")
  412. }
  413. }
  414. })
  415. .onAppear {
  416. configureView {
  417. state.insulinCalculated = state.calculateInsulin()
  418. }
  419. }
  420. .onDisappear {
  421. state.addButtonPressed = false
  422. }
  423. .sheet(isPresented: $showInfo) {
  424. calculationsDetailView
  425. .presentationDetents(
  426. [.fraction(0.9), .large],
  427. selection: $calculatorDetent
  428. )
  429. }
  430. }
  431. var progressText: ProgressText {
  432. switch (state.amount > 0, state.carbs > 0) {
  433. case (true, true):
  434. return .updatingIOBandCOB
  435. case (false, true):
  436. return .updatingCOB
  437. case (true, false):
  438. return .updatingIOB
  439. default:
  440. return .updatingTreatments
  441. }
  442. }
  443. var stickyButton: some View {
  444. ZStack {
  445. Rectangle()
  446. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  447. .shadow(
  448. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  449. Color.black.opacity(0.33),
  450. radius: 3
  451. )
  452. .foregroundStyle(Color.chart)
  453. Button {
  454. state.invokeTreatmentsTask()
  455. } label: {
  456. taskButtonLabel
  457. .font(.headline)
  458. .foregroundStyle(Color.white)
  459. .frame(maxWidth: .infinity, alignment: .center)
  460. .frame(minHeight: 50)
  461. }
  462. .disabled(disableTaskButton)
  463. .background(
  464. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  465. Color(.systemBlue)
  466. )
  467. .shadow(radius: 3)
  468. .clipShape(RoundedRectangle(cornerRadius: 8))
  469. .padding()
  470. .offset(y: 20)
  471. }
  472. }
  473. var calcSettingsFirstRow: some View {
  474. GridRow {
  475. Group {
  476. Text("Carb Ratio:")
  477. .foregroundColor(.secondary)
  478. }.gridCellAnchor(.leading)
  479. Group {
  480. Text("ISF:")
  481. .foregroundColor(.secondary)
  482. }.gridCellAnchor(.leading)
  483. VStack {
  484. Text("Target:")
  485. .foregroundColor(.secondary)
  486. }.gridCellAnchor(.leading)
  487. }
  488. }
  489. var calcSettingsSecondRow: some View {
  490. GridRow {
  491. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  492. .gridCellAnchor(.leading)
  493. Text(
  494. state.isf.formatted() + " " + state.units
  495. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  496. ).gridCellAnchor(.leading)
  497. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  498. Text(
  499. target
  500. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  501. " " + state.units.rawValue
  502. ).gridCellAnchor(.leading)
  503. }
  504. }
  505. var calcGlucoseFirstRow: some View {
  506. GridRow(alignment: .center) {
  507. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  508. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  509. Text("Glucose:").foregroundColor(.secondary)
  510. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  511. let firstRow = currentBG
  512. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  513. + " - " +
  514. target
  515. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  516. + " = " +
  517. targetDifference
  518. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  519. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  520. .gridColumnAlignment(.leading)
  521. HStack {
  522. Text(
  523. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  524. )
  525. Text("U").foregroundColor(.secondary)
  526. }.fontWeight(.bold)
  527. .gridColumnAlignment(.trailing)
  528. }
  529. }
  530. var calcGlucoseSecondRow: some View {
  531. GridRow(alignment: .center) {
  532. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  533. Text(
  534. currentBG
  535. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  536. " " +
  537. state.units.rawValue
  538. )
  539. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  540. let secondRow = targetDifference
  541. .formatted(
  542. .number.grouping(.never).rounded()
  543. .precision(.fractionLength(fractionDigits))
  544. )
  545. + " / " +
  546. state.isf.formatted()
  547. + " ≈ " +
  548. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  549. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  550. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  551. }
  552. }
  553. var calcGlucoseFormulaRow: some View {
  554. GridRow(alignment: .top) {
  555. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  556. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  557. .gridColumnAlignment(.leading)
  558. .gridCellColumns(2)
  559. }
  560. .font(.caption)
  561. }
  562. var calcIOBRow: some View {
  563. GridRow(alignment: .center) {
  564. HStack {
  565. Text("IOB:").foregroundColor(.secondary)
  566. Text(
  567. self.insulinRounder(state.iob).formatted()
  568. )
  569. }
  570. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  571. let iobFormatted = self.insulinRounder(state.iob).formatted()
  572. HStack {
  573. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  574. Text("U").foregroundColor(.secondary)
  575. }.fontWeight(.bold)
  576. .gridColumnAlignment(.trailing)
  577. }
  578. }
  579. var calcCOBRow: some View {
  580. GridRow(alignment: .center) {
  581. HStack {
  582. Text("COB:").foregroundColor(.secondary)
  583. Text(
  584. state.wholeCob
  585. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  586. NSLocalizedString(" g", comment: "grams")
  587. )
  588. }
  589. Text(
  590. state.wholeCob
  591. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  592. + " / " +
  593. state.carbRatio.formatted()
  594. + " ≈ " +
  595. self.insulinRounder(state.wholeCobInsulin).formatted()
  596. )
  597. .foregroundColor(.secondary)
  598. .gridColumnAlignment(.leading)
  599. HStack {
  600. Text(
  601. self.insulinRounder(state.wholeCobInsulin).formatted()
  602. )
  603. Text("U").foregroundColor(.secondary)
  604. }.fontWeight(.bold)
  605. .gridColumnAlignment(.trailing)
  606. }
  607. }
  608. var calcCOBFormulaRow: some View {
  609. GridRow(alignment: .center) {
  610. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  611. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  612. .gridColumnAlignment(.leading)
  613. .gridCellColumns(2)
  614. }
  615. .font(.caption)
  616. }
  617. var calcDeltaRow: some View {
  618. GridRow(alignment: .center) {
  619. Text("Delta:").foregroundColor(.secondary)
  620. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  621. Text(
  622. deltaBG
  623. .formatted(
  624. .number.grouping(.never).rounded()
  625. .precision(.fractionLength(fractionDigits))
  626. )
  627. + " / " +
  628. state.isf.formatted()
  629. + " ≈ " +
  630. self.insulinRounder(state.fifteenMinInsulin).formatted()
  631. )
  632. .foregroundColor(.secondary)
  633. .gridColumnAlignment(.leading)
  634. HStack {
  635. Text(
  636. self.insulinRounder(state.fifteenMinInsulin).formatted()
  637. )
  638. Text("U").foregroundColor(.secondary)
  639. }.fontWeight(.bold)
  640. .gridColumnAlignment(.trailing)
  641. }
  642. }
  643. var calcDeltaFormulaRow: some View {
  644. GridRow(alignment: .center) {
  645. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  646. Text(
  647. deltaBG
  648. .formatted(
  649. .number.grouping(.never).rounded()
  650. .precision(.fractionLength(fractionDigits))
  651. ) + " " +
  652. state.units.rawValue
  653. )
  654. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  655. .gridColumnAlignment(.leading)
  656. .gridCellColumns(2).padding(.top, 5)
  657. }
  658. }
  659. var calcFullBolusRow: some View {
  660. GridRow(alignment: .center) {
  661. Text("Full Bolus")
  662. .foregroundColor(.secondary)
  663. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  664. HStack {
  665. Text(self.insulinRounder(state.wholeCalc).formatted())
  666. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  667. Text("U").foregroundColor(.secondary)
  668. }.gridColumnAlignment(.trailing)
  669. .fontWeight(.bold)
  670. }
  671. }
  672. var calcSuperBolusRow: some View {
  673. GridRow(alignment: .center) {
  674. Text("Super Bolus")
  675. .foregroundColor(.secondary)
  676. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  677. HStack {
  678. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  679. .foregroundStyle(Color.loopRed)
  680. Text("U").foregroundColor(.secondary)
  681. }.gridColumnAlignment(.trailing)
  682. .fontWeight(.bold)
  683. }
  684. }
  685. var calcResultRow: some View {
  686. GridRow(alignment: .center) {
  687. Text("Result").fontWeight(.bold)
  688. HStack {
  689. Text(state.useSuperBolus ? "(" : "")
  690. .foregroundColor(.loopRed)
  691. + Text(state.fraction.formatted())
  692. + Text(" x ")
  693. .foregroundColor(.secondary)
  694. // if fatty meal is chosen
  695. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  696. .foregroundColor(.orange)
  697. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  698. .foregroundColor(.secondary)
  699. // endif fatty meal is chosen
  700. + Text(self.insulinRounder(state.wholeCalc).formatted())
  701. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  702. // if superbolus is chosen
  703. + Text(state.useSuperBolus ? ")" : "")
  704. .foregroundColor(.loopRed)
  705. + Text(state.useSuperBolus ? " + " : "")
  706. .foregroundColor(.secondary)
  707. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  708. .foregroundColor(.loopRed)
  709. // endif superbolus is chosen
  710. + Text(" ≈ ")
  711. .foregroundColor(.secondary)
  712. }
  713. .gridColumnAlignment(.leading)
  714. HStack {
  715. Text(self.insulinRounder(state.insulinCalculated).formatted())
  716. .fontWeight(.bold)
  717. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  718. Text("U").foregroundColor(.secondary)
  719. }
  720. .gridColumnAlignment(.trailing)
  721. .fontWeight(.bold)
  722. }
  723. }
  724. var calcResultFormulaRow: some View {
  725. GridRow(alignment: .bottom) {
  726. if state.useFattyMealCorrectionFactor {
  727. Group {
  728. Text("Factor x Fatty Meal Factor x Full Bolus")
  729. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  730. +
  731. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  732. }
  733. .font(.caption)
  734. .gridCellAnchor(.center)
  735. .gridCellColumns(3)
  736. } else if state.useSuperBolus {
  737. Group {
  738. Text("(Factor x Full Bolus) + Super Bolus")
  739. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  740. +
  741. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  742. }
  743. .font(.caption)
  744. .gridCellAnchor(.center)
  745. .gridCellColumns(3)
  746. } else {
  747. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  748. Group {
  749. Text("Factor x Full Bolus")
  750. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  751. +
  752. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  753. }
  754. .font(.caption)
  755. .padding(.top, 5)
  756. .gridCellAnchor(.leading)
  757. .gridCellColumns(2)
  758. }
  759. }
  760. }
  761. var calculationsDetailView: some View {
  762. NavigationStack {
  763. ScrollView {
  764. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  765. GridRow {
  766. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  767. }
  768. calcSettingsFirstRow
  769. calcSettingsSecondRow
  770. DividerCustom()
  771. // meal entries as grid rows
  772. if state.carbs > 0 {
  773. GridRow {
  774. Text("Carbs").foregroundColor(.secondary)
  775. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  776. HStack {
  777. Text(state.carbs.formatted())
  778. Text("g").foregroundColor(.secondary)
  779. }.gridCellAnchor(.trailing)
  780. }
  781. }
  782. if state.fat > 0 {
  783. GridRow {
  784. Text("Fat").foregroundColor(.secondary)
  785. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  786. HStack {
  787. Text(state.fat.formatted())
  788. Text("g").foregroundColor(.secondary)
  789. }.gridCellAnchor(.trailing)
  790. }
  791. }
  792. if state.protein > 0 {
  793. GridRow {
  794. Text("Protein").foregroundColor(.secondary)
  795. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  796. HStack {
  797. Text(state.protein.formatted())
  798. Text("g").foregroundColor(.secondary)
  799. }.gridCellAnchor(.trailing)
  800. }
  801. }
  802. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  803. DividerCustom()
  804. }
  805. GridRow {
  806. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  807. .padding(.bottom, 10)
  808. }
  809. calcGlucoseFirstRow
  810. calcGlucoseSecondRow.padding(.bottom, 5)
  811. calcGlucoseFormulaRow
  812. DividerCustom()
  813. calcIOBRow
  814. DividerCustom()
  815. calcCOBRow.padding(.bottom, 5)
  816. calcCOBFormulaRow
  817. DividerCustom()
  818. calcDeltaRow
  819. calcDeltaFormulaRow
  820. DividerCustom()
  821. calcFullBolusRow
  822. if state.useSuperBolus {
  823. DividerCustom()
  824. calcSuperBolusRow
  825. }
  826. DividerDouble()
  827. calcResultRow
  828. calcResultFormulaRow
  829. }
  830. Spacer()
  831. Button { showInfo = false }
  832. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  833. .buttonStyle(.bordered)
  834. .padding(.top)
  835. }
  836. .padding([.horizontal, .bottom])
  837. .font(.subheadline)
  838. }
  839. }
  840. private func insulinRounder(_ value: Decimal) -> Decimal {
  841. let toRound = NSDecimalNumber(decimal: value).doubleValue
  842. return Decimal(floor(100 * toRound) / 100)
  843. }
  844. private var taskButtonLabel: some View {
  845. let hasInsulin = state.amount > 0
  846. let hasCarbs = state.carbs > 0
  847. let hasFatOrProtein = state.fat > 0 || state.protein > 0
  848. switch (hasInsulin, hasCarbs, hasFatOrProtein) {
  849. case (true, true, true):
  850. return Text(
  851. state
  852. .externalInsulin ? (
  853. externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log meal and external insulin"
  854. ) :
  855. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log meal and enact bolus")
  856. )
  857. case (true, true, false):
  858. return Text(
  859. state
  860. .externalInsulin ?
  861. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log carbs and external insulin") :
  862. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log carbs and enact bolus")
  863. )
  864. case (true, false, true):
  865. return Text(
  866. state
  867. .externalInsulin ?
  868. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log FPUs and external insulin") :
  869. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Log FPUs and enact bolus")
  870. )
  871. case (true, false, false):
  872. return Text(
  873. state
  874. .externalInsulin ? (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin") :
  875. (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus")
  876. )
  877. case (false, true, true):
  878. return Text("Log meal")
  879. case (false, true, false):
  880. return Text("Log carbs")
  881. case (false, false, true):
  882. return Text("Log FPUs")
  883. default:
  884. return Text("Continue without treatment")
  885. }
  886. }
  887. private var pumpBolusLimit: Bool {
  888. state.amount > state.maxBolus
  889. }
  890. private var externalBolusLimit: Bool {
  891. state.amount > state.maxBolus * 3
  892. }
  893. private var disableTaskButton: Bool {
  894. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  895. }
  896. }
  897. struct DividerDouble: View {
  898. var body: some View {
  899. VStack(spacing: 2) {
  900. Rectangle()
  901. .frame(height: 1)
  902. .foregroundColor(.gray.opacity(0.65))
  903. Rectangle()
  904. .frame(height: 1)
  905. .foregroundColor(.gray.opacity(0.65))
  906. }
  907. .frame(height: 4)
  908. .padding(.vertical)
  909. }
  910. }
  911. struct DividerCustom: View {
  912. var body: some View {
  913. Rectangle()
  914. .frame(height: 1)
  915. .foregroundColor(.gray.opacity(0.65))
  916. .padding(.vertical)
  917. }
  918. }
  919. }