AlternativeBolusCalcRootView.swift 43 KB

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