AlternativeBolusCalcRootView.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. 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. } header: { Text("Bolus") }.listRowBackground(Color.chart)
  392. if state.amount > 0 {
  393. Section {
  394. Button {
  395. Task {
  396. await state.add()
  397. state.hideModal()
  398. state.addCarbs()
  399. }
  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 calcSettingsFirstRow: some View {
  444. GridRow {
  445. Group {
  446. Text("Carb Ratio:")
  447. .foregroundColor(.secondary)
  448. }.gridCellAnchor(.leading)
  449. Group {
  450. Text("ISF:")
  451. .foregroundColor(.secondary)
  452. }.gridCellAnchor(.leading)
  453. VStack {
  454. Text("Target:")
  455. .foregroundColor(.secondary)
  456. }.gridCellAnchor(.leading)
  457. }
  458. }
  459. var calcSettingsSecondRow: some View {
  460. GridRow {
  461. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  462. .gridCellAnchor(.leading)
  463. Text(
  464. state.isf.formatted() + " " + state.units
  465. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  466. ).gridCellAnchor(.leading)
  467. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  468. Text(
  469. target
  470. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  471. " " + state.units.rawValue
  472. ).gridCellAnchor(.leading)
  473. }
  474. }
  475. var calcGlucoseFirstRow: some View {
  476. GridRow(alignment: .center) {
  477. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  478. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  479. Text("Glucose:").foregroundColor(.secondary)
  480. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  481. let firstRow = currentBG
  482. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  483. + " - " +
  484. target
  485. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  486. + " = " +
  487. targetDifference
  488. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  489. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  490. .gridColumnAlignment(.leading)
  491. HStack {
  492. Text(
  493. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  494. )
  495. Text("U").foregroundColor(.secondary)
  496. }.fontWeight(.bold)
  497. .gridColumnAlignment(.trailing)
  498. }
  499. }
  500. var calcGlucoseSecondRow: some View {
  501. GridRow(alignment: .center) {
  502. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  503. Text(
  504. currentBG
  505. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  506. " " +
  507. state.units.rawValue
  508. )
  509. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  510. let secondRow = targetDifference
  511. .formatted(
  512. .number.grouping(.never).rounded()
  513. .precision(.fractionLength(fractionDigits))
  514. )
  515. + " / " +
  516. state.isf.formatted()
  517. + " ≈ " +
  518. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  519. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  520. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  521. }
  522. }
  523. var calcGlucoseFormulaRow: some View {
  524. GridRow(alignment: .top) {
  525. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  526. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  527. .gridColumnAlignment(.leading)
  528. .gridCellColumns(2)
  529. }
  530. .font(.caption)
  531. }
  532. var calcIOBRow: some View {
  533. GridRow(alignment: .center) {
  534. HStack {
  535. Text("IOB:").foregroundColor(.secondary)
  536. Text(
  537. self.insulinRounder(state.iob).formatted()
  538. )
  539. }
  540. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  541. let iobFormatted = self.insulinRounder(state.iob).formatted()
  542. HStack {
  543. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  544. Text("U").foregroundColor(.secondary)
  545. }.fontWeight(.bold)
  546. .gridColumnAlignment(.trailing)
  547. }
  548. }
  549. var calcCOBRow: some View {
  550. GridRow(alignment: .center) {
  551. HStack {
  552. Text("COB:").foregroundColor(.secondary)
  553. Text(
  554. state.wholeCob
  555. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  556. NSLocalizedString(" g", comment: "grams")
  557. )
  558. }
  559. Text(
  560. state.wholeCob
  561. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  562. + " / " +
  563. state.carbRatio.formatted()
  564. + " ≈ " +
  565. self.insulinRounder(state.wholeCobInsulin).formatted()
  566. )
  567. .foregroundColor(.secondary)
  568. .gridColumnAlignment(.leading)
  569. HStack {
  570. Text(
  571. self.insulinRounder(state.wholeCobInsulin).formatted()
  572. )
  573. Text("U").foregroundColor(.secondary)
  574. }.fontWeight(.bold)
  575. .gridColumnAlignment(.trailing)
  576. }
  577. }
  578. var calcCOBFormulaRow: some View {
  579. GridRow(alignment: .center) {
  580. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  581. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  582. .gridColumnAlignment(.leading)
  583. .gridCellColumns(2)
  584. }
  585. .font(.caption)
  586. }
  587. var calcDeltaRow: some View {
  588. GridRow(alignment: .center) {
  589. Text("Delta:").foregroundColor(.secondary)
  590. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  591. Text(
  592. deltaBG
  593. .formatted(
  594. .number.grouping(.never).rounded()
  595. .precision(.fractionLength(fractionDigits))
  596. )
  597. + " / " +
  598. state.isf.formatted()
  599. + " ≈ " +
  600. self.insulinRounder(state.fifteenMinInsulin).formatted()
  601. )
  602. .foregroundColor(.secondary)
  603. .gridColumnAlignment(.leading)
  604. HStack {
  605. Text(
  606. self.insulinRounder(state.fifteenMinInsulin).formatted()
  607. )
  608. Text("U").foregroundColor(.secondary)
  609. }.fontWeight(.bold)
  610. .gridColumnAlignment(.trailing)
  611. }
  612. }
  613. var calcDeltaFormulaRow: some View {
  614. GridRow(alignment: .center) {
  615. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  616. Text(
  617. deltaBG
  618. .formatted(
  619. .number.grouping(.never).rounded()
  620. .precision(.fractionLength(fractionDigits))
  621. ) + " " +
  622. state.units.rawValue
  623. )
  624. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  625. .gridColumnAlignment(.leading)
  626. .gridCellColumns(2).padding(.top, 5)
  627. }
  628. }
  629. var calcFullBolusRow: some View {
  630. GridRow(alignment: .center) {
  631. Text("Full Bolus")
  632. .foregroundColor(.secondary)
  633. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  634. HStack {
  635. Text(self.insulinRounder(state.wholeCalc).formatted())
  636. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  637. Text("U").foregroundColor(.secondary)
  638. }.gridColumnAlignment(.trailing)
  639. .fontWeight(.bold)
  640. }
  641. }
  642. var calcSuperBolusRow: some View {
  643. GridRow(alignment: .center) {
  644. Text("Super Bolus")
  645. .foregroundColor(.secondary)
  646. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  647. HStack {
  648. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  649. .foregroundStyle(Color.loopRed)
  650. Text("U").foregroundColor(.secondary)
  651. }.gridColumnAlignment(.trailing)
  652. .fontWeight(.bold)
  653. }
  654. }
  655. var calcResultRow: some View {
  656. GridRow(alignment: .center) {
  657. Text("Result").fontWeight(.bold)
  658. HStack {
  659. Text(state.useSuperBolus ? "(" : "")
  660. .foregroundColor(.loopRed)
  661. + Text(state.fraction.formatted())
  662. + Text(" x ")
  663. .foregroundColor(.secondary)
  664. // if fatty meal is chosen
  665. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  666. .foregroundColor(.orange)
  667. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  668. .foregroundColor(.secondary)
  669. // endif fatty meal is chosen
  670. + Text(self.insulinRounder(state.wholeCalc).formatted())
  671. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  672. // if superbolus is chosen
  673. + Text(state.useSuperBolus ? ")" : "")
  674. .foregroundColor(.loopRed)
  675. + Text(state.useSuperBolus ? " + " : "")
  676. .foregroundColor(.secondary)
  677. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  678. .foregroundColor(.loopRed)
  679. // endif superbolus is chosen
  680. + Text(" ≈ ")
  681. .foregroundColor(.secondary)
  682. }
  683. .gridColumnAlignment(.leading)
  684. HStack {
  685. Text(self.insulinRounder(state.insulinCalculated).formatted())
  686. .fontWeight(.bold)
  687. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  688. Text("U").foregroundColor(.secondary)
  689. }
  690. .gridColumnAlignment(.trailing)
  691. .fontWeight(.bold)
  692. }
  693. }
  694. var calcResultFormulaRow: some View {
  695. GridRow(alignment: .bottom) {
  696. if state.useFattyMealCorrectionFactor {
  697. Group {
  698. Text("Factor x Fatty Meal Factor x Full Bolus")
  699. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  700. +
  701. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  702. }
  703. .font(.caption)
  704. .gridCellAnchor(.center)
  705. .gridCellColumns(3)
  706. } else if state.useSuperBolus {
  707. Group {
  708. Text("(Factor x Full Bolus) + Super Bolus")
  709. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  710. +
  711. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  712. }
  713. .font(.caption)
  714. .gridCellAnchor(.center)
  715. .gridCellColumns(3)
  716. } else {
  717. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  718. Group {
  719. Text("Factor x Full Bolus")
  720. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  721. +
  722. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  723. }
  724. .font(.caption)
  725. .padding(.top, 5)
  726. .gridCellAnchor(.leading)
  727. .gridCellColumns(2)
  728. }
  729. }
  730. }
  731. var calculationsDetailView: some View {
  732. NavigationStack {
  733. ScrollView {
  734. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  735. GridRow {
  736. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  737. }
  738. calcSettingsFirstRow
  739. calcSettingsSecondRow
  740. DividerCustom()
  741. // meal entries as grid rows
  742. if state.carbs > 0 {
  743. GridRow {
  744. Text("Carbs").foregroundColor(.secondary)
  745. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  746. HStack {
  747. Text(state.carbs.formatted())
  748. Text("g").foregroundColor(.secondary)
  749. }.gridCellAnchor(.trailing)
  750. }
  751. }
  752. if state.fat > 0 {
  753. GridRow {
  754. Text("Fat").foregroundColor(.secondary)
  755. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  756. HStack {
  757. Text(state.fat.formatted())
  758. Text("g").foregroundColor(.secondary)
  759. }.gridCellAnchor(.trailing)
  760. }
  761. }
  762. if state.protein > 0 {
  763. GridRow {
  764. Text("Protein").foregroundColor(.secondary)
  765. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  766. HStack {
  767. Text(state.protein.formatted())
  768. Text("g").foregroundColor(.secondary)
  769. }.gridCellAnchor(.trailing)
  770. }
  771. }
  772. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  773. DividerCustom()
  774. }
  775. GridRow {
  776. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  777. .padding(.bottom, 10)
  778. }
  779. calcGlucoseFirstRow
  780. calcGlucoseSecondRow.padding(.bottom, 5)
  781. calcGlucoseFormulaRow
  782. DividerCustom()
  783. calcIOBRow
  784. DividerCustom()
  785. calcCOBRow.padding(.bottom, 5)
  786. calcCOBFormulaRow
  787. DividerCustom()
  788. calcDeltaRow
  789. calcDeltaFormulaRow
  790. DividerCustom()
  791. calcFullBolusRow
  792. if state.useSuperBolus {
  793. DividerCustom()
  794. calcSuperBolusRow
  795. }
  796. DividerDouble()
  797. calcResultRow
  798. calcResultFormulaRow
  799. }
  800. Spacer()
  801. Button { showInfo = false }
  802. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  803. .buttonStyle(.bordered)
  804. .padding(.top)
  805. }
  806. .padding([.horizontal, .bottom])
  807. .font(.system(size: 15))
  808. }
  809. }
  810. private func insulinRounder(_ value: Decimal) -> Decimal {
  811. let toRound = NSDecimalNumber(decimal: value).doubleValue
  812. return Decimal(floor(100 * toRound) / 100)
  813. }
  814. private var disabled: Bool {
  815. state.amount <= 0 || state.amount > state.maxBolus
  816. }
  817. }
  818. struct DividerDouble: View {
  819. var body: some View {
  820. VStack(spacing: 2) {
  821. Rectangle()
  822. .frame(height: 1)
  823. .foregroundColor(.gray.opacity(0.65))
  824. Rectangle()
  825. .frame(height: 1)
  826. .foregroundColor(.gray.opacity(0.65))
  827. }
  828. .frame(height: 4)
  829. .padding(.vertical)
  830. }
  831. }
  832. struct DividerCustom: View {
  833. var body: some View {
  834. Rectangle()
  835. .frame(height: 1)
  836. .foregroundColor(.gray.opacity(0.65))
  837. .padding(.vertical)
  838. }
  839. }
  840. }