AlternativeBolusCalcRootView.swift 42 KB

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