AlternativeBolusCalcRootView.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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. @StateObject var state: StateModel
  10. @State private var showInfo = false
  11. @State private var showAlert = false
  12. @State private var exceededMaxBolus = false
  13. @State private var autofocus: Bool = true
  14. @State private var calculatorDetent = PresentationDetent.medium
  15. @State var pushed = false
  16. @State var isPromptPresented = false
  17. @State var dish: String = ""
  18. @State var saved = 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: true,
  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. // to do
  299. state.insulinCalculated = state.calculateInsulin()
  300. }
  301. label: {
  302. Text("Calculate")
  303. }.disabled(empty)
  304. Spacer()
  305. }
  306. } header: { Text("Carbs") }.listRowBackground(Color.chart)
  307. Section {
  308. mealPresets
  309. }.listRowBackground(Color.chart)
  310. // MARK: ADDING END
  311. Section {
  312. HStack {
  313. Button(action: {
  314. showInfo.toggle()
  315. }, label: {
  316. Image(systemName: "info.circle")
  317. Text("Calculations")
  318. })
  319. .foregroundStyle(.blue)
  320. .font(.footnote)
  321. .buttonStyle(PlainButtonStyle())
  322. .frame(maxWidth: .infinity, alignment: .leading)
  323. if state.fattyMeals {
  324. Spacer()
  325. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  326. Text("Fatty Meal")
  327. }
  328. .toggleStyle(CheckboxToggleStyle())
  329. .font(.footnote)
  330. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  331. state.insulinCalculated = state.calculateInsulin()
  332. if state.useFattyMealCorrectionFactor {
  333. state.useSuperBolus = false
  334. }
  335. }
  336. }
  337. if state.sweetMeals {
  338. Spacer()
  339. Toggle(isOn: $state.useSuperBolus) {
  340. Text("Super Bolus")
  341. }
  342. .toggleStyle(CheckboxToggleStyle())
  343. .font(.footnote)
  344. .onChange(of: state.useSuperBolus) { _ in
  345. state.insulinCalculated = state.calculateInsulin()
  346. if state.useSuperBolus {
  347. state.useFattyMealCorrectionFactor = false
  348. }
  349. }
  350. }
  351. }
  352. HStack {
  353. Text("Recommended Bolus")
  354. Spacer()
  355. Text(
  356. formatter
  357. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  358. )
  359. Text(
  360. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  361. ).foregroundColor(.secondary)
  362. }.contentShape(Rectangle())
  363. .onTapGesture { state.amount = state.insulinCalculated }
  364. HStack {
  365. Text("Bolus")
  366. Spacer()
  367. DecimalTextField(
  368. "0",
  369. value: $state.amount,
  370. formatter: formatter,
  371. autofocus: false,
  372. cleanInput: true
  373. )
  374. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  375. }
  376. .onChange(of: state.amount) { newValue in
  377. if newValue > state.maxBolus {
  378. exceededMaxBolus = true
  379. } else {
  380. exceededMaxBolus = false
  381. }
  382. }
  383. } header: { Text("Bolus") }.listRowBackground(Color.chart)
  384. if state.amount > 0 {
  385. Section {
  386. Button {
  387. state.add()
  388. state.hideModal()
  389. state.addCarbs()
  390. }
  391. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  392. .frame(maxWidth: .infinity, alignment: .center)
  393. .disabled(disabled)
  394. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  395. .tint(.white)
  396. }
  397. }
  398. if state.amount <= 0 {
  399. Section {
  400. Button {
  401. state.hideModal()
  402. state.addCarbs()
  403. }
  404. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  405. }.listRowBackground(Color.chart)
  406. }
  407. }.scrollContentBackground(.hidden).background(color)
  408. .blur(radius: showInfo ? 3 : 0)
  409. .navigationTitle("Treatments")
  410. .navigationBarTitleDisplayMode(.large)
  411. .toolbar(content: {
  412. ToolbarItem(placement: .topBarLeading) {
  413. Button {
  414. state.hideModal()
  415. } label: {
  416. Text("Close")
  417. }
  418. }
  419. })
  420. .onAppear {
  421. configureView {
  422. state.insulinCalculated = state.calculateInsulin()
  423. }
  424. }
  425. .sheet(isPresented: $showInfo) {
  426. calculationsDetailView
  427. .presentationDetents(
  428. [.fraction(0.9), .large],
  429. selection: $calculatorDetent
  430. )
  431. }
  432. }
  433. var predictionChart: some View {
  434. ZStack {
  435. PredictionView(
  436. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  437. displayPredictions: $state.displayPredictions
  438. )
  439. }
  440. }
  441. var calcSettingsFirstRow: some View {
  442. GridRow {
  443. Group {
  444. Text("Carb Ratio:")
  445. .foregroundColor(.secondary)
  446. }.gridCellAnchor(.leading)
  447. Group {
  448. Text("ISF:")
  449. .foregroundColor(.secondary)
  450. }.gridCellAnchor(.leading)
  451. VStack {
  452. Text("Target:")
  453. .foregroundColor(.secondary)
  454. }.gridCellAnchor(.leading)
  455. }
  456. }
  457. var calcSettingsSecondRow: some View {
  458. GridRow {
  459. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  460. .gridCellAnchor(.leading)
  461. Text(
  462. state.isf.formatted() + " " + state.units
  463. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  464. ).gridCellAnchor(.leading)
  465. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  466. Text(
  467. target
  468. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  469. " " + state.units.rawValue
  470. ).gridCellAnchor(.leading)
  471. }
  472. }
  473. var calcGlucoseFirstRow: some View {
  474. GridRow(alignment: .center) {
  475. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  476. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  477. Text("Glucose:").foregroundColor(.secondary)
  478. let firstRow = currentBG
  479. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  480. + " - " +
  481. target
  482. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  483. + " = " +
  484. state.targetDifference
  485. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  486. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  487. .gridColumnAlignment(.leading)
  488. HStack {
  489. Text(
  490. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  491. )
  492. Text("U").foregroundColor(.secondary)
  493. }.fontWeight(.bold)
  494. .gridColumnAlignment(.trailing)
  495. }
  496. }
  497. var calcGlucoseSecondRow: some View {
  498. GridRow(alignment: .center) {
  499. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  500. Text(
  501. currentBG
  502. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  503. " " +
  504. state.units.rawValue
  505. )
  506. let secondRow = state.targetDifference
  507. .formatted(
  508. .number.grouping(.never).rounded()
  509. .precision(.fractionLength(fractionDigits))
  510. )
  511. + " / " +
  512. state.isf.formatted()
  513. + " ≈ " +
  514. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  515. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  516. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  517. }
  518. }
  519. var calcGlucoseFormulaRow: some View {
  520. GridRow(alignment: .top) {
  521. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  522. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  523. .gridColumnAlignment(.leading)
  524. .gridCellColumns(2)
  525. }
  526. .font(.caption)
  527. }
  528. var calcIOBRow: some View {
  529. GridRow(alignment: .center) {
  530. HStack {
  531. Text("IOB:").foregroundColor(.secondary)
  532. Text(
  533. self.insulinRounder(state.iob).formatted()
  534. )
  535. }
  536. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  537. let iobFormatted = self.insulinRounder(state.iob).formatted()
  538. HStack {
  539. Text((state.iob != 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  540. Text("U").foregroundColor(.secondary)
  541. }.fontWeight(.bold)
  542. .gridColumnAlignment(.trailing)
  543. }
  544. }
  545. var calcCOBRow: some View {
  546. GridRow(alignment: .center) {
  547. HStack {
  548. Text("COB:").foregroundColor(.secondary)
  549. Text(
  550. state.wholeCob
  551. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  552. NSLocalizedString(" g", comment: "grams")
  553. )
  554. }
  555. Text(
  556. state.cob
  557. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  558. + " / " +
  559. state.carbRatio.formatted()
  560. + " ≈ " +
  561. self.insulinRounder(state.wholeCobInsulin).formatted()
  562. )
  563. .foregroundColor(.secondary)
  564. .gridColumnAlignment(.leading)
  565. HStack {
  566. Text(
  567. self.insulinRounder(state.wholeCobInsulin).formatted()
  568. )
  569. Text("U").foregroundColor(.secondary)
  570. }.fontWeight(.bold)
  571. .gridColumnAlignment(.trailing)
  572. }
  573. }
  574. var calcCOBFormulaRow: some View {
  575. GridRow(alignment: .center) {
  576. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  577. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  578. .gridColumnAlignment(.leading)
  579. .gridCellColumns(2)
  580. }
  581. .font(.caption)
  582. }
  583. var calcDeltaRow: some View {
  584. GridRow(alignment: .center) {
  585. Text("Delta:").foregroundColor(.secondary)
  586. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  587. Text(
  588. deltaBG
  589. .formatted(
  590. .number.grouping(.never).rounded()
  591. .precision(.fractionLength(fractionDigits))
  592. )
  593. + " / " +
  594. state.isf.formatted()
  595. + " ≈ " +
  596. self.insulinRounder(state.fifteenMinInsulin).formatted()
  597. )
  598. .foregroundColor(.secondary)
  599. .gridColumnAlignment(.leading)
  600. HStack {
  601. Text(
  602. self.insulinRounder(state.fifteenMinInsulin).formatted()
  603. )
  604. Text("U").foregroundColor(.secondary)
  605. }.fontWeight(.bold)
  606. .gridColumnAlignment(.trailing)
  607. }
  608. }
  609. var calcDeltaFormulaRow: some View {
  610. GridRow(alignment: .center) {
  611. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  612. Text(
  613. deltaBG
  614. .formatted(
  615. .number.grouping(.never).rounded()
  616. .precision(.fractionLength(fractionDigits))
  617. ) + " " +
  618. state.units.rawValue
  619. )
  620. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  621. .gridColumnAlignment(.leading)
  622. .gridCellColumns(2).padding(.top, 5)
  623. }
  624. }
  625. var calcFullBolusRow: some View {
  626. GridRow(alignment: .center) {
  627. Text("Full Bolus")
  628. .foregroundColor(.secondary)
  629. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  630. HStack {
  631. Text(self.insulinRounder(state.wholeCalc).formatted())
  632. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  633. Text("U").foregroundColor(.secondary)
  634. }.gridColumnAlignment(.trailing)
  635. .fontWeight(.bold)
  636. }
  637. }
  638. var calcSuperBolusRow: some View {
  639. GridRow(alignment: .center) {
  640. Text("Super Bolus")
  641. .foregroundColor(.secondary)
  642. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  643. HStack {
  644. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  645. .foregroundStyle(Color.loopRed)
  646. Text("U").foregroundColor(.secondary)
  647. }.gridColumnAlignment(.trailing)
  648. .fontWeight(.bold)
  649. }
  650. }
  651. var calcResultRow: some View {
  652. GridRow(alignment: .center) {
  653. Text("Result").fontWeight(.bold)
  654. HStack {
  655. Text(state.useSuperBolus ? "(" : "")
  656. .foregroundColor(.loopRed)
  657. + Text(state.fraction.formatted())
  658. + Text(" x ")
  659. .foregroundColor(.secondary)
  660. // if fatty meal is chosen
  661. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  662. .foregroundColor(.orange)
  663. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  664. .foregroundColor(.secondary)
  665. // endif fatty meal is chosen
  666. + Text(self.insulinRounder(state.wholeCalc).formatted())
  667. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  668. // if superbolus is chosen
  669. + Text(state.useSuperBolus ? ")" : "")
  670. .foregroundColor(.loopRed)
  671. + Text(state.useSuperBolus ? " + " : "")
  672. .foregroundColor(.secondary)
  673. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  674. .foregroundColor(.loopRed)
  675. // endif superbolus is chosen
  676. + Text(" ≈ ")
  677. .foregroundColor(.secondary)
  678. }
  679. .gridColumnAlignment(.leading)
  680. HStack {
  681. Text(self.insulinRounder(state.insulinCalculated).formatted())
  682. .fontWeight(.bold)
  683. .foregroundColor(.blue)
  684. Text("U").foregroundColor(.secondary)
  685. }
  686. .gridColumnAlignment(.trailing)
  687. .fontWeight(.bold)
  688. }
  689. }
  690. var calcResultFormulaRow: some View {
  691. GridRow(alignment: .bottom) {
  692. if state.useFattyMealCorrectionFactor {
  693. Text("Factor x Fatty Meal Factor x Full Bolus")
  694. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  695. .font(.caption)
  696. .gridCellAnchor(.center)
  697. .gridCellColumns(3)
  698. } else if state.useSuperBolus {
  699. Text("(Factor x Full Bolus) + Super Bolus")
  700. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  701. .font(.caption)
  702. .gridCellAnchor(.center)
  703. .gridCellColumns(3)
  704. } else {
  705. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  706. Text("Factor x Full Bolus")
  707. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  708. .font(.caption)
  709. .padding(.top, 5)
  710. .gridCellAnchor(.leading)
  711. .gridCellColumns(2)
  712. }
  713. }
  714. }
  715. var calculationsDetailView: some View {
  716. NavigationStack {
  717. ScrollView {
  718. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  719. GridRow {
  720. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  721. }
  722. calcSettingsFirstRow
  723. calcSettingsSecondRow
  724. DividerCustom()
  725. // meal entries as grid rows
  726. if state.carbs > 0 {
  727. GridRow {
  728. Text("Carbs").foregroundColor(.secondary)
  729. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  730. HStack {
  731. Text(state.carbs.formatted())
  732. Text("g").foregroundColor(.secondary)
  733. }.gridCellAnchor(.trailing)
  734. }
  735. }
  736. if state.fat > 0 {
  737. GridRow {
  738. Text("Fat").foregroundColor(.secondary)
  739. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  740. HStack {
  741. Text(state.fat.formatted())
  742. Text("g").foregroundColor(.secondary)
  743. }.gridCellAnchor(.trailing)
  744. }
  745. }
  746. if state.protein > 0 {
  747. GridRow {
  748. Text("Protein").foregroundColor(.secondary)
  749. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  750. HStack {
  751. Text(state.protein.formatted())
  752. Text("g").foregroundColor(.secondary)
  753. }.gridCellAnchor(.trailing)
  754. }
  755. }
  756. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  757. DividerCustom()
  758. }
  759. GridRow {
  760. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  761. .padding(.bottom, 10)
  762. }
  763. calcGlucoseFirstRow
  764. calcGlucoseSecondRow.padding(.bottom, 5)
  765. calcGlucoseFormulaRow
  766. DividerCustom()
  767. calcIOBRow
  768. DividerCustom()
  769. calcCOBRow.padding(.bottom, 5)
  770. calcCOBFormulaRow
  771. DividerCustom()
  772. calcDeltaRow
  773. calcDeltaFormulaRow
  774. DividerCustom()
  775. calcFullBolusRow
  776. if state.useSuperBolus {
  777. DividerCustom()
  778. calcSuperBolusRow
  779. }
  780. DividerDouble()
  781. calcResultRow
  782. calcResultFormulaRow
  783. }
  784. Spacer()
  785. Button { showInfo = false }
  786. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  787. .buttonStyle(.bordered)
  788. .padding(.top)
  789. }
  790. .padding([.horizontal, .bottom])
  791. .font(.system(size: 15))
  792. }
  793. }
  794. private func insulinRounder(_ value: Decimal) -> Decimal {
  795. let toRound = NSDecimalNumber(decimal: value).doubleValue
  796. return Decimal(floor(100 * toRound) / 100)
  797. }
  798. private var disabled: Bool {
  799. state.amount <= 0 || state.amount > state.maxBolus
  800. }
  801. }
  802. struct DividerDouble: View {
  803. var body: some View {
  804. VStack(spacing: 2) {
  805. Rectangle()
  806. .frame(height: 1)
  807. .foregroundColor(.gray.opacity(0.65))
  808. Rectangle()
  809. .frame(height: 1)
  810. .foregroundColor(.gray.opacity(0.65))
  811. }
  812. .frame(height: 4)
  813. .padding(.vertical)
  814. }
  815. }
  816. struct DividerCustom: View {
  817. var body: some View {
  818. Rectangle()
  819. .frame(height: 1)
  820. .foregroundColor(.gray.opacity(0.65))
  821. .padding(.vertical)
  822. }
  823. }
  824. }