AlternativeBolusCalcRootView.swift 43 KB

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