AlternativeBolusCalcRootView.swift 37 KB

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