AlternativeBolusCalcRootView.swift 38 KB

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