AlternativeBolusCalcRootView.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. 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. )
  387. Text(" U").foregroundColor(.secondary)
  388. }
  389. .onChange(of: state.amount) { newValue in
  390. if newValue > state.maxBolus {
  391. exceededMaxBolus = true
  392. } else {
  393. exceededMaxBolus = false
  394. }
  395. }
  396. }.listRowBackground(Color.chart)
  397. if state.amount > 0 {
  398. Section {
  399. HStack {
  400. Text("External insulin")
  401. Spacer()
  402. Toggle("", isOn: $state.externalInsulin).toggleStyle(Checkbox())
  403. }
  404. }.listRowBackground(Color.chart)
  405. }
  406. }
  407. }.safeAreaInset(edge: .bottom, spacing: 0) {
  408. stickyButton
  409. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  410. if state.waitForSuggestion {
  411. CustomProgressView(text: progressText)
  412. }
  413. }
  414. .scrollContentBackground(.hidden).background(color)
  415. .blur(radius: showInfo ? 3 : 0)
  416. .navigationTitle("Treatments")
  417. .navigationBarTitleDisplayMode(.inline)
  418. .toolbar(content: {
  419. ToolbarItem(placement: .topBarLeading) {
  420. Button {
  421. state.hideModal()
  422. } label: {
  423. Text("Close")
  424. }
  425. }
  426. })
  427. .onAppear {
  428. configureView {
  429. state.insulinCalculated = state.calculateInsulin()
  430. }
  431. }
  432. .onDisappear {
  433. state.addButtonPressed = false
  434. }
  435. .sheet(isPresented: $showInfo) {
  436. calculationsDetailView
  437. .presentationDetents(
  438. [.fraction(0.9), .large],
  439. selection: $calculatorDetent
  440. )
  441. }
  442. }
  443. var progressText: String {
  444. switch (state.amount > 0, state.carbs > 0) {
  445. case (true, true):
  446. return "Updating COB and IOB..."
  447. case (false, true):
  448. return "Updating COB..."
  449. case (true, false):
  450. return "Updating IOB..."
  451. default:
  452. return "Updating Treatments..."
  453. }
  454. }
  455. var stickyButton: some View {
  456. Section {
  457. Button {
  458. if state.amount > 0 {
  459. if !state.externalInsulin {
  460. Task {
  461. await state.add()
  462. state.waitForSuggestion = true
  463. }
  464. } else {
  465. Task {
  466. do {
  467. await state.addExternalInsulin()
  468. state.waitForSuggestion = true
  469. }
  470. }
  471. }
  472. state.addCarbs()
  473. state.addButtonPressed = true
  474. } else {
  475. // show loading bar only when carbs are actually added
  476. if state.carbs > 0 {
  477. state.addCarbs()
  478. state.waitForSuggestion = true
  479. } else {
  480. // hide modal because its otherwise only hidden after a suggestion update, see StateModal
  481. state.hideModal()
  482. }
  483. state.addButtonPressed = true
  484. }
  485. } label: {
  486. if state.amount > 0 {
  487. Text(
  488. !state
  489. .externalInsulin ? (exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") :
  490. (exceededMaxBolus ? "Max Bolus exceeded!" : "Log external insulin")
  491. ).font(.system(size: 17, design: .rounded))
  492. } else {
  493. Text("Continue without bolus").font(.system(size: 17, design: .rounded))
  494. }
  495. }
  496. .frame(maxWidth: .infinity, alignment: .center)
  497. .frame(minHeight: 50)
  498. .disabled(state.amount > 0 ? (state.externalInsulin ? limitManualBolus : limitPumpBolus) : false)
  499. .background(state.amount > 0 ? logExternalInsulinBackground : Color(.systemBlue))
  500. .shadow(radius: 3)
  501. .clipShape(RoundedRectangle(cornerRadius: 8))
  502. .foregroundStyle(state.amount > 0 ? logExternalInsulinForeground : .white)
  503. .padding()
  504. }
  505. .listRowBackground(Color.chart)
  506. }
  507. var calcSettingsFirstRow: some View {
  508. GridRow {
  509. Group {
  510. Text("Carb Ratio:")
  511. .foregroundColor(.secondary)
  512. }.gridCellAnchor(.leading)
  513. Group {
  514. Text("ISF:")
  515. .foregroundColor(.secondary)
  516. }.gridCellAnchor(.leading)
  517. VStack {
  518. Text("Target:")
  519. .foregroundColor(.secondary)
  520. }.gridCellAnchor(.leading)
  521. }
  522. }
  523. var calcSettingsSecondRow: some View {
  524. GridRow {
  525. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  526. .gridCellAnchor(.leading)
  527. Text(
  528. state.isf.formatted() + " " + state.units
  529. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  530. ).gridCellAnchor(.leading)
  531. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  532. Text(
  533. target
  534. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  535. " " + state.units.rawValue
  536. ).gridCellAnchor(.leading)
  537. }
  538. }
  539. var calcGlucoseFirstRow: some View {
  540. GridRow(alignment: .center) {
  541. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  542. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  543. Text("Glucose:").foregroundColor(.secondary)
  544. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  545. let firstRow = currentBG
  546. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  547. + " - " +
  548. target
  549. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  550. + " = " +
  551. targetDifference
  552. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  553. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  554. .gridColumnAlignment(.leading)
  555. HStack {
  556. Text(
  557. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  558. )
  559. Text("U").foregroundColor(.secondary)
  560. }.fontWeight(.bold)
  561. .gridColumnAlignment(.trailing)
  562. }
  563. }
  564. var calcGlucoseSecondRow: some View {
  565. GridRow(alignment: .center) {
  566. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  567. Text(
  568. currentBG
  569. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  570. " " +
  571. state.units.rawValue
  572. )
  573. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  574. let secondRow = targetDifference
  575. .formatted(
  576. .number.grouping(.never).rounded()
  577. .precision(.fractionLength(fractionDigits))
  578. )
  579. + " / " +
  580. state.isf.formatted()
  581. + " ≈ " +
  582. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  583. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  584. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  585. }
  586. }
  587. var calcGlucoseFormulaRow: some View {
  588. GridRow(alignment: .top) {
  589. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  590. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  591. .gridColumnAlignment(.leading)
  592. .gridCellColumns(2)
  593. }
  594. .font(.caption)
  595. }
  596. var calcIOBRow: some View {
  597. GridRow(alignment: .center) {
  598. HStack {
  599. Text("IOB:").foregroundColor(.secondary)
  600. Text(
  601. self.insulinRounder(state.iob).formatted()
  602. )
  603. }
  604. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  605. let iobFormatted = self.insulinRounder(state.iob).formatted()
  606. HStack {
  607. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  608. Text("U").foregroundColor(.secondary)
  609. }.fontWeight(.bold)
  610. .gridColumnAlignment(.trailing)
  611. }
  612. }
  613. var calcCOBRow: some View {
  614. GridRow(alignment: .center) {
  615. HStack {
  616. Text("COB:").foregroundColor(.secondary)
  617. Text(
  618. state.wholeCob
  619. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  620. NSLocalizedString(" g", comment: "grams")
  621. )
  622. }
  623. Text(
  624. state.wholeCob
  625. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  626. + " / " +
  627. state.carbRatio.formatted()
  628. + " ≈ " +
  629. self.insulinRounder(state.wholeCobInsulin).formatted()
  630. )
  631. .foregroundColor(.secondary)
  632. .gridColumnAlignment(.leading)
  633. HStack {
  634. Text(
  635. self.insulinRounder(state.wholeCobInsulin).formatted()
  636. )
  637. Text("U").foregroundColor(.secondary)
  638. }.fontWeight(.bold)
  639. .gridColumnAlignment(.trailing)
  640. }
  641. }
  642. var calcCOBFormulaRow: some View {
  643. GridRow(alignment: .center) {
  644. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  645. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  646. .gridColumnAlignment(.leading)
  647. .gridCellColumns(2)
  648. }
  649. .font(.caption)
  650. }
  651. var calcDeltaRow: some View {
  652. GridRow(alignment: .center) {
  653. Text("Delta:").foregroundColor(.secondary)
  654. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  655. Text(
  656. deltaBG
  657. .formatted(
  658. .number.grouping(.never).rounded()
  659. .precision(.fractionLength(fractionDigits))
  660. )
  661. + " / " +
  662. state.isf.formatted()
  663. + " ≈ " +
  664. self.insulinRounder(state.fifteenMinInsulin).formatted()
  665. )
  666. .foregroundColor(.secondary)
  667. .gridColumnAlignment(.leading)
  668. HStack {
  669. Text(
  670. self.insulinRounder(state.fifteenMinInsulin).formatted()
  671. )
  672. Text("U").foregroundColor(.secondary)
  673. }.fontWeight(.bold)
  674. .gridColumnAlignment(.trailing)
  675. }
  676. }
  677. var calcDeltaFormulaRow: some View {
  678. GridRow(alignment: .center) {
  679. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  680. Text(
  681. deltaBG
  682. .formatted(
  683. .number.grouping(.never).rounded()
  684. .precision(.fractionLength(fractionDigits))
  685. ) + " " +
  686. state.units.rawValue
  687. )
  688. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  689. .gridColumnAlignment(.leading)
  690. .gridCellColumns(2).padding(.top, 5)
  691. }
  692. }
  693. var calcFullBolusRow: some View {
  694. GridRow(alignment: .center) {
  695. Text("Full Bolus")
  696. .foregroundColor(.secondary)
  697. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  698. HStack {
  699. Text(self.insulinRounder(state.wholeCalc).formatted())
  700. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  701. Text("U").foregroundColor(.secondary)
  702. }.gridColumnAlignment(.trailing)
  703. .fontWeight(.bold)
  704. }
  705. }
  706. var calcSuperBolusRow: some View {
  707. GridRow(alignment: .center) {
  708. Text("Super Bolus")
  709. .foregroundColor(.secondary)
  710. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  711. HStack {
  712. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  713. .foregroundStyle(Color.loopRed)
  714. Text("U").foregroundColor(.secondary)
  715. }.gridColumnAlignment(.trailing)
  716. .fontWeight(.bold)
  717. }
  718. }
  719. var calcResultRow: some View {
  720. GridRow(alignment: .center) {
  721. Text("Result").fontWeight(.bold)
  722. HStack {
  723. Text(state.useSuperBolus ? "(" : "")
  724. .foregroundColor(.loopRed)
  725. + Text(state.fraction.formatted())
  726. + Text(" x ")
  727. .foregroundColor(.secondary)
  728. // if fatty meal is chosen
  729. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  730. .foregroundColor(.orange)
  731. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  732. .foregroundColor(.secondary)
  733. // endif fatty meal is chosen
  734. + Text(self.insulinRounder(state.wholeCalc).formatted())
  735. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  736. // if superbolus is chosen
  737. + Text(state.useSuperBolus ? ")" : "")
  738. .foregroundColor(.loopRed)
  739. + Text(state.useSuperBolus ? " + " : "")
  740. .foregroundColor(.secondary)
  741. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  742. .foregroundColor(.loopRed)
  743. // endif superbolus is chosen
  744. + Text(" ≈ ")
  745. .foregroundColor(.secondary)
  746. }
  747. .gridColumnAlignment(.leading)
  748. HStack {
  749. Text(self.insulinRounder(state.insulinCalculated).formatted())
  750. .fontWeight(.bold)
  751. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  752. Text("U").foregroundColor(.secondary)
  753. }
  754. .gridColumnAlignment(.trailing)
  755. .fontWeight(.bold)
  756. }
  757. }
  758. var calcResultFormulaRow: some View {
  759. GridRow(alignment: .bottom) {
  760. if state.useFattyMealCorrectionFactor {
  761. Group {
  762. Text("Factor x Fatty Meal Factor x Full Bolus")
  763. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  764. +
  765. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  766. }
  767. .font(.caption)
  768. .gridCellAnchor(.center)
  769. .gridCellColumns(3)
  770. } else if state.useSuperBolus {
  771. Group {
  772. Text("(Factor x Full Bolus) + Super Bolus")
  773. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  774. +
  775. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  776. }
  777. .font(.caption)
  778. .gridCellAnchor(.center)
  779. .gridCellColumns(3)
  780. } else {
  781. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  782. Group {
  783. Text("Factor x Full Bolus")
  784. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  785. +
  786. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  787. }
  788. .font(.caption)
  789. .padding(.top, 5)
  790. .gridCellAnchor(.leading)
  791. .gridCellColumns(2)
  792. }
  793. }
  794. }
  795. var calculationsDetailView: some View {
  796. NavigationStack {
  797. ScrollView {
  798. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  799. GridRow {
  800. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  801. }
  802. calcSettingsFirstRow
  803. calcSettingsSecondRow
  804. DividerCustom()
  805. // meal entries as grid rows
  806. if state.carbs > 0 {
  807. GridRow {
  808. Text("Carbs").foregroundColor(.secondary)
  809. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  810. HStack {
  811. Text(state.carbs.formatted())
  812. Text("g").foregroundColor(.secondary)
  813. }.gridCellAnchor(.trailing)
  814. }
  815. }
  816. if state.fat > 0 {
  817. GridRow {
  818. Text("Fat").foregroundColor(.secondary)
  819. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  820. HStack {
  821. Text(state.fat.formatted())
  822. Text("g").foregroundColor(.secondary)
  823. }.gridCellAnchor(.trailing)
  824. }
  825. }
  826. if state.protein > 0 {
  827. GridRow {
  828. Text("Protein").foregroundColor(.secondary)
  829. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  830. HStack {
  831. Text(state.protein.formatted())
  832. Text("g").foregroundColor(.secondary)
  833. }.gridCellAnchor(.trailing)
  834. }
  835. }
  836. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  837. DividerCustom()
  838. }
  839. GridRow {
  840. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  841. .padding(.bottom, 10)
  842. }
  843. calcGlucoseFirstRow
  844. calcGlucoseSecondRow.padding(.bottom, 5)
  845. calcGlucoseFormulaRow
  846. DividerCustom()
  847. calcIOBRow
  848. DividerCustom()
  849. calcCOBRow.padding(.bottom, 5)
  850. calcCOBFormulaRow
  851. DividerCustom()
  852. calcDeltaRow
  853. calcDeltaFormulaRow
  854. DividerCustom()
  855. calcFullBolusRow
  856. if state.useSuperBolus {
  857. DividerCustom()
  858. calcSuperBolusRow
  859. }
  860. DividerDouble()
  861. calcResultRow
  862. calcResultFormulaRow
  863. }
  864. Spacer()
  865. Button { showInfo = false }
  866. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  867. .buttonStyle(.bordered)
  868. .padding(.top)
  869. }
  870. .padding([.horizontal, .bottom])
  871. .font(.system(size: 15))
  872. }
  873. }
  874. private func insulinRounder(_ value: Decimal) -> Decimal {
  875. let toRound = NSDecimalNumber(decimal: value).doubleValue
  876. return Decimal(floor(100 * toRound) / 100)
  877. }
  878. private var limitPumpBolus: Bool {
  879. state.amount <= 0 || state.amount > state.maxBolus
  880. }
  881. // MARK: DEFINITIONS FOR ADDING EXTERNAL INSULIN
  882. private var limitManualBolus: Bool {
  883. state.amount <= 0 || state.amount > state.maxBolus * 3
  884. }
  885. private var logExternalInsulinBackground: Color {
  886. if state.amount > state.maxBolus {
  887. return Color.red
  888. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  889. return Color(.systemGray4)
  890. } else {
  891. return Color(.systemBlue)
  892. }
  893. }
  894. private var logExternalInsulinForeground: Color {
  895. if state.amount > state.maxBolus {
  896. return Color.white
  897. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  898. return Color.secondary
  899. } else {
  900. return Color.white
  901. }
  902. }
  903. }
  904. struct DividerDouble: View {
  905. var body: some View {
  906. VStack(spacing: 2) {
  907. Rectangle()
  908. .frame(height: 1)
  909. .foregroundColor(.gray.opacity(0.65))
  910. Rectangle()
  911. .frame(height: 1)
  912. .foregroundColor(.gray.opacity(0.65))
  913. }
  914. .frame(height: 4)
  915. .padding(.vertical)
  916. }
  917. }
  918. struct DividerCustom: View {
  919. var body: some View {
  920. Rectangle()
  921. .frame(height: 1)
  922. .foregroundColor(.gray.opacity(0.65))
  923. .padding(.vertical)
  924. }
  925. }
  926. }