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