AlternativeBolusCalcRootView.swift 38 KB

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