AlternativeBolusCalcRootView.swift 42 KB

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