AlternativeBolusCalcRootView.swift 40 KB

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