AlternativeBolusCalcRootView.swift 37 KB

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