AlternativeBolusCalcRootView.swift 43 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. @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(exceededMaxBolus ? "Max Bolus exceeded!" : "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. state.addCarbs()
  457. state.addButtonPressed = true
  458. }
  459. }
  460. label: { Text("Continue without bolus") }
  461. .frame(maxWidth: .infinity, alignment: .center)
  462. .frame(minHeight: 50)
  463. .background(Color(.systemBlue))
  464. .clipShape(RoundedRectangle(cornerRadius: 8))
  465. .tint(.white)
  466. .padding()
  467. }.listRowBackground(Color.chart)
  468. }
  469. }.blur(radius: state.waitForSuggestion ? 5 : 0)
  470. if state.waitForSuggestion {
  471. CustomProgressView(text: progressText)
  472. }
  473. }
  474. .scrollContentBackground(.hidden).background(color)
  475. .blur(radius: showInfo ? 3 : 0)
  476. .navigationTitle("Treatments")
  477. .navigationBarTitleDisplayMode(.inline)
  478. .toolbar(content: {
  479. ToolbarItem(placement: .topBarLeading) {
  480. Button {
  481. state.hideModal()
  482. } label: {
  483. Text("Close")
  484. }
  485. }
  486. })
  487. .onAppear {
  488. configureView {
  489. state.insulinCalculated = state.calculateInsulin()
  490. }
  491. }
  492. .onDisappear {
  493. state.addButtonPressed = false
  494. }
  495. .sheet(isPresented: $showInfo) {
  496. calculationsDetailView
  497. .presentationDetents(
  498. [.fraction(0.9), .large],
  499. selection: $calculatorDetent
  500. )
  501. }
  502. }
  503. var progressText: String {
  504. switch (state.amount > 0, state.carbs > 0) {
  505. case (true, true):
  506. return "Updating COB and IOB..."
  507. case (false, true):
  508. return "Updating COB..."
  509. case (true, false):
  510. return "Updating IOB..."
  511. default:
  512. return "Updating Treatments..."
  513. }
  514. }
  515. var calcSettingsFirstRow: some View {
  516. GridRow {
  517. Group {
  518. Text("Carb Ratio:")
  519. .foregroundColor(.secondary)
  520. }.gridCellAnchor(.leading)
  521. Group {
  522. Text("ISF:")
  523. .foregroundColor(.secondary)
  524. }.gridCellAnchor(.leading)
  525. VStack {
  526. Text("Target:")
  527. .foregroundColor(.secondary)
  528. }.gridCellAnchor(.leading)
  529. }
  530. }
  531. var calcSettingsSecondRow: some View {
  532. GridRow {
  533. Text(state.carbRatio.formatted() + " " + NSLocalizedString("g/U", comment: " grams per Unit"))
  534. .gridCellAnchor(.leading)
  535. Text(
  536. state.isf.formatted() + " " + state.units
  537. .rawValue + NSLocalizedString("/U", comment: "/Insulin unit")
  538. ).gridCellAnchor(.leading)
  539. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  540. Text(
  541. target
  542. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  543. " " + state.units.rawValue
  544. ).gridCellAnchor(.leading)
  545. }
  546. }
  547. var calcGlucoseFirstRow: some View {
  548. GridRow(alignment: .center) {
  549. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  550. let target = state.units == .mmolL ? state.target.asMmolL : state.target
  551. Text("Glucose:").foregroundColor(.secondary)
  552. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  553. let firstRow = currentBG
  554. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  555. + " - " +
  556. target
  557. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  558. + " = " +
  559. targetDifference
  560. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  561. Text(firstRow).frame(minWidth: 0, alignment: .leading).foregroundColor(.secondary)
  562. .gridColumnAlignment(.leading)
  563. HStack {
  564. Text(
  565. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  566. )
  567. Text("U").foregroundColor(.secondary)
  568. }.fontWeight(.bold)
  569. .gridColumnAlignment(.trailing)
  570. }
  571. }
  572. var calcGlucoseSecondRow: some View {
  573. GridRow(alignment: .center) {
  574. let currentBG = state.units == .mmolL ? state.currentBG.asMmolL : state.currentBG
  575. Text(
  576. currentBG
  577. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  578. " " +
  579. state.units.rawValue
  580. )
  581. let targetDifference = state.units == .mmolL ? state.targetDifference.asMmolL : state.targetDifference
  582. let secondRow = targetDifference
  583. .formatted(
  584. .number.grouping(.never).rounded()
  585. .precision(.fractionLength(fractionDigits))
  586. )
  587. + " / " +
  588. state.isf.formatted()
  589. + " ≈ " +
  590. self.insulinRounder(state.targetDifferenceInsulin).formatted()
  591. Text(secondRow).foregroundColor(.secondary).gridColumnAlignment(.leading)
  592. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  593. }
  594. }
  595. var calcGlucoseFormulaRow: some View {
  596. GridRow(alignment: .top) {
  597. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  598. Text("(Current - Target) / ISF").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  599. .gridColumnAlignment(.leading)
  600. .gridCellColumns(2)
  601. }
  602. .font(.caption)
  603. }
  604. var calcIOBRow: some View {
  605. GridRow(alignment: .center) {
  606. HStack {
  607. Text("IOB:").foregroundColor(.secondary)
  608. Text(
  609. self.insulinRounder(state.iob).formatted()
  610. )
  611. }
  612. Text("Subtract IOB").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  613. let iobFormatted = self.insulinRounder(state.iob).formatted()
  614. HStack {
  615. Text((state.iob >= 0 ? "-" : "") + (state.iob >= 0 ? iobFormatted : "(" + iobFormatted + ")"))
  616. Text("U").foregroundColor(.secondary)
  617. }.fontWeight(.bold)
  618. .gridColumnAlignment(.trailing)
  619. }
  620. }
  621. var calcCOBRow: some View {
  622. GridRow(alignment: .center) {
  623. HStack {
  624. Text("COB:").foregroundColor(.secondary)
  625. Text(
  626. state.wholeCob
  627. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits))) +
  628. NSLocalizedString(" g", comment: "grams")
  629. )
  630. }
  631. Text(
  632. state.wholeCob
  633. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(fractionDigits)))
  634. + " / " +
  635. state.carbRatio.formatted()
  636. + " ≈ " +
  637. self.insulinRounder(state.wholeCobInsulin).formatted()
  638. )
  639. .foregroundColor(.secondary)
  640. .gridColumnAlignment(.leading)
  641. HStack {
  642. Text(
  643. self.insulinRounder(state.wholeCobInsulin).formatted()
  644. )
  645. Text("U").foregroundColor(.secondary)
  646. }.fontWeight(.bold)
  647. .gridColumnAlignment(.trailing)
  648. }
  649. }
  650. var calcCOBFormulaRow: some View {
  651. GridRow(alignment: .center) {
  652. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  653. Text("COB / Carb Ratio").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  654. .gridColumnAlignment(.leading)
  655. .gridCellColumns(2)
  656. }
  657. .font(.caption)
  658. }
  659. var calcDeltaRow: some View {
  660. GridRow(alignment: .center) {
  661. Text("Delta:").foregroundColor(.secondary)
  662. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  663. Text(
  664. deltaBG
  665. .formatted(
  666. .number.grouping(.never).rounded()
  667. .precision(.fractionLength(fractionDigits))
  668. )
  669. + " / " +
  670. state.isf.formatted()
  671. + " ≈ " +
  672. self.insulinRounder(state.fifteenMinInsulin).formatted()
  673. )
  674. .foregroundColor(.secondary)
  675. .gridColumnAlignment(.leading)
  676. HStack {
  677. Text(
  678. self.insulinRounder(state.fifteenMinInsulin).formatted()
  679. )
  680. Text("U").foregroundColor(.secondary)
  681. }.fontWeight(.bold)
  682. .gridColumnAlignment(.trailing)
  683. }
  684. }
  685. var calcDeltaFormulaRow: some View {
  686. GridRow(alignment: .center) {
  687. let deltaBG = state.units == .mmolL ? state.deltaBG.asMmolL : state.deltaBG
  688. Text(
  689. deltaBG
  690. .formatted(
  691. .number.grouping(.never).rounded()
  692. .precision(.fractionLength(fractionDigits))
  693. ) + " " +
  694. state.units.rawValue
  695. )
  696. Text("15min Delta / ISF").font(.caption).foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  697. .gridColumnAlignment(.leading)
  698. .gridCellColumns(2).padding(.top, 5)
  699. }
  700. }
  701. var calcFullBolusRow: some View {
  702. GridRow(alignment: .center) {
  703. Text("Full Bolus")
  704. .foregroundColor(.secondary)
  705. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  706. HStack {
  707. Text(self.insulinRounder(state.wholeCalc).formatted())
  708. .foregroundStyle(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  709. Text("U").foregroundColor(.secondary)
  710. }.gridColumnAlignment(.trailing)
  711. .fontWeight(.bold)
  712. }
  713. }
  714. var calcSuperBolusRow: some View {
  715. GridRow(alignment: .center) {
  716. Text("Super Bolus")
  717. .foregroundColor(.secondary)
  718. Text("Added to Result").foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8)).font(.footnote)
  719. HStack {
  720. Text("+" + self.insulinRounder(state.superBolusInsulin).formatted())
  721. .foregroundStyle(Color.loopRed)
  722. Text("U").foregroundColor(.secondary)
  723. }.gridColumnAlignment(.trailing)
  724. .fontWeight(.bold)
  725. }
  726. }
  727. var calcResultRow: some View {
  728. GridRow(alignment: .center) {
  729. Text("Result").fontWeight(.bold)
  730. HStack {
  731. Text(state.useSuperBolus ? "(" : "")
  732. .foregroundColor(.loopRed)
  733. + Text(state.fraction.formatted())
  734. + Text(" x ")
  735. .foregroundColor(.secondary)
  736. // if fatty meal is chosen
  737. + Text(state.useFattyMealCorrectionFactor ? state.fattyMealFactor.formatted() : "")
  738. .foregroundColor(.orange)
  739. + Text(state.useFattyMealCorrectionFactor ? " x " : "")
  740. .foregroundColor(.secondary)
  741. // endif fatty meal is chosen
  742. + Text(self.insulinRounder(state.wholeCalc).formatted())
  743. .foregroundColor(state.wholeCalc < 0 ? Color.loopRed : Color.primary)
  744. // if superbolus is chosen
  745. + Text(state.useSuperBolus ? ")" : "")
  746. .foregroundColor(.loopRed)
  747. + Text(state.useSuperBolus ? " + " : "")
  748. .foregroundColor(.secondary)
  749. + Text(state.useSuperBolus ? state.superBolusInsulin.formatted() : "")
  750. .foregroundColor(.loopRed)
  751. // endif superbolus is chosen
  752. + Text(" ≈ ")
  753. .foregroundColor(.secondary)
  754. }
  755. .gridColumnAlignment(.leading)
  756. HStack {
  757. Text(self.insulinRounder(state.insulinCalculated).formatted())
  758. .fontWeight(.bold)
  759. .foregroundColor(state.wholeCalc >= state.maxBolus ? Color.loopRed : Color.blue)
  760. Text("U").foregroundColor(.secondary)
  761. }
  762. .gridColumnAlignment(.trailing)
  763. .fontWeight(.bold)
  764. }
  765. }
  766. var calcResultFormulaRow: some View {
  767. GridRow(alignment: .bottom) {
  768. if state.useFattyMealCorrectionFactor {
  769. Group {
  770. Text("Factor x Fatty Meal Factor x Full Bolus")
  771. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  772. +
  773. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  774. }
  775. .font(.caption)
  776. .gridCellAnchor(.center)
  777. .gridCellColumns(3)
  778. } else if state.useSuperBolus {
  779. Group {
  780. Text("(Factor x Full Bolus) + Super Bolus")
  781. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  782. +
  783. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  784. }
  785. .font(.caption)
  786. .gridCellAnchor(.center)
  787. .gridCellColumns(3)
  788. } else {
  789. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  790. Group {
  791. Text("Factor x Full Bolus")
  792. .foregroundColor(.secondary.opacity(colorScheme == .dark ? 0.65 : 0.8))
  793. +
  794. Text(state.wholeCalc > state.maxBolus ? " ≈ Max Bolus" : "").foregroundColor(Color.loopRed)
  795. }
  796. .font(.caption)
  797. .padding(.top, 5)
  798. .gridCellAnchor(.leading)
  799. .gridCellColumns(2)
  800. }
  801. }
  802. }
  803. var calculationsDetailView: some View {
  804. NavigationStack {
  805. ScrollView {
  806. Grid(alignment: .topLeading, horizontalSpacing: 3, verticalSpacing: 0) {
  807. GridRow {
  808. Text("Calculations").fontWeight(.bold).gridCellColumns(3).gridCellAnchor(.center).padding(.vertical)
  809. }
  810. calcSettingsFirstRow
  811. calcSettingsSecondRow
  812. DividerCustom()
  813. // meal entries as grid rows
  814. if state.carbs > 0 {
  815. GridRow {
  816. Text("Carbs").foregroundColor(.secondary)
  817. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  818. HStack {
  819. Text(state.carbs.formatted())
  820. Text("g").foregroundColor(.secondary)
  821. }.gridCellAnchor(.trailing)
  822. }
  823. }
  824. if state.fat > 0 {
  825. GridRow {
  826. Text("Fat").foregroundColor(.secondary)
  827. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  828. HStack {
  829. Text(state.fat.formatted())
  830. Text("g").foregroundColor(.secondary)
  831. }.gridCellAnchor(.trailing)
  832. }
  833. }
  834. if state.protein > 0 {
  835. GridRow {
  836. Text("Protein").foregroundColor(.secondary)
  837. Color.clear.gridCellUnsizedAxes([.horizontal, .vertical])
  838. HStack {
  839. Text(state.protein.formatted())
  840. Text("g").foregroundColor(.secondary)
  841. }.gridCellAnchor(.trailing)
  842. }
  843. }
  844. if state.carbs > 0 || state.protein > 0 || state.fat > 0 {
  845. DividerCustom()
  846. }
  847. GridRow {
  848. Text("Detailed Calculation Steps").gridCellColumns(3).gridCellAnchor(.center)
  849. .padding(.bottom, 10)
  850. }
  851. calcGlucoseFirstRow
  852. calcGlucoseSecondRow.padding(.bottom, 5)
  853. calcGlucoseFormulaRow
  854. DividerCustom()
  855. calcIOBRow
  856. DividerCustom()
  857. calcCOBRow.padding(.bottom, 5)
  858. calcCOBFormulaRow
  859. DividerCustom()
  860. calcDeltaRow
  861. calcDeltaFormulaRow
  862. DividerCustom()
  863. calcFullBolusRow
  864. if state.useSuperBolus {
  865. DividerCustom()
  866. calcSuperBolusRow
  867. }
  868. DividerDouble()
  869. calcResultRow
  870. calcResultFormulaRow
  871. }
  872. Spacer()
  873. Button { showInfo = false }
  874. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  875. .buttonStyle(.bordered)
  876. .padding(.top)
  877. }
  878. .padding([.horizontal, .bottom])
  879. .font(.system(size: 15))
  880. }
  881. }
  882. private func insulinRounder(_ value: Decimal) -> Decimal {
  883. let toRound = NSDecimalNumber(decimal: value).doubleValue
  884. return Decimal(floor(100 * toRound) / 100)
  885. }
  886. private var limitPumpBolus: Bool {
  887. state.amount <= 0 || state.amount > state.maxBolus
  888. }
  889. // MARK: DEFINITIONS FOR ADDING EXTERNAL INSULIN
  890. private var limitManualBolus: Bool {
  891. state.amount <= 0 || state.amount > state.maxBolus * 3
  892. }
  893. private var logExternalInsulinBackground: Color {
  894. if state.amount > state.maxBolus {
  895. return Color.red
  896. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  897. return Color(.systemGray4)
  898. } else {
  899. return Color(.systemBlue)
  900. }
  901. }
  902. private var logExternalInsulinForeground: Color {
  903. if state.amount > state.maxBolus {
  904. return Color.white
  905. } else if state.amount <= 0 || state.amount > state.maxBolus * 3 {
  906. return Color.secondary
  907. } else {
  908. return Color.white
  909. }
  910. }
  911. }
  912. struct DividerDouble: View {
  913. var body: some View {
  914. VStack(spacing: 2) {
  915. Rectangle()
  916. .frame(height: 1)
  917. .foregroundColor(.gray.opacity(0.65))
  918. Rectangle()
  919. .frame(height: 1)
  920. .foregroundColor(.gray.opacity(0.65))
  921. }
  922. .frame(height: 4)
  923. .padding(.vertical)
  924. }
  925. }
  926. struct DividerCustom: View {
  927. var body: some View {
  928. Rectangle()
  929. .frame(height: 1)
  930. .foregroundColor(.gray.opacity(0.65))
  931. .padding(.vertical)
  932. }
  933. }
  934. }