AlternativeBolusCalcRootView.swift 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. ZStack(alignment: .center) {
  239. Form {
  240. // MARK: ADDED
  241. Section {
  242. HStack {
  243. Text("Carbs").fontWeight(.semibold)
  244. Spacer()
  245. DecimalTextField(
  246. "0",
  247. value: $state.carbs,
  248. formatter: formatter,
  249. autofocus: false,
  250. cleanInput: true
  251. )
  252. Text("g").foregroundColor(.secondary)
  253. }
  254. if state.useFPUconversion {
  255. proteinAndFat()
  256. }
  257. // Summary when combining presets
  258. if state.waitersNotepad() != "" {
  259. HStack {
  260. Text("Total")
  261. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  262. HStack(spacing: 0) {
  263. ForEach(test, id: \.self) {
  264. Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
  265. Text($0 == test[test.count - 1] ? "" : ", ")
  266. }
  267. }.frame(maxWidth: .infinity, alignment: .trailing)
  268. }
  269. }
  270. // Time
  271. HStack {
  272. Text("Time").foregroundStyle(Color.secondary)
  273. Spacer()
  274. if !pushed {
  275. Button {
  276. pushed = true
  277. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary)
  278. .padding(.trailing, 5)
  279. } else {
  280. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  281. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  282. DatePicker(
  283. "Time",
  284. selection: $state.date,
  285. displayedComponents: [.hourAndMinute]
  286. ).controlSize(.mini)
  287. .labelsHidden()
  288. Button {
  289. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  290. }
  291. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  292. }
  293. }
  294. .popover(isPresented: $isPromptPresented) {
  295. presetPopover
  296. }
  297. HStack {
  298. Spacer()
  299. Button {
  300. isCalculating = true
  301. state.insulinCalculated = state.calculateInsulin()
  302. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  303. isCalculating = false
  304. }
  305. }
  306. label: {
  307. if !isCalculating {
  308. Text("Calculate")
  309. } else {
  310. ProgressView().progressViewStyle(CircularProgressViewStyle())
  311. }
  312. }.disabled(empty)
  313. Spacer()
  314. }
  315. } header: { Text("Carbs") }.listRowBackground(Color.chart)
  316. Section {
  317. mealPresets
  318. }.listRowBackground(Color.chart)
  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.waitForSuggestion = true
  398. state.addCarbs()
  399. state.addButtonPressed = true
  400. }
  401. }
  402. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  403. .frame(maxWidth: .infinity, alignment: .center)
  404. .disabled(disabled)
  405. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  406. .tint(.white)
  407. }
  408. }
  409. if state.amount <= 0 {
  410. Section {
  411. Button {
  412. // show loading bar only when carbs are actually added
  413. if state.carbs > 0 {
  414. state.waitForSuggestion = true
  415. } else {
  416. // otherwise close view, because hideModal() is otherwise only excecuted after a suggestion update, see StateModal
  417. state.hideModal()
  418. }
  419. state.addButtonPressed = true
  420. state.addCarbs()
  421. }
  422. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  423. }.listRowBackground(Color.chart)
  424. }
  425. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  426. if state.waitForSuggestion {
  427. CustomProgressView(text: progressText)
  428. }
  429. }
  430. .scrollContentBackground(.hidden)
  431. .background(color)
  432. .blur(radius: showInfo ? 3 : 0)
  433. .navigationTitle("Treatments")
  434. .navigationBarTitleDisplayMode(.large)
  435. .toolbar(content: {
  436. ToolbarItem(placement: .topBarLeading) {
  437. Button {
  438. state.hideModal()
  439. } label: {
  440. Text("Close")
  441. }
  442. }
  443. })
  444. .onAppear {
  445. configureView {
  446. state.insulinCalculated = state.calculateInsulin()
  447. }
  448. }
  449. .onDisappear {
  450. state.addButtonPressed = false
  451. }
  452. .sheet(isPresented: $showInfo) {
  453. calculationsDetailView
  454. .presentationDetents(
  455. [.fraction(0.9), .large],
  456. selection: $calculatorDetent
  457. )
  458. }
  459. }
  460. var progressText: String {
  461. switch (state.amount > 0, state.carbs > 0) {
  462. case (true, true):
  463. return "Updating COB and IOB..."
  464. case (false, true):
  465. return "Updating COB..."
  466. case (true, false):
  467. return "Updating IOB..."
  468. default:
  469. return "Updating Treatments..."
  470. }
  471. }
  472. var predictionChart: some View {
  473. ZStack {
  474. PredictionView(
  475. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  476. displayPredictions: $state.displayPredictions
  477. )
  478. }
  479. }
  480. var calcSettingsFirstRow: some View {
  481. GridRow {
  482. Group {
  483. Text("Carb Ratio:")
  484. .foregroundColor(.secondary)
  485. }.gridCellAnchor(.leading)
  486. Group {
  487. Text("ISF:")
  488. .foregroundColor(.secondary)
  489. }.gridCellAnchor(.leading)
  490. VStack {
  491. Text("Target:")
  492. .foregroundColor(.secondary)
  493. }.gridCellAnchor(.leading)
  494. }
  495. }
  496. var calcSettingsSecondRow: some View {
  497. GridRow {
  498. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  499. .gridCellAnchor(.leading)
  500. Text(
  501. state.isf.formatted() + " " + state.units
  502. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  503. ).gridCellAnchor(.leading)
  504. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  505. Text(
  506. target
  507. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  508. " " + state.units.rawValue
  509. ).gridCellAnchor(.leading)
  510. }
  511. }
  512. var calcGlucoseFirstRow: some View {
  513. GridRow(alignment: .center) {
  514. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  515. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  516. Text("Glucose:").foregroundColor(.secondary)
  517. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  518. let firstRow = currentBG
  519. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  520. + " - " +
  521. target
  522. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  523. + " = " +
  524. targetDifference
  525. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  526. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  527. .gridColumnAlignment(.leading)
  528. HStack {
  529. Text(
  530. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  531. )
  532. Text("U").foregroundColor(.secondary)
  533. }.fontWeight(.bold)
  534. .gridColumnAlignment(.trailing)
  535. }
  536. }
  537. var calcGlucoseSecondRow: some View {
  538. GridRow(alignment: .center) {
  539. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  540. Text(
  541. currentBG
  542. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  543. " " +
  544. state.units.rawValue
  545. )
  546. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  547. let secondRow = targetDifference
  548. .formatted(
  549. .number.grouping(.never).rounded()
  550. .precision(.fractionLength(fractionDigits))
  551. )
  552. + " / " +
  553. state.isf.formatted()
  554. + " ≈ " +
  555. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  556. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  557. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  558. }
  559. }
  560. var calcGlucoseFormulaRow: some View {
  561. GridRow(alignment: .top) {
  562. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  563. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  564. .gridColumnAlignment(.leading)
  565. .gridCellColumns(2)
  566. }
  567. .font(.caption)
  568. }
  569. var calcIOBRow: some View {
  570. GridRow(alignment: .center) {
  571. HStack {
  572. Text("IOB:").foregroundColor(.secondary)
  573. Text(
  574. self.insulinRounder(state.iob).formatted()
  575. )
  576. }
  577. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  578. let iobFormatted = self.insulinRounder(state.iob).formatted()
  579. HStack {
  580. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  581. Text("U").foregroundColor(.secondary)
  582. }.fontWeight(.bold)
  583. .gridColumnAlignment(.trailing)
  584. }
  585. }
  586. var calcCOBRow: some View {
  587. GridRow(alignment: .center) {
  588. HStack {
  589. Text("COB:").foregroundColor(.secondary)
  590. Text(
  591. state.wholeCob
  592. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  593. NSLocalizedString(" g", comment: "grams")
  594. )
  595. }
  596. Text(
  597. state.wholeCob
  598. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  599. + " / " +
  600. state.carbRatio.formatted()
  601. + " ≈ " +
  602. self.insulinRounder(state.wholeCobInsulin).formatted()
  603. )
  604. .foregroundColor(.secondary)
  605. .gridColumnAlignment(.leading)
  606. HStack {
  607. Text(
  608. self.insulinRounder(state.wholeCobInsulin).formatted()
  609. )
  610. Text("U").foregroundColor(.secondary)
  611. }.fontWeight(.bold)
  612. .gridColumnAlignment(.trailing)
  613. }
  614. }
  615. var calcCOBFormulaRow: some View {
  616. GridRow(alignment: .center) {
  617. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  618. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  619. .gridColumnAlignment(.leading)
  620. .gridCellColumns(2)
  621. }
  622. .font(.caption)
  623. }
  624. var calcDeltaRow: some View {
  625. GridRow(alignment: .center) {
  626. Text("Delta:").foregroundColor(.secondary)
  627. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  628. Text(
  629. deltaBG
  630. .formatted(
  631. .number.grouping(.never).rounded()
  632. .precision(.fractionLength(fractionDigits))
  633. )
  634. + " / " +
  635. state.isf.formatted()
  636. + " ≈ " +
  637. self.insulinRounder(state.fifteenMinInsulin).formatted()
  638. )
  639. .foregroundColor(.secondary)
  640. .gridColumnAlignment(.leading)
  641. HStack {
  642. Text(
  643. self.insulinRounder(state.fifteenMinInsulin).formatted()
  644. )
  645. Text("U").foregroundColor(.secondary)
  646. }.fontWeight(.bold)
  647. .gridColumnAlignment(.trailing)
  648. }
  649. }
  650. var calcDeltaFormulaRow: some View {
  651. GridRow(alignment: .center) {
  652. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  653. Text(
  654. deltaBG
  655. .formatted(
  656. .number.grouping(.never).rounded()
  657. .precision(.fractionLength(fractionDigits))
  658. ) + " " +
  659. state.units.rawValue
  660. )
  661. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  662. .gridColumnAlignment(.leading)
  663. .gridCellColumns(2).padding(.top, 5)
  664. }
  665. }
  666. var calcFullBolusRow: some View {
  667. GridRow(alignment: .center) {
  668. Text("Full Bolus")
  669. .foregroundColor(.secondary)
  670. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  671. HStack {
  672. Text(self.insulinRounder(state.wholeCalc).formatted())
  673. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  674. Text("U").foregroundColor(.secondary)
  675. }.gridColumnAlignment(.trailing)
  676. .fontWeight(.bold)
  677. }
  678. }
  679. var calcSuperBolusRow: some View {
  680. GridRow(alignment: .center) {
  681. Text("Super Bolus")
  682. .foregroundColor(.secondary)
  683. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  684. HStack {
  685. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  686. .foregroundStyle(Color.loopRed)
  687. Text("U").foregroundColor(.secondary)
  688. }.gridColumnAlignment(.trailing)
  689. .fontWeight(.bold)
  690. }
  691. }
  692. var calcResultRow: some View {
  693. GridRow(alignment: .center) {
  694. Text("Result").fontWeight(.bold)
  695. HStack {
  696. Text(state.useSuperBolus ? "(" : "")
  697. .foregroundColor(.loopRed)
  698. + Text(state.fraction.formatted())
  699. + Text(" x ")
  700. .foregroundColor(.secondary)
  701. // if fatty meal is chosen
  702. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  703. .foregroundColor(.orange)
  704. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  705. .foregroundColor(.secondary)
  706. // endif fatty meal is chosen
  707. + Text(self.insulinRounder(state.wholeCalc).formatted())
  708. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  709. // if superbolus is chosen
  710. + Text(state.useSuperBolus ? ")" : "")
  711. .foregroundColor(.loopRed)
  712. + Text(state.useSuperBolus ? " + " : "")
  713. .foregroundColor(.secondary)
  714. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  715. .foregroundColor(.loopRed)
  716. // endif superbolus is chosen
  717. + Text(" ≈ ")
  718. .foregroundColor(.secondary)
  719. }
  720. .gridColumnAlignment(.leading)
  721. HStack {
  722. Text(self.insulinRounder(state.insulinCalculated).formatted())
  723. .fontWeight(.bold)
  724. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  725. Text("U").foregroundColor(.secondary)
  726. }
  727. .gridColumnAlignment(.trailing)
  728. .fontWeight(.bold)
  729. }
  730. }
  731. var calcResultFormulaRow: some View {
  732. GridRow(alignment: .bottom) {
  733. if state.useFattyMealCorrectionFactor {
  734. Group {
  735. Text("Factor x Fatty Meal Factor x Full Bolus")
  736. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  737. +
  738. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  739. }
  740. .font(.caption)
  741. .gridCellAnchor(.center)
  742. .gridCellColumns(3)
  743. } else if state.useSuperBolus {
  744. Group {
  745. Text("(Factor x Full Bolus) + Super Bolus")
  746. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  747. +
  748. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  749. }
  750. .font(.caption)
  751. .gridCellAnchor(.center)
  752. .gridCellColumns(3)
  753. } else {
  754. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  755. Group {
  756. Text("Factor x Full Bolus")
  757. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  758. +
  759. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  760. }
  761. .font(.caption)
  762. .padding(.top, 5)
  763. .gridCellAnchor(.leading)
  764. .gridCellColumns(2)
  765. }
  766. }
  767. }
  768. var calculationsDetailView: some View {
  769. NavigationStack {
  770. ScrollView {
  771. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  772. GridRow {
  773. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  774. }
  775. calcSettingsFirstRow
  776. calcSettingsSecondRow
  777. DividerCustom()
  778. // meal entries as grid rows
  779. if state.carbs > 0 {
  780. GridRow {
  781. Text("Carbs").foregroundColor(.secondary)
  782. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  783. HStack {
  784. Text(state.carbs.formatted())
  785. Text("g").foregroundColor(.secondary)
  786. }.gridCellAnchor(.trailing)
  787. }
  788. }
  789. if state.fat > 0 {
  790. GridRow {
  791. Text("Fat").foregroundColor(.secondary)
  792. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  793. HStack {
  794. Text(state.fat.formatted())
  795. Text("g").foregroundColor(.secondary)
  796. }.gridCellAnchor(.trailing)
  797. }
  798. }
  799. if state.protein > 0 {
  800. GridRow {
  801. Text("Protein").foregroundColor(.secondary)
  802. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  803. HStack {
  804. Text(state.protein.formatted())
  805. Text("g").foregroundColor(.secondary)
  806. }.gridCellAnchor(.trailing)
  807. }
  808. }
  809. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  810. DividerCustom()
  811. }
  812. GridRow {
  813. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  814. .padding(.bottom, 10)
  815. }
  816. calcGlucoseFirstRow
  817. calcGlucoseSecondRow.padding(.bottom, 5)
  818. calcGlucoseFormulaRow
  819. DividerCustom()
  820. calcIOBRow
  821. DividerCustom()
  822. calcCOBRow.padding(.bottom, 5)
  823. calcCOBFormulaRow
  824. DividerCustom()
  825. calcDeltaRow
  826. calcDeltaFormulaRow
  827. DividerCustom()
  828. calcFullBolusRow
  829. if state.useSuperBolus {
  830. DividerCustom()
  831. calcSuperBolusRow
  832. }
  833. DividerDouble()
  834. calcResultRow
  835. calcResultFormulaRow
  836. }
  837. Spacer()
  838. Button { showInfo = false }
  839. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  840. .buttonStyle(.bordered)
  841. .padding(.top)
  842. }
  843. .padding([.horizontal, .bottom])
  844. .font(.system(size: 15))
  845. }
  846. }
  847. private func insulinRounder(_ value: Decimal) -> Decimal {
  848. let toRound = NSDecimalNumber(decimal: value).doubleValue
  849. return Decimal(floor(100 * toRound) / 100)
  850. }
  851. private var disabled: Bool {
  852. state.amount <= 0 || state.amount > state.maxBolus
  853. }
  854. }
  855. struct DividerDouble: View {
  856. var body: some View {
  857. VStack(spacing: 2) {
  858. Rectangle()
  859. .frame(height: 1)
  860. .foregroundColor(.gray.opacity(0.65))
  861. Rectangle()
  862. .frame(height: 1)
  863. .foregroundColor(.gray.opacity(0.65))
  864. }
  865. .frame(height: 4)
  866. .padding(.vertical)
  867. }
  868. }
  869. struct DividerCustom: View {
  870. var body: some View {
  871. Rectangle()
  872. .frame(height: 1)
  873. .foregroundColor(.gray.opacity(0.65))
  874. .padding(.vertical)
  875. }
  876. }
  877. }