AlternativeBolusCalcRootView.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. import Swinject
  5. extension Bolus {
  6. struct AlternativeBolusCalcRootView: BaseView {
  7. let resolver: Resolver
  8. let waitForSuggestion: Bool
  9. let fetch: Bool
  10. let editMode: Bool
  11. let override: Bool
  12. @StateObject var state: StateModel
  13. @State private var showInfo = false
  14. @State private var showAlert = false
  15. @State private var exceededMaxBolus = false
  16. @State private var keepForNextWiew: Bool = false
  17. @State private var autofocus: Bool = true
  18. @State private var calculatorDetent = PresentationDetent.medium
  19. @State var pushed = false
  20. @State var isPromptPresented = false
  21. @State var dish: String = ""
  22. @State var saved = false
  23. @State private var treatmentsViewMode: TreatmentsViewMode = .calcMode
  24. @FocusState private var isFocused: Bool
  25. @ObservedObject var appState: AppState
  26. @Environment(\.managedObjectContext) var moc
  27. private enum Config {
  28. static let dividerHeight: CGFloat = 2
  29. static let spacing: CGFloat = 3
  30. }
  31. private enum TreatmentsViewMode {
  32. case editMode
  33. case calcMode
  34. }
  35. @Environment(\.colorScheme) var colorScheme
  36. @FetchRequest(
  37. entity: Meals.entity(),
  38. sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false)]
  39. ) var meal: FetchedResults<Meals>
  40. @FetchRequest(
  41. entity: Presets.entity(),
  42. sortDescriptors: [NSSortDescriptor(key: "dish", ascending: true)]
  43. ) var carbPresets: FetchedResults<Presets>
  44. private var formatter: NumberFormatter {
  45. let formatter = NumberFormatter()
  46. formatter.numberStyle = .decimal
  47. formatter.maximumFractionDigits = 2
  48. return formatter
  49. }
  50. private var mealFormatter: NumberFormatter {
  51. let formatter = NumberFormatter()
  52. formatter.numberStyle = .decimal
  53. formatter.maximumFractionDigits = 1
  54. return formatter
  55. }
  56. private var gluoseFormatter: NumberFormatter {
  57. let formatter = NumberFormatter()
  58. formatter.numberStyle = .decimal
  59. if state.units == .mmolL {
  60. formatter.maximumFractionDigits = 1
  61. } else { formatter.maximumFractionDigits = 0 }
  62. return formatter
  63. }
  64. private var fractionDigits: Int {
  65. if state.units == .mmolL {
  66. return 1
  67. } else { return 0 }
  68. }
  69. private var color: LinearGradient {
  70. colorScheme == .dark ? LinearGradient(
  71. gradient: Gradient(colors: [
  72. Color.bgDarkBlue,
  73. Color.bgDarkerDarkBlue
  74. ]),
  75. startPoint: .top,
  76. endPoint: .bottom
  77. )
  78. :
  79. LinearGradient(
  80. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  81. startPoint: .top,
  82. endPoint: .bottom
  83. )
  84. }
  85. private var empty: Bool {
  86. state.carbs <= 0 && state.fat <= 0 && state.protein <= 0
  87. }
  88. private var presetPopover: some View {
  89. Form {
  90. Section {
  91. TextField("Name Of Dish", text: $dish)
  92. Button {
  93. saved = true
  94. if dish != "", saved {
  95. let preset = Presets(context: moc)
  96. preset.dish = dish
  97. preset.fat = state.fat as NSDecimalNumber
  98. preset.protein = state.protein as NSDecimalNumber
  99. preset.carbs = state.carbs as NSDecimalNumber
  100. try? moc.save()
  101. state.addNewPresetToWaitersNotepad(dish)
  102. saved = false
  103. isPromptPresented = false
  104. }
  105. }
  106. label: { Text("Save") }
  107. Button {
  108. dish = ""
  109. saved = false
  110. isPromptPresented = false }
  111. label: { Text("Cancel") }
  112. } header: { Text("Enter Meal Preset Name") }
  113. }
  114. }
  115. private var minusButton: some View {
  116. Button {
  117. if state.carbs != 0,
  118. (state.carbs - (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  119. {
  120. state.carbs -= (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal)
  121. } else { state.carbs = 0 }
  122. if state.fat != 0,
  123. (state.fat - (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  124. {
  125. state.fat -= (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal)
  126. } else { state.fat = 0 }
  127. if state.protein != 0,
  128. (state.protein - (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) as Decimal) >= 0
  129. {
  130. state.protein -= (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal)
  131. } else { state.protein = 0 }
  132. state.removePresetFromNewMeal()
  133. if state.carbs == 0, state.fat == 0, state.protein == 0 { state.summation = [] }
  134. }
  135. label: { Image(systemName: "minus.circle.fill")
  136. .font(.system(size: 20))
  137. }
  138. .disabled(
  139. state
  140. .selection == nil ||
  141. (
  142. !state.summation
  143. .contains(state.selection?.dish ?? "") && (state.selection?.dish ?? "") != ""
  144. )
  145. )
  146. .buttonStyle(.borderless)
  147. .tint(.blue)
  148. }
  149. private var plusButton: some View {
  150. Button {
  151. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  152. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  153. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  154. state.addPresetToNewMeal()
  155. }
  156. label: { Image(systemName: "plus.circle.fill")
  157. .font(.system(size: 20))
  158. }
  159. .disabled(state.selection == nil)
  160. .buttonStyle(.borderless)
  161. .tint(.blue)
  162. }
  163. private var mealPresets: some View {
  164. Section {
  165. HStack {
  166. if state.selection != nil {
  167. minusButton
  168. }
  169. Picker("Preset", selection: $state.selection) {
  170. Text("Saved Food").tag(nil as Presets?)
  171. ForEach(carbPresets, id: \.self) { (preset: Presets) in
  172. Text(preset.dish ?? "").tag(preset as Presets?)
  173. }
  174. }
  175. .labelsHidden()
  176. .frame(maxWidth: .infinity, alignment: .center)
  177. ._onBindingChange($state.selection) { _ in
  178. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  179. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  180. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  181. state.addToSummation()
  182. }
  183. if state.selection != nil {
  184. plusButton
  185. }
  186. }
  187. HStack {
  188. Button("Delete Preset") {
  189. showAlert.toggle()
  190. }
  191. .disabled(state.selection == nil)
  192. .tint(.orange)
  193. .buttonStyle(.borderless)
  194. .alert(
  195. "Delete preset '\(state.selection?.dish ?? "")'?",
  196. isPresented: $showAlert,
  197. actions: {
  198. Button("No", role: .cancel) {}
  199. Button("Yes", role: .destructive) {
  200. state.deletePreset()
  201. state.carbs += ((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal
  202. state.fat += ((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal
  203. state.protein += ((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal
  204. state.addPresetToNewMeal()
  205. }
  206. }
  207. )
  208. Spacer()
  209. Button {
  210. isPromptPresented = true
  211. }
  212. label: { Text("Save as Preset") }
  213. .buttonStyle(.borderless)
  214. .disabled(
  215. empty ||
  216. (
  217. (((state.selection?.carbs ?? 0) as NSDecimalNumber) as Decimal) == state
  218. .carbs && (((state.selection?.fat ?? 0) as NSDecimalNumber) as Decimal) == state
  219. .fat && (((state.selection?.protein ?? 0) as NSDecimalNumber) as Decimal) == state
  220. .protein
  221. )
  222. )
  223. }
  224. }
  225. }
  226. @ViewBuilder private func proteinAndFat() -> some View {
  227. HStack {
  228. Text("Fat").foregroundColor(.orange)
  229. Spacer()
  230. DecimalTextField(
  231. "0",
  232. value: $state.fat,
  233. formatter: formatter,
  234. autofocus: false,
  235. cleanInput: true
  236. )
  237. Text("g").foregroundColor(.secondary)
  238. }
  239. HStack {
  240. Text("Protein").foregroundColor(.red)
  241. Spacer()
  242. DecimalTextField(
  243. "0",
  244. value: $state.protein,
  245. formatter: formatter,
  246. autofocus: false,
  247. cleanInput: true
  248. ).foregroundColor(.loopRed)
  249. Text("g").foregroundColor(.secondary)
  250. }
  251. }
  252. var body: some View {
  253. Form {
  254. // MARK: ADDED
  255. Section {
  256. HStack {
  257. Text("Carbs").fontWeight(.semibold)
  258. Spacer()
  259. DecimalTextField(
  260. "0",
  261. value: $state.carbs,
  262. formatter: formatter,
  263. autofocus: true,
  264. cleanInput: true
  265. )
  266. Text("g").foregroundColor(.secondary)
  267. }
  268. if state.useFPUconversion {
  269. proteinAndFat()
  270. }
  271. // Summary when combining presets
  272. if state.waitersNotepad() != "" {
  273. HStack {
  274. Text("Total")
  275. let test = state.waitersNotepad().components(separatedBy: ", ").removeDublicates()
  276. HStack(spacing: 0) {
  277. ForEach(test, id: \.self) {
  278. Text($0).foregroundStyle(Color.randomGreen()).font(.footnote)
  279. Text($0 == test[test.count - 1] ? "" : ", ")
  280. }
  281. }.frame(maxWidth: .infinity, alignment: .trailing)
  282. }
  283. }
  284. // Time
  285. HStack {
  286. Text("Time").foregroundStyle(Color.secondary)
  287. Spacer()
  288. if !pushed {
  289. Button {
  290. pushed = true
  291. } label: { Text("Now") }.buttonStyle(.borderless).foregroundColor(.secondary).padding(.trailing, 5)
  292. } else {
  293. Button { state.date = state.date.addingTimeInterval(-15.minutes.timeInterval) }
  294. label: { Image(systemName: "minus.circle") }.tint(.blue).buttonStyle(.borderless)
  295. DatePicker(
  296. "Time",
  297. selection: $state.date,
  298. displayedComponents: [.hourAndMinute]
  299. ).controlSize(.mini)
  300. .labelsHidden()
  301. Button {
  302. state.date = state.date.addingTimeInterval(15.minutes.timeInterval)
  303. }
  304. label: { Image(systemName: "plus.circle") }.tint(.blue).buttonStyle(.borderless)
  305. }
  306. }
  307. // Optional meal note
  308. // HStack {
  309. // Image(systemName: "note.text.badge.plus").foregroundColor(.secondary)
  310. // TextField("", text: $state.note).multilineTextAlignment(.trailing)
  311. // if state.note != "", isFocused {
  312. // Button { isFocused = false } label: { Image(systemName: "keyboard.chevron.compact.down") }
  313. // .controlSize(.mini)
  314. // }
  315. // }
  316. // .focused($isFocused)
  317. .popover(isPresented: $isPromptPresented) {
  318. presetPopover
  319. }
  320. HStack {
  321. Spacer()
  322. Button {
  323. if treatmentsViewMode == .calcMode {
  324. state.addCarbs(override, fetch: editMode)
  325. treatmentsViewMode = .editMode
  326. } else {
  327. state.backToCarbsView(complexEntry: true, meal, override: false)
  328. treatmentsViewMode = .calcMode
  329. }
  330. }
  331. label: {
  332. // Text((state.skipBolus && !override && !editMode) ? "Save" : "Calculate Bolus")
  333. // if carbs > 0 and it is the first entry then go into edit mode
  334. // conditionally change text to 'edit meal'
  335. // Text(!editMode ? "Calculate" : "Edit Meal")
  336. if treatmentsViewMode == .calcMode {
  337. Text("Calculate")
  338. } else {
  339. Text("Edit meal")
  340. }
  341. }.disabled(empty)
  342. Spacer()
  343. }
  344. } header: { Text("Carbs") }.listRowBackground(Color.chart)
  345. Section {
  346. mealPresets
  347. }.listRowBackground(Color.chart)
  348. // MARK: ADDING END
  349. Section {
  350. HStack {
  351. Button(action: {
  352. showInfo.toggle()
  353. }, label: {
  354. Image(systemName: "info.circle")
  355. Text("Calculations")
  356. })
  357. .foregroundStyle(.blue)
  358. .font(.footnote)
  359. .buttonStyle(PlainButtonStyle())
  360. .frame(maxWidth: .infinity, alignment: .leading)
  361. if state.fattyMeals {
  362. Spacer()
  363. Toggle(isOn: $state.useFattyMealCorrectionFactor) {
  364. Text("Fatty Meal")
  365. }
  366. .toggleStyle(CheckboxToggleStyle())
  367. .font(.footnote)
  368. .onChange(of: state.useFattyMealCorrectionFactor) { _ in
  369. state.insulinCalculated = state.calculateInsulin()
  370. if state.useFattyMealCorrectionFactor {
  371. state.useSuperBolus = false
  372. }
  373. }
  374. }
  375. if state.sweetMeals {
  376. Spacer()
  377. Toggle(isOn: $state.useSuperBolus) {
  378. Text("Super Bolus")
  379. }
  380. .toggleStyle(CheckboxToggleStyle())
  381. .font(.footnote)
  382. .onChange(of: state.useSuperBolus) { _ in
  383. state.insulinCalculated = state.calculateInsulin()
  384. if state.useSuperBolus {
  385. state.useFattyMealCorrectionFactor = false
  386. }
  387. }
  388. }
  389. }
  390. if state.waitForSuggestion {
  391. HStack {
  392. Text("Wait please").foregroundColor(.secondary)
  393. Spacer()
  394. ActivityIndicator(isAnimating: .constant(true), style: .medium) // fix iOS 15 bug
  395. }
  396. } else {
  397. HStack {
  398. Text("Recommended Bolus")
  399. Spacer()
  400. Text(
  401. formatter
  402. .string(from: Double(state.insulinCalculated) as NSNumber) ?? ""
  403. )
  404. Text(
  405. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  406. ).foregroundColor(.secondary)
  407. }.contentShape(Rectangle())
  408. .onTapGesture { state.amount = state.insulinCalculated }
  409. }
  410. HStack {
  411. Text("Bolus")
  412. Spacer()
  413. DecimalTextField(
  414. "0",
  415. value: $state.amount,
  416. formatter: formatter,
  417. autofocus: false,
  418. cleanInput: true
  419. )
  420. Text(exceededMaxBolus ? "😵" : " U").foregroundColor(.secondary)
  421. }
  422. .onChange(of: state.amount) { newValue in
  423. if newValue > state.maxBolus {
  424. exceededMaxBolus = true
  425. } else {
  426. exceededMaxBolus = false
  427. }
  428. }
  429. } header: { Text("Bolus") }.listRowBackground(Color.chart)
  430. if state.amount > 0 {
  431. Section {
  432. Button {
  433. keepForNextWiew = true
  434. state.add()
  435. state.hideModal()
  436. }
  437. label: { Text(exceededMaxBolus ? "Max Bolus exceeded!" : "Enact bolus") }
  438. .frame(maxWidth: .infinity, alignment: .center)
  439. .disabled(disabled)
  440. .listRowBackground(!disabled ? Color(.systemBlue) : Color(.systemGray4))
  441. .tint(.white)
  442. }
  443. }
  444. if state.amount <= 0 {
  445. Section {
  446. Button {
  447. keepForNextWiew = true
  448. state.hideModal()
  449. }
  450. label: { Text("Continue without bolus") }.frame(maxWidth: .infinity, alignment: .center)
  451. }.listRowBackground(Color.chart)
  452. }
  453. }.scrollContentBackground(.hidden).background(color)
  454. .blur(radius: showInfo ? 3 : 0)
  455. .navigationTitle("Treatments")
  456. .navigationBarTitleDisplayMode(.large)
  457. .toolbar(content: {
  458. ToolbarItem(placement: .topBarLeading) {
  459. Button {
  460. state.hideModal()
  461. } label: {
  462. Text("Close")
  463. }
  464. }
  465. })
  466. .onAppear {
  467. configureView {
  468. state.waitForSuggestionInitial = waitForSuggestion
  469. state.waitForSuggestion = waitForSuggestion
  470. state.insulinCalculated = state.calculateInsulin()
  471. }
  472. }
  473. .onDisappear {
  474. if hasFatOrProtein, !keepForNextWiew, state.useCalc {
  475. state.delete(deleteTwice: true, meal: meal)
  476. } else if !keepForNextWiew, state.useCalc {
  477. state.delete(deleteTwice: false, meal: meal)
  478. }
  479. }
  480. .sheet(isPresented: $showInfo) {
  481. calculationsDetailView
  482. .presentationDetents(
  483. [fetch ? .large : .fraction(0.9), .large],
  484. selection: $calculatorDetent
  485. )
  486. }
  487. }
  488. var predictionChart: some View {
  489. ZStack {
  490. PredictionView(
  491. predictions: $state.predictions, units: $state.units, eventualBG: $state.evBG, target: $state.target,
  492. displayPredictions: $state.displayPredictions
  493. )
  494. }
  495. }
  496. var calcSettingsFirstRow: some View {
  497. GridRow {
  498. Group {
  499. Text("Carb Ratio:")
  500. .foregroundColor(.secondary)
  501. }.gridCellAnchor(.leading)
  502. Group {
  503. Text("ISF:")
  504. .foregroundColor(.secondary)
  505. }.gridCellAnchor(.leading)
  506. VStack {
  507. Text("Target:")
  508. .foregroundColor(.secondary)
  509. }.gridCellAnchor(.leading)
  510. }
  511. }
  512. var calcSettingsSecondRow: some View {
  513. GridRow {
  514. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  515. .gridCellAnchor(.leading)
  516. Text(
  517. state.isf.formatted() + " " + state.units
  518. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  519. ).gridCellAnchor(.leading)
  520. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  521. Text(
  522. target
  523. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  524. " " + state.units.rawValue
  525. ).gridCellAnchor(.leading)
  526. }
  527. }
  528. var calcGlucoseFirstRow: some View {
  529. GridRow(alignment: .center) {
  530. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  531. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  532. Text("Glucose:").foregroundColor(.secondary)
  533. let firstRow = currentBG
  534. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  535. + " - " +
  536. target
  537. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  538. + " = " +
  539. state.targetDifference
  540. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  541. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  542. .gridColumnAlignment(.leading)
  543. HStack {
  544. Text(
  545. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  546. )
  547. Text("U").foregroundColor(.secondary)
  548. }.fontWeight(.bold)
  549. .gridColumnAlignment(.trailing)
  550. }
  551. }
  552. var calcGlucoseSecondRow: some View {
  553. GridRow(alignment: .center) {
  554. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  555. Text(
  556. currentBG
  557. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  558. " " +
  559. state.units.rawValue
  560. )
  561. let secondRow = state.targetDifference
  562. .formatted(
  563. .number.grouping(.never).rounded()
  564. .precision(.fractionLength(fractionDigits))
  565. )
  566. + " / " +
  567. state.isf.formatted()
  568. + " ≈ " +
  569. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  570. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  571. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  572. }
  573. }
  574. var calcGlucoseFormulaRow: some View {
  575. GridRow(alignment: .top) {
  576. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  577. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  578. .gridColumnAlignment(.leading)
  579. .gridCellColumns(2)
  580. }
  581. .font(.caption)
  582. }
  583. var calcIOBRow: some View {
  584. GridRow(alignment: .center) {
  585. HStack {
  586. Text("IOB:").foregroundColor(.secondary)
  587. Text(
  588. self.insulinRounder(state.iob).formatted()
  589. )
  590. }
  591. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  592. let iobFormatted = self.insulinRounder(state.iob).formatted()
  593. HStack {
  594. Text((state.iob != 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  595. Text("U").foregroundColor(.secondary)
  596. }.fontWeight(.bold)
  597. .gridColumnAlignment(.trailing)
  598. }
  599. }
  600. var calcCOBRow: some View {
  601. GridRow(alignment: .center) {
  602. HStack {
  603. Text("COB:").foregroundColor(.secondary)
  604. Text(
  605. state.cob
  606. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  607. NSLocalizedString(" g", comment: "grams")
  608. )
  609. }
  610. Text(
  611. state.cob
  612. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  613. + " / " +
  614. state.carbRatio.formatted()
  615. + " ≈ " +
  616. self.insulinRounder(state.wholeCobInsulin).formatted()
  617. )
  618. .foregroundColor(.secondary)
  619. .gridColumnAlignment(.leading)
  620. HStack {
  621. Text(
  622. self.insulinRounder(state.wholeCobInsulin).formatted()
  623. )
  624. Text("U").foregroundColor(.secondary)
  625. }.fontWeight(.bold)
  626. .gridColumnAlignment(.trailing)
  627. }
  628. }
  629. var calcCOBFormulaRow: some View {
  630. GridRow(alignment: .center) {
  631. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  632. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  633. .gridColumnAlignment(.leading)
  634. .gridCellColumns(2)
  635. }
  636. .font(.caption)
  637. }
  638. var calcDeltaRow: some View {
  639. GridRow(alignment: .center) {
  640. Text("Delta:").foregroundColor(.secondary)
  641. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  642. Text(
  643. deltaBG
  644. .formatted(
  645. .number.grouping(.never).rounded()
  646. .precision(.fractionLength(fractionDigits))
  647. )
  648. + " / " +
  649. state.isf.formatted()
  650. + " ≈ " +
  651. self.insulinRounder(state.fifteenMinInsulin).formatted()
  652. )
  653. .foregroundColor(.secondary)
  654. .gridColumnAlignment(.leading)
  655. HStack {
  656. Text(
  657. self.insulinRounder(state.fifteenMinInsulin).formatted()
  658. )
  659. Text("U").foregroundColor(.secondary)
  660. }.fontWeight(.bold)
  661. .gridColumnAlignment(.trailing)
  662. }
  663. }
  664. var calcDeltaFormulaRow: some View {
  665. GridRow(alignment: .center) {
  666. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  667. Text(
  668. deltaBG
  669. .formatted(
  670. .number.grouping(.never).rounded()
  671. .precision(.fractionLength(fractionDigits))
  672. ) + " " +
  673. state.units.rawValue
  674. )
  675. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  676. .gridColumnAlignment(.leading)
  677. .gridCellColumns(2).padding(.top, 5)
  678. }
  679. }
  680. var calcFullBolusRow: some View {
  681. GridRow(alignment: .center) {
  682. Text("Full Bolus")
  683. .foregroundColor(.secondary)
  684. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  685. HStack {
  686. Text(self.insulinRounder(state.wholeCalc).formatted())
  687. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  688. Text("U").foregroundColor(.secondary)
  689. }.gridColumnAlignment(.trailing)
  690. .fontWeight(.bold)
  691. }
  692. }
  693. var calcSuperBolusRow: some View {
  694. GridRow(alignment: .center) {
  695. Text("Super Bolus")
  696. .foregroundColor(.secondary)
  697. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  698. HStack {
  699. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  700. .foregroundStyle(Color.loopRed)
  701. Text("U").foregroundColor(.secondary)
  702. }.gridColumnAlignment(.trailing)
  703. .fontWeight(.bold)
  704. }
  705. }
  706. var calcResultRow: some View {
  707. GridRow(alignment: .center) {
  708. Text("Result").fontWeight(.bold)
  709. HStack {
  710. Text(state.useSuperBolus ? "(" : "")
  711. .foregroundColor(.loopRed)
  712. + Text(state.fraction.formatted())
  713. + Text(" x ")
  714. .foregroundColor(.secondary)
  715. // if fatty meal is chosen
  716. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  717. .foregroundColor(.orange)
  718. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  719. .foregroundColor(.secondary)
  720. // endif fatty meal is chosen
  721. + Text(self.insulinRounder(state.wholeCalc).formatted())
  722. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  723. // if superbolus is chosen
  724. + Text(state.useSuperBolus ? ")" : "")
  725. .foregroundColor(.loopRed)
  726. + Text(state.useSuperBolus ? " + " : "")
  727. .foregroundColor(.secondary)
  728. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  729. .foregroundColor(.loopRed)
  730. // endif superbolus is chosen
  731. + Text(" ≈ ")
  732. .foregroundColor(.secondary)
  733. }
  734. .gridColumnAlignment(.leading)
  735. HStack {
  736. Text(self.insulinRounder(state.insulinCalculated).formatted())
  737. .fontWeight(.bold)
  738. .foregroundColor(.blue)
  739. Text("U").foregroundColor(.secondary)
  740. }
  741. .gridColumnAlignment(.trailing)
  742. .fontWeight(.bold)
  743. }
  744. }
  745. var calcResultFormulaRow: some View {
  746. GridRow(alignment: .bottom) {
  747. if state.useFattyMealCorrectionFactor {
  748. Text("Factor x Fatty Meal Factor x Full Bolus")
  749. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  750. .font(.caption)
  751. .gridCellAnchor(.center)
  752. .gridCellColumns(3)
  753. } else if state.useSuperBolus {
  754. Text("(Factor x Full Bolus) + Super Bolus")
  755. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  756. .font(.caption)
  757. .gridCellAnchor(.center)
  758. .gridCellColumns(3)
  759. } else {
  760. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  761. Text("Factor x Full Bolus")
  762. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  763. .font(.caption)
  764. .padding(.top, 5)
  765. .gridCellAnchor(.leading)
  766. .gridCellColumns(2)
  767. }
  768. }
  769. }
  770. var calculationsDetailView: some View {
  771. NavigationStack {
  772. ScrollView {
  773. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  774. GridRow {
  775. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  776. }
  777. calcSettingsFirstRow
  778. calcSettingsSecondRow
  779. DividerCustom()
  780. if fetch {
  781. // meal entries as grid rows
  782. GridRow {
  783. if let carbs = meal.first?.carbs, carbs > 0 {
  784. Text("Carbs").foregroundColor(.secondary)
  785. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  786. HStack {
  787. Text(carbs.formatted())
  788. Text("g").foregroundColor(.secondary)
  789. }.gridCellAnchor(.trailing)
  790. }
  791. }
  792. GridRow {
  793. if let fat = meal.first?.fat, fat > 0 {
  794. Text("Fat").foregroundColor(.secondary)
  795. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  796. HStack {
  797. Text(fat.formatted())
  798. Text("g").foregroundColor(.secondary)
  799. }.gridCellAnchor(.trailing)
  800. }
  801. }
  802. GridRow {
  803. if let protein = meal.first?.protein, protein > 0 {
  804. Text("Protein").foregroundColor(.secondary)
  805. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  806. HStack {
  807. Text(protein.formatted())
  808. Text("g").foregroundColor(.secondary)
  809. }.gridCellAnchor(.trailing)
  810. }
  811. }
  812. GridRow {
  813. if let note = meal.first?.note, note != "" {
  814. Text("Note").foregroundColor(.secondary)
  815. Text(note).foregroundColor(.secondary).gridCellColumns(2).gridCellAnchor(.trailing)
  816. }
  817. }
  818. DividerCustom()
  819. }
  820. GridRow {
  821. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  822. .padding(.bottom, 10)
  823. }
  824. calcGlucoseFirstRow
  825. calcGlucoseSecondRow.padding(.bottom, 5)
  826. calcGlucoseFormulaRow
  827. DividerCustom()
  828. calcIOBRow
  829. DividerCustom()
  830. calcCOBRow.padding(.bottom, 5)
  831. calcCOBFormulaRow
  832. DividerCustom()
  833. calcDeltaRow
  834. calcDeltaFormulaRow
  835. DividerCustom()
  836. calcFullBolusRow
  837. if state.useSuperBolus {
  838. DividerCustom()
  839. calcSuperBolusRow
  840. }
  841. DividerDouble()
  842. calcResultRow
  843. calcResultFormulaRow
  844. }
  845. Spacer()
  846. Button { showInfo = false }
  847. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  848. .buttonStyle(.bordered)
  849. .padding(.top)
  850. }
  851. .padding([.horizontal, .bottom])
  852. .font(.system(size: 15))
  853. }
  854. }
  855. private func insulinRounder(_ value: Decimal) -> Decimal {
  856. let toRound = NSDecimalNumber(decimal: value).doubleValue
  857. return Decimal(floor(100 * toRound) / 100)
  858. }
  859. private var disabled: Bool {
  860. state.amount <= 0 || state.amount > state.maxBolus
  861. }
  862. var changed: Bool {
  863. ((meal.first?.carbs ?? 0) > 0) || ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  864. }
  865. var hasFatOrProtein: Bool {
  866. ((meal.first?.fat ?? 0) > 0) || ((meal.first?.protein ?? 0) > 0)
  867. }
  868. var mealEntries: some View {
  869. VStack {
  870. if let carbs = meal.first?.carbs, carbs > 0 {
  871. HStack {
  872. Text("Carbs").foregroundColor(.secondary)
  873. Spacer()
  874. Text(carbs.formatted())
  875. Text("g").foregroundColor(.secondary)
  876. }
  877. }
  878. if let fat = meal.first?.fat, fat > 0 {
  879. HStack {
  880. Text("Fat").foregroundColor(.secondary)
  881. Spacer()
  882. Text(fat.formatted())
  883. Text("g").foregroundColor(.secondary)
  884. }
  885. }
  886. if let protein = meal.first?.protein, protein > 0 {
  887. HStack {
  888. Text("Protein").foregroundColor(.secondary)
  889. Spacer()
  890. Text(protein.formatted())
  891. Text("g").foregroundColor(.secondary)
  892. }
  893. }
  894. if let note = meal.first?.note, note != "" {
  895. HStack {
  896. Text("Note").foregroundColor(.secondary)
  897. Spacer()
  898. Text(note).foregroundColor(.secondary)
  899. }
  900. }
  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. }