AlternativeBolusCalcRootView.swift 41 KB

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