AlternativeBolusCalcRootView.swift 37 KB

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