AlternativeBolusCalcRootView.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 = false
  11. @State private var showAlert = 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. VStack {
  240. Form {
  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. }.listRowBackground(Color.chart)
  316. if state.displayPresets {
  317. Section {
  318. mealPresets
  319. }.listRowBackground(Color.chart)
  320. }
  321. Section {
  322. HStack {
  323. Button(action: {
  324. showInfo.toggle()
  325. }, label: {
  326. Image(systemName: "info.circle")
  327. Text("Calculations")
  328. })
  329. .foregroundStyle(.blue)
  330. .font(.footnote)
  331. .buttonStyle(PlainButtonStyle())
  332. .frame(maxWidth: .infinity, alignment: .leading)
  333. if state.fattyMeals {
  334. Spacer()
  335. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  336. Text("Fatty Meal")
  337. }
  338. .toggleStyle(CheckboxToggleStyle())
  339. .font(.footnote)
  340. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  341. state.insulinCalculated = state.calculateInsulin()
  342. if state.useFattyMealCorrectionFactor {
  343. state.useSuperBolus = false
  344. }
  345. }
  346. }
  347. if state.sweetMeals {
  348. Spacer()
  349. Toggle(isOn: $state.useSuperBolus) {
  350. Text("Super Bolus")
  351. }
  352. .toggleStyle(CheckboxToggleStyle())
  353. .font(.footnote)
  354. .onChange(of: state.useSuperBolus) { _ in
  355. state.insulinCalculated = state.calculateInsulin()
  356. if state.useSuperBolus {
  357. state.useFattyMealCorrectionFactor = false
  358. }
  359. }
  360. }
  361. }
  362. HStack {
  363. Text("Recommended Bolus")
  364. Spacer()
  365. Text(
  366. formatter
  367. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  368. )
  369. Text(
  370. NSLocalizedString(
  371. " U",
  372. comment: "Unit in number of units delivered (keep the space character!)"
  373. )
  374. ).foregroundColor(.secondary)
  375. }.contentShape(Rectangle())
  376. .onTapGesture { state.amount = state.insulinCalculated }
  377. HStack {
  378. Text("Bolus")
  379. Spacer()
  380. DecimalTextField(
  381. "0",
  382. value: $state.amount,
  383. formatter: formatter,
  384. autofocus: false,
  385. cleanInput: true,
  386. textColor: .systemBlue
  387. )
  388. Text(" U").foregroundColor(.secondary)
  389. }
  390. }.listRowBackground(Color.chart)
  391. if state.amount > 0 {
  392. Section {
  393. HStack {
  394. Text("External insulin")
  395. Spacer()
  396. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  397. }
  398. }.listRowBackground(Color.chart)
  399. }
  400. }
  401. }.safeAreaInset(edge: .bottom, spacing: 0) {
  402. stickyButton
  403. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  404. if state.waitForSuggestion {
  405. CustomProgressView(text: progressText.rawValue)
  406. }
  407. }
  408. .scrollContentBackground(.hidden).background(color)
  409. .blur(radius: showInfo ? 3 : 0)
  410. .navigationTitle("Treatments")
  411. .navigationBarTitleDisplayMode(.inline)
  412. .toolbar(content: {
  413. ToolbarItem(placement: .topBarLeading) {
  414. Button {
  415. state.hideModal()
  416. } label: {
  417. Text("Close")
  418. }
  419. }
  420. })
  421. .onAppear {
  422. configureView {
  423. state.insulinCalculated = state.calculateInsulin()
  424. }
  425. }
  426. .onDisappear {
  427. state.addButtonPressed = false
  428. }
  429. .sheet(isPresented: $showInfo) {
  430. calculationsDetailView
  431. .presentationDetents(
  432. [.fraction(0.9), .large],
  433. selection: $calculatorDetent
  434. )
  435. }
  436. }
  437. var progressText: ProgressText {
  438. switch (state.amount > 0, state.carbs > 0) {
  439. case (true, true):
  440. return .updatingIOBandCOB
  441. case (false, true):
  442. return .updatingCOB
  443. case (true, false):
  444. return .updatingIOB
  445. default:
  446. return .updatingTreatments
  447. }
  448. }
  449. var stickyButton: some View {
  450. ZStack {
  451. Rectangle()
  452. .frame(width: UIScreen.main.bounds.width, height: 120).offset(y: 40)
  453. .shadow(
  454. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  455. Color.black.opacity(0.33),
  456. radius: 3
  457. )
  458. .foregroundStyle(Color.chart)
  459. Section {
  460. Button {
  461. state.invokeTreatmentsTask()
  462. } label: {
  463. taskButtonLabel
  464. }
  465. .frame(maxWidth: .infinity, alignment: .center)
  466. .frame(minHeight: 50)
  467. .disabled(disableTaskButton)
  468. .background(
  469. (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) ? Color(.systemRed) :
  470. Color(.systemBlue)
  471. )
  472. .shadow(radius: 3)
  473. .clipShape(RoundedRectangle(cornerRadius: 8))
  474. .foregroundStyle(Color.white)
  475. .padding()
  476. }.offset(y: 20)
  477. .listRowBackground(Color.chart)
  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(.subheadline)
  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 taskButtonLabel: some View {
  852. if state.amount > 0 {
  853. Text(
  854. !state.externalInsulin ? (pumpBolusLimit ? "Pump bolus exceeds max bolus!" : "Enact bolus") :
  855. (externalBolusLimit ? "Manual bolus exceeds max bolus!" : "Log external insulin")
  856. ).font(.headline)
  857. } else {
  858. Text("Continue without bolus").font(.headline)
  859. }
  860. }
  861. private var pumpBolusLimit: Bool {
  862. state.amount > state.maxBolus
  863. }
  864. private var externalBolusLimit: Bool {
  865. state.amount > state.maxBolus * 3
  866. }
  867. private var disableTaskButton: Bool {
  868. state.amount > 0 ? (state.externalInsulin ? externalBolusLimit : pumpBolusLimit) : false
  869. }
  870. }
  871. struct DividerDouble: View {
  872. var body: some View {
  873. VStack(spacing: 2) {
  874. Rectangle()
  875. .frame(height: 1)
  876. .foregroundColor(.gray.opacity(0.65))
  877. Rectangle()
  878. .frame(height: 1)
  879. .foregroundColor(.gray.opacity(0.65))
  880. }
  881. .frame(height: 4)
  882. .padding(.vertical)
  883. }
  884. }
  885. struct DividerCustom: View {
  886. var body: some View {
  887. Rectangle()
  888. .frame(height: 1)
  889. .foregroundColor(.gray.opacity(0.65))
  890. .padding(.vertical)
  891. }
  892. }
  893. }