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