AlternativeBolusCalcRootView.swift 41 KB

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