AlternativeBolusCalcRootView.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. ZStack(alignment: .center) {
  239. VStack {
  240. Form {
  241. Section {
  242. HStack {
  243. Text("Carbs").fontWeight(.semibold)
  244. Spacer()
  245. DecimalTextField(
  246. "0",
  247. value: $state.carbs,
  248. formatter: formatter,
  249. autofocus: false,
  250. cleanInput: true
  251. )
  252. Text("g").foregroundColor(.secondary)
  253. }
  254. if state.useFPUconversion {
  255. proteinAndFat()
  256. }
  257. // Summary when combining presets
  258. if state.waitersNotepad() != "" {
  259. HStack {
  260. Text("Total")
  261. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  262. HStack(spacing: 0) {
  263. ForEach(test, id: \.self) {
  264. Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
  265. Text($0 == test[test.count - 1] ? "" : ", ")
  266. }
  267. }.frame(maxWidth: .infinity, alignment: .trailing)
  268. }
  269. }
  270. // Time
  271. HStack {
  272. Text("Time").foregroundStyle(Color.secondary)
  273. Spacer()
  274. if !pushed {
  275. Button {
  276. pushed = true
  277. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  278. .padding(.trailing, 5)
  279. } else {
  280. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  281. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  282. DatePicker(
  283. "Time",
  284. selection: $state.date,
  285. displayedComponents: [.hourAndMinute]
  286. ).controlSize(.mini)
  287. .labelsHidden()
  288. Button {
  289. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  290. }
  291. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  292. }
  293. }
  294. .popover(isPresented: $isPromptPresented) {
  295. presetPopover
  296. }
  297. HStack {
  298. Spacer()
  299. Button {
  300. isCalculating = true
  301. state.insulinCalculated = state.calculateInsulin()
  302. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  303. isCalculating = false
  304. }
  305. }
  306. label: {
  307. if !isCalculating {
  308. Text("Calculate")
  309. } else {
  310. ProgressView().progressViewStyle(CircularProgressViewStyle())
  311. }
  312. }.disabled(empty)
  313. Spacer()
  314. }
  315. }
  316. if state.displayPresets {
  317. Section {
  318. mealPresets
  319. }.listRowBackground(Color.chart)
  320. }
  321. Section {
  322. HStack {
  323. Button(action: {
  324. showInfo.toggle()
  325. }, label: {
  326. Image(systemName: "info.circle")
  327. Text("Calculations")
  328. })
  329. .foregroundStyle(.blue)
  330. .font(.footnote)
  331. .buttonStyle(PlainButtonStyle())
  332. .frame(maxWidth: .infinity, alignment: .leading)
  333. if state.fattyMeals {
  334. Spacer()
  335. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  336. Text("Fatty Meal")
  337. }
  338. .toggleStyle(CheckboxToggleStyle())
  339. .font(.footnote)
  340. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  341. state.insulinCalculated = state.calculateInsulin()
  342. if state.useFattyMealCorrectionFactor {
  343. state.useSuperBolus = false
  344. }
  345. }
  346. }
  347. if state.sweetMeals {
  348. Spacer()
  349. Toggle(isOn: $state.useSuperBolus) {
  350. Text("Super Bolus")
  351. }
  352. .toggleStyle(CheckboxToggleStyle())
  353. .font(.footnote)
  354. .onChange(of: state.useSuperBolus) { _ in
  355. state.insulinCalculated = state.calculateInsulin()
  356. if state.useSuperBolus {
  357. state.useFattyMealCorrectionFactor = false
  358. }
  359. }
  360. }
  361. }
  362. HStack {
  363. Text("Recommended Bolus")
  364. Spacer()
  365. Text(
  366. formatter
  367. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  368. )
  369. Text(
  370. NSLocalizedString(
  371. " U",
  372. comment: "Unit in number of units delivered (keep the space character!)"
  373. )
  374. ).foregroundColor(.secondary)
  375. }.contentShape(Rectangle())
  376. .onTapGesture { state.amount = state.insulinCalculated }
  377. HStack {
  378. Text("Bolus")
  379. Spacer()
  380. DecimalTextField(
  381. "0",
  382. value: $state.amount,
  383. formatter: formatter,
  384. autofocus: false,
  385. cleanInput: true
  386. )
  387. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  388. }
  389. .onChange(of: state.amount) { newValue in
  390. if newValue > state.maxBolus {
  391. exceededMaxBolus = true
  392. } else {
  393. exceededMaxBolus = false
  394. }
  395. }
  396. }
  397. if state.amount > 0 {
  398. Section {
  399. HStack {
  400. Text("External insulin")
  401. Spacer()
  402. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  403. }
  404. }
  405. }
  406. }
  407. }.safeAreaInset(edge: .bottom, spacing: 0) {
  408. if state.amount > 0 {
  409. Section {
  410. Button {
  411. if !state.externalInsulin {
  412. Task {
  413. await state.add()
  414. state.waitForSuggestion = true
  415. state.addCarbs()
  416. state.addButtonPressed = true
  417. }
  418. } else {
  419. Task {
  420. do {
  421. await state.addExternalInsulin()
  422. state.waitForSuggestion = true
  423. state.addCarbs()
  424. state.addButtonPressed = true
  425. }
  426. }
  427. }
  428. }
  429. label: {
  430. if !state.externalInsulin {
  431. Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus")
  432. } else {
  433. Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Log external insulin")
  434. }
  435. }
  436. .frame(maxWidth: .infinity, alignment: .center)
  437. .frame(minHeight: 50)
  438. .disabled(state.externalInsulin ? limitManualBolus : limitPumpBolus)
  439. .background(logExternalInsulinBackground)
  440. .clipShape(RoundedRectangle(cornerRadius: 8))
  441. .tint(logExternalInsulinForeground)
  442. .padding()
  443. } header: {
  444. if state.amount > state.maxBolus
  445. {
  446. Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
  447. }
  448. }
  449. }
  450. if state.amount <= 0 {
  451. Section {
  452. Button {
  453. // show loading bar only when carbs are actually added
  454. if state.carbs > 0 {
  455. state.addCarbs()
  456. state.waitForSuggestion = true
  457. } else {
  458. // hide modal because its otherwise only hided after a suggestion update, see StateModal
  459. state.hideModal()
  460. }
  461. state.addButtonPressed = true
  462. }
  463. label: { Text("Continue without bolus") }
  464. .frame(maxWidth: .infinity, alignment: .center)
  465. .frame(minHeight: 50)
  466. .background(Color(.systemBlue))
  467. .clipShape(RoundedRectangle(cornerRadius: 8))
  468. .tint(.white)
  469. .padding()
  470. }.listRowBackground(Color.chart)
  471. }
  472. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  473. if state.waitForSuggestion {
  474. CustomProgressView(text: progressText)
  475. }
  476. }
  477. .scrollContentBackground(.hidden).background(color)
  478. .blur(radius: showInfo ? 3 : 0)
  479. .navigationTitle("Treatments")
  480. .navigationBarTitleDisplayMode(.inline)
  481. .toolbar(content: {
  482. ToolbarItem(placement: .topBarLeading) {
  483. Button {
  484. state.hideModal()
  485. } label: {
  486. Text("Close")
  487. }
  488. }
  489. })
  490. .onAppear {
  491. configureView {
  492. state.insulinCalculated = state.calculateInsulin()
  493. }
  494. }
  495. .onDisappear {
  496. state.addButtonPressed = false
  497. }
  498. .sheet(isPresented: $showInfo) {
  499. calculationsDetailView
  500. .presentationDetents(
  501. [.fraction(0.9), .large],
  502. selection: $calculatorDetent
  503. )
  504. }
  505. }
  506. var progressText: String {
  507. switch (state.amount > 0, state.carbs > 0) {
  508. case (true, true):
  509. return "Updating COB and IOB..."
  510. case (false, true):
  511. return "Updating COB..."
  512. case (true, false):
  513. return "Updating IOB..."
  514. default:
  515. return "Updating Treatments..."
  516. }
  517. }
  518. var calcSettingsFirstRow: some View {
  519. GridRow {
  520. Group {
  521. Text("Carb Ratio:")
  522. .foregroundColor(.secondary)
  523. }.gridCellAnchor(.leading)
  524. Group {
  525. Text("ISF:")
  526. .foregroundColor(.secondary)
  527. }.gridCellAnchor(.leading)
  528. VStack {
  529. Text("Target:")
  530. .foregroundColor(.secondary)
  531. }.gridCellAnchor(.leading)
  532. }
  533. }
  534. var calcSettingsSecondRow: some View {
  535. GridRow {
  536. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  537. .gridCellAnchor(.leading)
  538. Text(
  539. state.isf.formatted() + " " + state.units
  540. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  541. ).gridCellAnchor(.leading)
  542. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  543. Text(
  544. target
  545. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  546. " " + state.units.rawValue
  547. ).gridCellAnchor(.leading)
  548. }
  549. }
  550. var calcGlucoseFirstRow: some View {
  551. GridRow(alignment: .center) {
  552. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  553. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  554. Text("Glucose:").foregroundColor(.secondary)
  555. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  556. let firstRow = currentBG
  557. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  558. + " - " +
  559. target
  560. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  561. + " = " +
  562. targetDifference
  563. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  564. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  565. .gridColumnAlignment(.leading)
  566. HStack {
  567. Text(
  568. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  569. )
  570. Text("U").foregroundColor(.secondary)
  571. }.fontWeight(.bold)
  572. .gridColumnAlignment(.trailing)
  573. }
  574. }
  575. var calcGlucoseSecondRow: some View {
  576. GridRow(alignment: .center) {
  577. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  578. Text(
  579. currentBG
  580. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  581. " " +
  582. state.units.rawValue
  583. )
  584. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  585. let secondRow = targetDifference
  586. .formatted(
  587. .number.grouping(.never).rounded()
  588. .precision(.fractionLength(fractionDigits))
  589. )
  590. + " / " +
  591. state.isf.formatted()
  592. + " ≈ " +
  593. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  594. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  595. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  596. }
  597. }
  598. var calcGlucoseFormulaRow: some View {
  599. GridRow(alignment: .top) {
  600. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  601. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  602. .gridColumnAlignment(.leading)
  603. .gridCellColumns(2)
  604. }
  605. .font(.caption)
  606. }
  607. var calcIOBRow: some View {
  608. GridRow(alignment: .center) {
  609. HStack {
  610. Text("IOB:").foregroundColor(.secondary)
  611. Text(
  612. self.insulinRounder(state.iob).formatted()
  613. )
  614. }
  615. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  616. let iobFormatted = self.insulinRounder(state.iob).formatted()
  617. HStack {
  618. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  619. Text("U").foregroundColor(.secondary)
  620. }.fontWeight(.bold)
  621. .gridColumnAlignment(.trailing)
  622. }
  623. }
  624. var calcCOBRow: some View {
  625. GridRow(alignment: .center) {
  626. HStack {
  627. Text("COB:").foregroundColor(.secondary)
  628. Text(
  629. state.wholeCob
  630. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  631. NSLocalizedString(" g", comment: "grams")
  632. )
  633. }
  634. Text(
  635. state.wholeCob
  636. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  637. + " / " +
  638. state.carbRatio.formatted()
  639. + " ≈ " +
  640. self.insulinRounder(state.wholeCobInsulin).formatted()
  641. )
  642. .foregroundColor(.secondary)
  643. .gridColumnAlignment(.leading)
  644. HStack {
  645. Text(
  646. self.insulinRounder(state.wholeCobInsulin).formatted()
  647. )
  648. Text("U").foregroundColor(.secondary)
  649. }.fontWeight(.bold)
  650. .gridColumnAlignment(.trailing)
  651. }
  652. }
  653. var calcCOBFormulaRow: some View {
  654. GridRow(alignment: .center) {
  655. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  656. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  657. .gridColumnAlignment(.leading)
  658. .gridCellColumns(2)
  659. }
  660. .font(.caption)
  661. }
  662. var calcDeltaRow: some View {
  663. GridRow(alignment: .center) {
  664. Text("Delta:").foregroundColor(.secondary)
  665. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  666. Text(
  667. deltaBG
  668. .formatted(
  669. .number.grouping(.never).rounded()
  670. .precision(.fractionLength(fractionDigits))
  671. )
  672. + " / " +
  673. state.isf.formatted()
  674. + " ≈ " +
  675. self.insulinRounder(state.fifteenMinInsulin).formatted()
  676. )
  677. .foregroundColor(.secondary)
  678. .gridColumnAlignment(.leading)
  679. HStack {
  680. Text(
  681. self.insulinRounder(state.fifteenMinInsulin).formatted()
  682. )
  683. Text("U").foregroundColor(.secondary)
  684. }.fontWeight(.bold)
  685. .gridColumnAlignment(.trailing)
  686. }
  687. }
  688. var calcDeltaFormulaRow: some View {
  689. GridRow(alignment: .center) {
  690. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  691. Text(
  692. deltaBG
  693. .formatted(
  694. .number.grouping(.never).rounded()
  695. .precision(.fractionLength(fractionDigits))
  696. ) + " " +
  697. state.units.rawValue
  698. )
  699. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  700. .gridColumnAlignment(.leading)
  701. .gridCellColumns(2).padding(.top, 5)
  702. }
  703. }
  704. var calcFullBolusRow: some View {
  705. GridRow(alignment: .center) {
  706. Text("Full Bolus")
  707. .foregroundColor(.secondary)
  708. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  709. HStack {
  710. Text(self.insulinRounder(state.wholeCalc).formatted())
  711. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  712. Text("U").foregroundColor(.secondary)
  713. }.gridColumnAlignment(.trailing)
  714. .fontWeight(.bold)
  715. }
  716. }
  717. var calcSuperBolusRow: some View {
  718. GridRow(alignment: .center) {
  719. Text("Super Bolus")
  720. .foregroundColor(.secondary)
  721. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  722. HStack {
  723. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  724. .foregroundStyle(Color.loopRed)
  725. Text("U").foregroundColor(.secondary)
  726. }.gridColumnAlignment(.trailing)
  727. .fontWeight(.bold)
  728. }
  729. }
  730. var calcResultRow: some View {
  731. GridRow(alignment: .center) {
  732. Text("Result").fontWeight(.bold)
  733. HStack {
  734. Text(state.useSuperBolus ? "(" : "")
  735. .foregroundColor(.loopRed)
  736. + Text(state.fraction.formatted())
  737. + Text(" x ")
  738. .foregroundColor(.secondary)
  739. // if fatty meal is chosen
  740. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  741. .foregroundColor(.orange)
  742. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  743. .foregroundColor(.secondary)
  744. // endif fatty meal is chosen
  745. + Text(self.insulinRounder(state.wholeCalc).formatted())
  746. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  747. // if superbolus is chosen
  748. + Text(state.useSuperBolus ? ")" : "")
  749. .foregroundColor(.loopRed)
  750. + Text(state.useSuperBolus ? " + " : "")
  751. .foregroundColor(.secondary)
  752. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  753. .foregroundColor(.loopRed)
  754. // endif superbolus is chosen
  755. + Text(" ≈ ")
  756. .foregroundColor(.secondary)
  757. }
  758. .gridColumnAlignment(.leading)
  759. HStack {
  760. Text(self.insulinRounder(state.insulinCalculated).formatted())
  761. .fontWeight(.bold)
  762. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  763. Text("U").foregroundColor(.secondary)
  764. }
  765. .gridColumnAlignment(.trailing)
  766. .fontWeight(.bold)
  767. }
  768. }
  769. var calcResultFormulaRow: some View {
  770. GridRow(alignment: .bottom) {
  771. if state.useFattyMealCorrectionFactor {
  772. Group {
  773. Text("Factor x Fatty Meal Factor x Full Bolus")
  774. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  775. +
  776. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  777. }
  778. .font(.caption)
  779. .gridCellAnchor(.center)
  780. .gridCellColumns(3)
  781. } else if state.useSuperBolus {
  782. Group {
  783. Text("(Factor x Full Bolus) + Super Bolus")
  784. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  785. +
  786. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  787. }
  788. .font(.caption)
  789. .gridCellAnchor(.center)
  790. .gridCellColumns(3)
  791. } else {
  792. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  793. Group {
  794. Text("Factor x Full Bolus")
  795. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  796. +
  797. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  798. }
  799. .font(.caption)
  800. .padding(.top, 5)
  801. .gridCellAnchor(.leading)
  802. .gridCellColumns(2)
  803. }
  804. }
  805. }
  806. var calculationsDetailView: some View {
  807. NavigationStack {
  808. ScrollView {
  809. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  810. GridRow {
  811. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  812. }
  813. calcSettingsFirstRow
  814. calcSettingsSecondRow
  815. DividerCustom()
  816. // meal entries as grid rows
  817. if state.carbs > 0 {
  818. GridRow {
  819. Text("Carbs").foregroundColor(.secondary)
  820. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  821. HStack {
  822. Text(state.carbs.formatted())
  823. Text("g").foregroundColor(.secondary)
  824. }.gridCellAnchor(.trailing)
  825. }
  826. }
  827. if state.fat > 0 {
  828. GridRow {
  829. Text("Fat").foregroundColor(.secondary)
  830. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  831. HStack {
  832. Text(state.fat.formatted())
  833. Text("g").foregroundColor(.secondary)
  834. }.gridCellAnchor(.trailing)
  835. }
  836. }
  837. if state.protein > 0 {
  838. GridRow {
  839. Text("Protein").foregroundColor(.secondary)
  840. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  841. HStack {
  842. Text(state.protein.formatted())
  843. Text("g").foregroundColor(.secondary)
  844. }.gridCellAnchor(.trailing)
  845. }
  846. }
  847. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  848. DividerCustom()
  849. }
  850. GridRow {
  851. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  852. .padding(.bottom, 10)
  853. }
  854. calcGlucoseFirstRow
  855. calcGlucoseSecondRow.padding(.bottom, 5)
  856. calcGlucoseFormulaRow
  857. DividerCustom()
  858. calcIOBRow
  859. DividerCustom()
  860. calcCOBRow.padding(.bottom, 5)
  861. calcCOBFormulaRow
  862. DividerCustom()
  863. calcDeltaRow
  864. calcDeltaFormulaRow
  865. DividerCustom()
  866. calcFullBolusRow
  867. if state.useSuperBolus {
  868. DividerCustom()
  869. calcSuperBolusRow
  870. }
  871. DividerDouble()
  872. calcResultRow
  873. calcResultFormulaRow
  874. }
  875. Spacer()
  876. Button { showInfo = false }
  877. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  878. .buttonStyle(.bordered)
  879. .padding(.top)
  880. }
  881. .padding([.horizontal, .bottom])
  882. .font(.system(size: 15))
  883. }
  884. }
  885. private func insulinRounder(_ value: Decimal) -> Decimal {
  886. let toRound = NSDecimalNumber(decimal: value).doubleValue
  887. return Decimal(floor(100 * toRound) / 100)
  888. }
  889. private var limitPumpBolus: Bool {
  890. state.amount <= 0 || state.amount > state.maxBolus
  891. }
  892. // MARK: DEFINITIONS FOR ADDING EXTERNAL INSULIN
  893. private var limitManualBolus: Bool {
  894. state.amount <= 0 || state.amount > state.maxBolus * 3
  895. }
  896. private var logExternalInsulinBackground: Color {
  897. if state.amount > state.maxBolus {
  898. return Color.red
  899. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  900. return Color(.systemGray4)
  901. } else {
  902. return Color(.systemBlue)
  903. }
  904. }
  905. private var logExternalInsulinForeground: Color {
  906. if state.amount > state.maxBolus {
  907. return Color.white
  908. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  909. return Color.secondary
  910. } else {
  911. return Color.white
  912. }
  913. }
  914. }
  915. struct DividerDouble: View {
  916. var body: some View {
  917. VStack(spacing: 2) {
  918. Rectangle()
  919. .frame(height: 1)
  920. .foregroundColor(.gray.opacity(0.65))
  921. Rectangle()
  922. .frame(height: 1)
  923. .foregroundColor(.gray.opacity(0.65))
  924. }
  925. .frame(height: 4)
  926. .padding(.vertical)
  927. }
  928. }
  929. struct DividerCustom: View {
  930. var body: some View {
  931. Rectangle()
  932. .frame(height: 1)
  933. .foregroundColor(.gray.opacity(0.65))
  934. .padding(.vertical)
  935. }
  936. }
  937. }