AlternativeBolusCalcRootView.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. extension Bolus {
  6. struct AlternativeBolusCalcRootView: BaseView {
  7. let resolver: Resolver
  8. let waitForSuggestion: Bool
  9. @StateObject var state: StateModel
  10. @State private var showInfo = false
  11. @State private var showAlert = false
  12. @State private var exceededMaxBolus = false
  13. @State private var autofocus: Bool = true
  14. @State private var calculatorDetent = PresentationDetent.medium
  15. @State var pushed = false
  16. @State var isPromptPresented = false
  17. @State var dish: String = ""
  18. @State var saved = 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: true,
  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. // to do
  299. state.insulinCalculated = state.calculateInsulin()
  300. }
  301. label: {
  302. Text("Calculate")
  303. }.disabled(empty)
  304. Spacer()
  305. }
  306. } header: { Text("Carbs") }.listRowBackground(Color.chart)
  307. Section {
  308. mealPresets
  309. }.listRowBackground(Color.chart)
  310. // MARK: ADDING END
  311. Section {
  312. HStack {
  313. Button(action: {
  314. showInfo.toggle()
  315. }, label: {
  316. Image(systemName: "info.circle")
  317. Text("Calculations")
  318. })
  319. .foregroundStyle(.blue)
  320. .font(.footnote)
  321. .buttonStyle(PlainButtonStyle())
  322. .frame(maxWidth: .infinity, alignment: .leading)
  323. if state.fattyMeals {
  324. Spacer()
  325. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  326. Text("Fatty Meal")
  327. }
  328. .toggleStyle(CheckboxToggleStyle())
  329. .font(.footnote)
  330. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  331. state.insulinCalculated = state.calculateInsulin()
  332. if state.useFattyMealCorrectionFactor {
  333. state.useSuperBolus = false
  334. }
  335. }
  336. }
  337. if state.sweetMeals {
  338. Spacer()
  339. Toggle(isOn: $state.useSuperBolus) {
  340. Text("Super Bolus")
  341. }
  342. .toggleStyle(CheckboxToggleStyle())
  343. .font(.footnote)
  344. .onChange(of: state.useSuperBolus) { _ in
  345. state.insulinCalculated = state.calculateInsulin()
  346. if state.useSuperBolus {
  347. state.useFattyMealCorrectionFactor = false
  348. }
  349. }
  350. }
  351. }
  352. if state.waitForSuggestion {
  353. HStack {
  354. Text("Wait please").foregroundColor(.secondary)
  355. Spacer()
  356. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  357. }
  358. } else {
  359. HStack {
  360. Text("Recommended Bolus")
  361. Spacer()
  362. Text(
  363. formatter
  364. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  365. )
  366. Text(
  367. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  368. ).foregroundColor(.secondary)
  369. }.contentShape(Rectangle())
  370. .onTapGesture { state.amount = state.insulinCalculated }
  371. }
  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. state.add()
  396. state.hideModal()
  397. state.addCarbs()
  398. }
  399. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  400. .frame(maxWidth: .infinity, alignment: .center)
  401. .disabled(disabled)
  402. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  403. .tint(.white)
  404. }
  405. }
  406. if state.amount <= 0 {
  407. Section {
  408. Button {
  409. state.hideModal()
  410. state.addCarbs()
  411. }
  412. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  413. }.listRowBackground(Color.chart)
  414. }
  415. }.scrollContentBackground(.hidden).background(color)
  416. .blur(radius: showInfo ? 3 : 0)
  417. .navigationTitle("Treatments")
  418. .navigationBarTitleDisplayMode(.large)
  419. .toolbar(content: {
  420. ToolbarItem(placement: .topBarLeading) {
  421. Button {
  422. state.hideModal()
  423. } label: {
  424. Text("Close")
  425. }
  426. }
  427. })
  428. .onAppear {
  429. configureView {
  430. state.waitForSuggestionInitial = waitForSuggestion
  431. state.waitForSuggestion = waitForSuggestion
  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. // meal entries as grid rows
  736. if state.carbs > 0 {
  737. GridRow {
  738. Text("Carbs").foregroundColor(.secondary)
  739. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  740. HStack {
  741. Text(state.carbs.formatted())
  742. Text("g").foregroundColor(.secondary)
  743. }.gridCellAnchor(.trailing)
  744. }
  745. }
  746. if state.fat > 0 {
  747. GridRow {
  748. Text("Fat").foregroundColor(.secondary)
  749. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  750. HStack {
  751. Text(state.fat.formatted())
  752. Text("g").foregroundColor(.secondary)
  753. }.gridCellAnchor(.trailing)
  754. }
  755. }
  756. if state.protein > 0 {
  757. GridRow {
  758. Text("Protein").foregroundColor(.secondary)
  759. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  760. HStack {
  761. Text(state.protein.formatted())
  762. Text("g").foregroundColor(.secondary)
  763. }.gridCellAnchor(.trailing)
  764. }
  765. }
  766. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  767. DividerCustom()
  768. }
  769. GridRow {
  770. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  771. .padding(.bottom, 10)
  772. }
  773. calcGlucoseFirstRow
  774. calcGlucoseSecondRow.padding(.bottom, 5)
  775. calcGlucoseFormulaRow
  776. DividerCustom()
  777. calcIOBRow
  778. DividerCustom()
  779. calcCOBRow.padding(.bottom, 5)
  780. calcCOBFormulaRow
  781. DividerCustom()
  782. calcDeltaRow
  783. calcDeltaFormulaRow
  784. DividerCustom()
  785. calcFullBolusRow
  786. if state.useSuperBolus {
  787. DividerCustom()
  788. calcSuperBolusRow
  789. }
  790. DividerDouble()
  791. calcResultRow
  792. calcResultFormulaRow
  793. }
  794. Spacer()
  795. Button { showInfo = false }
  796. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  797. .buttonStyle(.bordered)
  798. .padding(.top)
  799. }
  800. .padding([.horizontal, .bottom])
  801. .font(.system(size: 15))
  802. }
  803. }
  804. private func insulinRounder(_ value: Decimal) -> Decimal {
  805. let toRound = NSDecimalNumber(decimal: value).doubleValue
  806. return Decimal(floor(100 * toRound) / 100)
  807. }
  808. private var disabled: Bool {
  809. state.amount <= 0 || state.amount > state.maxBolus
  810. }
  811. }
  812. struct DividerDouble: View {
  813. var body: some View {
  814. VStack(spacing: 2) {
  815. Rectangle()
  816. .frame(height: 1)
  817. .foregroundColor(.gray.opacity(0.65))
  818. Rectangle()
  819. .frame(height: 1)
  820. .foregroundColor(.gray.opacity(0.65))
  821. }
  822. .frame(height: 4)
  823. .padding(.vertical)
  824. }
  825. }
  826. struct DividerCustom: View {
  827. var body: some View {
  828. Rectangle()
  829. .frame(height: 1)
  830. .foregroundColor(.gray.opacity(0.65))
  831. .padding(.vertical)
  832. }
  833. }
  834. }