PopupView.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. import SwiftUI
  2. // MARK: - Style Extensions
  3. // View modifiers that provide consistent styling across calculation components.
  4. // These extensions establish a visual hierarchy through font sizing, coloring, and layout priorities.
  5. private extension View {
  6. /// Applies secondary label styling for descriptive text elements.
  7. /// Uses a smaller font with secondary color to visually distinguish labels from values.
  8. /// Layout priority ensures these elements maintain appropriate space.
  9. func secondaryStyle() -> some View {
  10. font(.footnote)
  11. .foregroundStyle(.secondary)
  12. .allowsTightening(true)
  13. .minimumScaleFactor(0.5)
  14. .layoutPriority(1)
  15. }
  16. /// Applies unit label styling for measurement units (mg/dL, mmol/L, U, g, etc.)
  17. /// Uses the smallest font size with secondary color to de-emphasize units.
  18. /// Low layout priority ensures units don't compete for space with values.
  19. func unitStyle() -> some View {
  20. font(.caption2)
  21. .foregroundStyle(.secondary)
  22. .allowsTightening(true)
  23. .minimumScaleFactor(0.5)
  24. .layoutPriority(-1)
  25. }
  26. /// Applies mathematical operator label styling (+, -, ×, ÷, =, etc.)
  27. /// Medium priority ensures operators maintain proper spacing between values
  28. /// while allowing compression when space is limited.
  29. func operatorStyle() -> some View {
  30. font(.body)
  31. .foregroundStyle(.secondary)
  32. .allowsTightening(true)
  33. .minimumScaleFactor(0.5)
  34. .layoutPriority(3)
  35. }
  36. /// Applies styling for numeric values in calculations.
  37. /// Higher layout priority (5) ensures values maintain visibility when space is constrained.
  38. /// Minimum width prevents values from becoming too compressed.
  39. func valueStyle() -> some View {
  40. font(.headline)
  41. .frame(minWidth: 50)
  42. .allowsTightening(true)
  43. .minimumScaleFactor(0.5)
  44. .lineLimit(1)
  45. .layoutPriority(5)
  46. }
  47. /// Applies styling for calculation results with dynamic coloring based on value.
  48. /// - Parameter value: The numeric value to display, which determines color:
  49. /// - Negative values: Red (indicating insulin reduction)
  50. /// - Zero: Primary color
  51. /// - Positive values: Green (indicating insulin addition)
  52. /// Highest layout priority (10) ensures results remain visible even in constrained layouts.
  53. func solutionStyle(_ value: Decimal = 0) -> some View {
  54. let solutionColor: Color
  55. switch value {
  56. case ..<0:
  57. solutionColor = .red
  58. case 0:
  59. solutionColor = .primary
  60. default:
  61. solutionColor = .green
  62. }
  63. return font(.system(.headline, weight: .bold))
  64. .frame(minWidth: 45, alignment: .center)
  65. .foregroundStyle(solutionColor)
  66. .allowsTightening(true)
  67. .fixedSize(horizontal: true, vertical: true)
  68. .minimumScaleFactor(0.5)
  69. .layoutPriority(10)
  70. .lineLimit(1)
  71. }
  72. /// Applies styling for the final recommendation value.
  73. /// Uses larger font size than regular solutions to emphasize the final result.
  74. /// Maintains highest layout priority to ensure visibility.
  75. func largeSolutionStyle() -> some View {
  76. font(.system(.title3, weight: .bold))
  77. .allowsTightening(true)
  78. .fixedSize(horizontal: true, vertical: true)
  79. .minimumScaleFactor(0.5)
  80. .layoutPriority(10)
  81. .lineLimit(1)
  82. }
  83. /// Applies styling for warning labels.
  84. /// - Parameter warningColor: The color of the text.
  85. func warningStyle(_ warningColor: Color) -> some View {
  86. font(.subheadline)
  87. .foregroundStyle(warningColor)
  88. .allowsTightening(true)
  89. .minimumScaleFactor(0.5)
  90. }
  91. /// Reduces the default inset padding of List Sections for more compact presentation.
  92. /// Creates tighter spacing in the calculation cards.
  93. func listRowStyle() -> some View {
  94. listRowInsets(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
  95. }
  96. }
  97. // MARK: - Main PopupView
  98. // A detailed view presenting all components of the bolus calculation.
  99. // Displays breakdown of calculations in separate cards within a scrollable list,
  100. // with a sticky recommendation card at the bottom.
  101. struct PopupView: View {
  102. @Environment(\.colorScheme) var colorScheme
  103. /// State model containing all calculation parameters and results.
  104. var state: Treatments.StateModel
  105. /// Controls the preferred presentation size of the popup.
  106. @State private var calcPopupDetent = PresentationDetent.large
  107. /// Trigger for flashing scroll indicators when view appears.
  108. /// Helps users discover scrollable content.
  109. @State private var shouldFlashScroll = false
  110. var body: some View {
  111. NavigationStack {
  112. VStack(alignment: .center) {
  113. // List of calculation cards organized in sections.
  114. // Each section represents a component of the final calculation.
  115. List {
  116. Section("Glucose Calculation") {
  117. glucoseCardContent.listRowStyle()
  118. }
  119. Section("Insulin On Board (IOB)") {
  120. iobCardContent.listRowStyle()
  121. }
  122. Section("Carbs On Board (COB)") {
  123. cobCardContent.listRowStyle()
  124. }
  125. Section("Glucose Trend (15 min)") {
  126. deltaCardContent.listRowStyle()
  127. }
  128. Section("Full Bolus") {
  129. fullBolusCardContent.listRowStyle()
  130. }
  131. // Conditional sections based on user's selection of the "Super Bolus" option.
  132. if state.useSuperBolus {
  133. Section("Super Bolus") {
  134. superBolusCardContent.listRowStyle()
  135. }
  136. }
  137. // If the solution of this card does not recommend any insulin,
  138. // there's no point in showing it
  139. if state.factoredInsulin > 0 {
  140. Section("Applied Factors") {
  141. factorsCardContent.listRowStyle()
  142. }
  143. }
  144. }
  145. .frame(maxWidth: .infinity)
  146. .listStyle(InsetGroupedListStyle())
  147. .listSectionSpacing(0)
  148. .scrollIndicatorsFlash(trigger: shouldFlashScroll)
  149. .onAppear {
  150. // Flash scroll indicators after a short delay to help users discover scrollable content.
  151. // The delay allows the sheet presentation animation to complete first.
  152. DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
  153. shouldFlashScroll = true
  154. }
  155. }
  156. // Sticky footer with recommendation and dismiss button.
  157. // Remains visible regardless of scroll position.
  158. VStack(alignment: .center, spacing: 10) {
  159. recommendedBolusCard
  160. Button {
  161. state.showInfo = false
  162. } label: {
  163. Text("Got it!").bold()
  164. .frame(maxWidth: .infinity, minHeight: 30)
  165. }
  166. .buttonStyle(.bordered)
  167. }
  168. .padding([.horizontal, .bottom])
  169. }
  170. .navigationBarTitle(String(localized: "Bolus Calculator Details"), displayMode: .inline)
  171. .presentationDetents(
  172. [.fraction(0.9), .large],
  173. selection: $calcPopupDetent
  174. )
  175. }
  176. }
  177. // MARK: - Calculation Card Contents
  178. // Each card visualizes a specific component of the bolus calculation.
  179. // The cards use Grid layout to show mathematical formulas with proper alignment
  180. // of the variable's name as the header and the units used as the footer.
  181. // Inifinity frame on "=" operator aligns the formula to the left and the solution to the right of the row.
  182. /// Card showing insulin required to get current glucose to the target glucose based on insulin sensitivity.
  183. /// Formula: (Current Glucose - Target Glucose) / ISF = Glucose Correction Dose
  184. private var glucoseCardContent: some View {
  185. Grid(alignment: .center) {
  186. // Row 1: Column headers for the calculation components
  187. GridRow(alignment: .lastTextBaseline) {
  188. Text("Current")
  189. .gridCellColumns(3) // Allows label to expand above operators.
  190. Text("Target")
  191. Text("")
  192. .layoutPriority(-15)
  193. .gridCellColumns(2)
  194. Text("ISF")
  195. }
  196. .secondaryStyle()
  197. // Row 2: The calculation formula with values and operators
  198. GridRow {
  199. Text("(")
  200. .operatorStyle()
  201. Text(state.units == .mmolL ? state.currentBG.formattedAsMmolL : state.currentBG.description)
  202. .valueStyle()
  203. Text("−")
  204. .operatorStyle()
  205. Text(state.units == .mmolL ? state.target.formattedAsMmolL : state.target.description)
  206. .valueStyle()
  207. Text(")")
  208. .operatorStyle()
  209. Text("/")
  210. .operatorStyle()
  211. Text(state.units == .mmolL ? state.isf.formattedAsMmolL : state.isf.description)
  212. .valueStyle()
  213. Text("=")
  214. .operatorStyle()
  215. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  216. .layoutPriority(-15)
  217. Text(insulinFormatter(state.targetDifferenceInsulin))
  218. .solutionStyle(state.targetDifferenceInsulin)
  219. }
  220. // Row 3: Units for each value
  221. GridRow(alignment: .firstTextBaseline) {
  222. Text(state.units.rawValue)
  223. .gridCellColumns(3) // Allows cell to expand below operators.
  224. Text(state.units.rawValue)
  225. Text("")
  226. .layoutPriority(-15)
  227. .gridCellColumns(2)
  228. Text("\(state.units.rawValue)/U")
  229. Text("")
  230. .layoutPriority(-15)
  231. Text("U")
  232. }
  233. .unitStyle()
  234. }
  235. .multilineTextAlignment(.center)
  236. }
  237. /// Card showing offset of current insulin on board (IOB).
  238. /// If current IOB is already positive, reduce the insulin recommendation,
  239. /// but if negative then increase the insulin recommendation.
  240. /// Formula: -1 × Current IOB = IOB Correction Dose
  241. private var iobCardContent: some View {
  242. Grid(alignment: .center) {
  243. // Row 1: Column header
  244. GridRow(alignment: .lastTextBaseline) {
  245. Text("")
  246. .layoutPriority(-15)
  247. .gridCellColumns(2)
  248. Text("IOB")
  249. }
  250. .secondaryStyle()
  251. // Row 2: The IOB calculation formula
  252. GridRow {
  253. Text("-1")
  254. .valueStyle()
  255. Text("×")
  256. .operatorStyle()
  257. Text(insulinFormatter(state.iob, .plain)) // Use .plain rounding to match inverted value.
  258. .valueStyle()
  259. Text("=").operatorStyle()
  260. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  261. .layoutPriority(-15)
  262. Text(insulinFormatter(-1 * state.iob, .plain)) // Use .plain rounding to match inverted value.
  263. .solutionStyle(-1 * state.iob)
  264. }
  265. // Row 3: Units
  266. GridRow(alignment: .firstTextBaseline) {
  267. Text("")
  268. .layoutPriority(-15)
  269. .gridCellColumns(2)
  270. Text("U")
  271. Text("")
  272. .layoutPriority(-15)
  273. Text("U")
  274. }
  275. .unitStyle()
  276. }
  277. .multilineTextAlignment(.center)
  278. }
  279. /// Card showing insulin required to offset meals. Combine current carbs on board (COB)
  280. /// with new carbs entered in the Treatment view and divide by the carb ratio.
  281. /// Don't allow total carbs to exceed Max IOB setting.
  282. /// Formula: (Current COB + New Carbs) / Carb Ratio = COB Correction Dose
  283. private var cobCardContent: some View {
  284. // Check if this is a backdated entry by comparing with the default date using a tolerance
  285. let isBackdated = abs(state.date.timeIntervalSince(state.defaultDate)) > 1.0
  286. // Determine COB and carbs to display based on backdating status
  287. let displayedCOB = isBackdated ? (state.simulatedDetermination?.cob ?? Decimal(state.cob)) : Decimal(state.cob)
  288. let displayedCarbs = isBackdated ? 0 : state.carbs
  289. let hasExceededMaxCOB: Bool = displayedCOB + displayedCarbs > state.maxCOB
  290. return Group {
  291. Grid(alignment: .center) {
  292. // Row 1: Column headers for the COB calculation
  293. GridRow(alignment: .lastTextBaseline) {
  294. Text("")
  295. .layoutPriority(-15)
  296. Text("COB")
  297. Text("Carbs")
  298. .gridCellColumns(3) // Allows label to expand above operators.
  299. Text("")
  300. .layoutPriority(-15)
  301. Text("CR")
  302. }
  303. .secondaryStyle()
  304. // Row 2: The full COB calculation formula
  305. // Don't include solution when Max IOB has been exceeded
  306. GridRow {
  307. Text("(")
  308. .operatorStyle()
  309. Text(Int(displayedCOB).description)
  310. .valueStyle()
  311. Text("+")
  312. .operatorStyle()
  313. Text(Int(displayedCarbs).description)
  314. .valueStyle()
  315. Text(")")
  316. .operatorStyle()
  317. Text("/")
  318. .operatorStyle()
  319. Text(state.carbRatio.formatted())
  320. .valueStyle()
  321. Text("=")
  322. .operatorStyle()
  323. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  324. .layoutPriority(-15)
  325. if !hasExceededMaxCOB {
  326. Text(insulinFormatter(state.wholeCobInsulin))
  327. .solutionStyle(state.wholeCobInsulin)
  328. }
  329. }
  330. // Row 3: Units for each component
  331. // Don't show solution's unit if Max COB has been exceeded
  332. GridRow(alignment: .firstTextBaseline) {
  333. Text("")
  334. .layoutPriority(-15)
  335. Text("g")
  336. Text("")
  337. .layoutPriority(-15)
  338. Text("g")
  339. Text("")
  340. .layoutPriority(-15)
  341. .gridCellColumns(2)
  342. Text("g/U")
  343. if !hasExceededMaxCOB {
  344. Text("")
  345. .layoutPriority(-15)
  346. Text("U")
  347. }
  348. }
  349. .unitStyle()
  350. }
  351. .multilineTextAlignment(.center)
  352. if isBackdated {
  353. Text("Backdated carbs (\(Int(state.carbs)) g) included in COB calculation")
  354. .font(.caption)
  355. .foregroundStyle(.orange)
  356. .padding(.top, 4)
  357. }
  358. // Additional grid only displayed when Max COB limit has been exceeded
  359. if hasExceededMaxCOB {
  360. Grid(alignment: .center) {
  361. // Row 4: Alternative calculation headers (max COB)
  362. GridRow(alignment: .lastTextBaseline) {
  363. Text("Max COB")
  364. Text("")
  365. .layoutPriority(-15)
  366. Text("CR")
  367. }
  368. .secondaryStyle()
  369. // Row 5: Alternative calculation with max COB
  370. // Shows: Max COB / Carb Ratio = Limited COB Insulin
  371. GridRow {
  372. Text(Int(state.wholeCob).description)
  373. .valueStyle()
  374. .foregroundStyle(.orange)
  375. Text("/")
  376. .operatorStyle()
  377. Text(state.carbRatio.formatted())
  378. .valueStyle()
  379. Text("=").operatorStyle()
  380. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  381. .layoutPriority(-15)
  382. Text(insulinFormatter(state.wholeCobInsulin))
  383. .solutionStyle(state.wholeCobInsulin)
  384. }
  385. // Row 6: Units for max COB calculation
  386. GridRow(alignment: .firstTextBaseline) {
  387. Text("g")
  388. Text("")
  389. .layoutPriority(-15)
  390. Text("g/U")
  391. Text("")
  392. .layoutPriority(-15)
  393. Text("U")
  394. }
  395. .unitStyle()
  396. }
  397. .multilineTextAlignment(.center)
  398. }
  399. }
  400. }
  401. /// Card showing inslin required to offset glucose trend from past 15 minutes
  402. /// Formula: Change in Glucose / ISF = Glucose Trend Correction Dose
  403. private var deltaCardContent: some View {
  404. Grid(alignment: .center) {
  405. // Row 1: Column headers
  406. GridRow(alignment: .lastTextBaseline) {
  407. Text("Delta")
  408. Text("")
  409. .layoutPriority(-15)
  410. Text("ISF")
  411. }
  412. .secondaryStyle()
  413. // Row 2: The delta calculation formula
  414. GridRow {
  415. Text(state.units == .mmolL ? state.deltaBG.formattedAsMmolL : state.deltaBG.description)
  416. .valueStyle()
  417. Text("/")
  418. .operatorStyle()
  419. Text(state.units == .mmolL ? state.isf.formattedAsMmolL : state.isf.description)
  420. .valueStyle()
  421. Text("=")
  422. .operatorStyle()
  423. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  424. .layoutPriority(-15)
  425. Text(insulinFormatter(state.fifteenMinInsulin))
  426. .solutionStyle(state.fifteenMinInsulin)
  427. }
  428. // Row 3: Units for each component
  429. GridRow(alignment: .firstTextBaseline) {
  430. Text(state.units.rawValue)
  431. Text("")
  432. .layoutPriority(-15)
  433. Text("\(state.units.rawValue)/U")
  434. Text("")
  435. .layoutPriority(-15)
  436. Text("U")
  437. }
  438. .unitStyle()
  439. }
  440. .multilineTextAlignment(.center)
  441. }
  442. /// Card showing combined calculation for full bolus (before factors)
  443. /// Combines all four individual components into a single dose.
  444. /// Formula: Glucose Dose + IOB Dose + COB Dose + Delta Dose = Full Bolus
  445. private var fullBolusCardContent: some View {
  446. Group {
  447. Grid(alignment: .center, horizontalSpacing: 1) {
  448. // Row 1: Column headers
  449. GridRow(alignment: .lastTextBaseline) {
  450. Text("Glucose")
  451. Text("")
  452. .layoutPriority(-15)
  453. Text("IOB")
  454. Text("")
  455. .layoutPriority(-15)
  456. Text("COB")
  457. Text("")
  458. .layoutPriority(-15)
  459. Text("Delta")
  460. }
  461. .secondaryStyle()
  462. // Row 2: The full bolus calculation formula components. (Values only.)
  463. // Infinity frames on operators distributes the formula across the entire row.
  464. GridRow {
  465. Text(wrapNegative(state.targetDifferenceInsulin))
  466. .valueStyle()
  467. Text("+")
  468. .operatorStyle()
  469. .frame(maxWidth: .infinity)
  470. Text(wrapNegative(-1 * state.iob, .plain))
  471. .valueStyle()
  472. Text("+")
  473. .operatorStyle()
  474. .frame(maxWidth: .infinity)
  475. Text(wrapNegative(state.wholeCobInsulin))
  476. .valueStyle()
  477. Text("+")
  478. .operatorStyle()
  479. .frame(maxWidth: .infinity)
  480. Text(wrapNegative(state.fifteenMinInsulin))
  481. .valueStyle()
  482. }
  483. // Row 3: Units for each component.
  484. GridRow(alignment: .firstTextBaseline) {
  485. Text("U")
  486. Text("")
  487. .layoutPriority(-15)
  488. Text("U")
  489. Text("")
  490. .layoutPriority(-15)
  491. Text("U")
  492. Text("")
  493. .layoutPriority(-15)
  494. Text("U")
  495. }
  496. .unitStyle()
  497. }
  498. .multilineTextAlignment(.center)
  499. // Row 4: Sum/total of all components, aligned right.
  500. HStack(alignment: .center, spacing: 4) {
  501. Spacer()
  502. Text("=")
  503. .operatorStyle()
  504. HStack(alignment: .firstTextBaseline, spacing: 4) {
  505. Text(insulinFormatter(state.wholeCalc))
  506. .solutionStyle(state.wholeCalc)
  507. Text("U")
  508. .secondaryStyle()
  509. }
  510. }
  511. }
  512. }
  513. /// Card showing Super Bolus calculation (if selected by user).
  514. /// Converts a portion of basal insulin into immediate bolus for stronger bolus recommendation.
  515. /// Formula: Basal Rate × Super Bolus % = Super Bolus Insulin
  516. private var superBolusCardContent: some View {
  517. Grid(alignment: .center) {
  518. // Row 1: Column headers.
  519. GridRow(alignment: .lastTextBaseline) {
  520. Text("Basal Rate")
  521. Text("")
  522. .layoutPriority(-15)
  523. Text("Super Bolus %")
  524. .frame(minWidth: 90) // Discourages wrapping this cell into multiple lines.
  525. }
  526. .secondaryStyle()
  527. // Row 2: The super bolus calculation formula.
  528. GridRow {
  529. Text("\(state.currentBasal)")
  530. .valueStyle()
  531. Text("×")
  532. .operatorStyle()
  533. Text((100 * state.sweetMealFactor).formatted() + " %")
  534. .valueStyle()
  535. Text("=").operatorStyle()
  536. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  537. .layoutPriority(-15)
  538. Text(insulinFormatter(state.superBolusInsulin))
  539. .solutionStyle(state.superBolusInsulin)
  540. }
  541. // Row 3: Units for each component.
  542. GridRow(alignment: .firstTextBaseline) {
  543. Text("U/hr")
  544. Text("")
  545. .layoutPriority(-15)
  546. .gridCellColumns(3)
  547. Text("U")
  548. }
  549. .unitStyle()
  550. }
  551. .multilineTextAlignment(.center)
  552. }
  553. /// Card showing applied factors to the final insulin calculation.
  554. /// Dynamically changes card based on user's selection in the Treatment view.
  555. /// User can choose Reduced Bolus, Super Bolus, or neither, but not both.
  556. private var factorsCardContent: some View {
  557. Grid(alignment: .center) {
  558. // Choose the layout based on which options are selected
  559. switch (state.useSuperBolus, state.useFattyMealCorrectionFactor) {
  560. // Simple case: just Full Bolus × Rec. Bolus %
  561. case (false, false):
  562. // Row 1: Header.
  563. GridRow(alignment: .lastTextBaseline) {
  564. Text("Full Bolus")
  565. Text("")
  566. .layoutPriority(-15)
  567. Text("Rec. Bolus %")
  568. }
  569. .secondaryStyle()
  570. // Row 2: Formula.
  571. GridRow {
  572. Text(insulinFormatter(state.wholeCalc))
  573. .valueStyle()
  574. Text("×")
  575. .operatorStyle()
  576. Text((100 * state.fraction).formatted() + " %")
  577. .valueStyle()
  578. Text("=")
  579. .operatorStyle()
  580. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  581. .layoutPriority(-15)
  582. Text(insulinFormatter(state.factoredInsulin))
  583. .solutionStyle(state.factoredInsulin)
  584. }
  585. // Row 3: Units.
  586. GridRow(alignment: .firstTextBaseline) {
  587. Text("U")
  588. Text("")
  589. .layoutPriority(-15)
  590. .gridCellColumns(3)
  591. Text("U")
  592. }
  593. .unitStyle()
  594. // Case: Full Bolus × Rec. Bolus % × Reduced Bolus %
  595. case (false, true):
  596. // Row 1: Header.
  597. GridRow(alignment: .lastTextBaseline) {
  598. Text("Full Bolus")
  599. Text("")
  600. .layoutPriority(-15)
  601. Text("Rec. Bolus %")
  602. Text("")
  603. .layoutPriority(-15)
  604. Text("Red. Bolus %")
  605. }
  606. .secondaryStyle()
  607. // Row 2: Formula.
  608. GridRow {
  609. Text(insulinFormatter(state.wholeCalc)).valueStyle()
  610. Text("×")
  611. .operatorStyle()
  612. Text((100 * state.fraction).formatted() + " %")
  613. .valueStyle()
  614. Text("×")
  615. .operatorStyle()
  616. Text((100 * state.fattyMealFactor).formatted() + " %")
  617. .valueStyle()
  618. Text("=")
  619. .operatorStyle()
  620. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  621. .layoutPriority(-15)
  622. Text(insulinFormatter(state.factoredInsulin))
  623. .solutionStyle(state.factoredInsulin)
  624. }
  625. // Row 3: Units.
  626. GridRow(alignment: .firstTextBaseline) {
  627. Text("U")
  628. Text("")
  629. .layoutPriority(-15)
  630. Text("U")
  631. }
  632. .unitStyle()
  633. // Case: (Full Bolus × Rec. Bolus %) + Super Bolus
  634. case (true, false):
  635. if state.wholeCalc > 0 {
  636. // Row 1: Header.
  637. GridRow(alignment: .lastTextBaseline) {
  638. Text("Full Bolus")
  639. .gridCellColumns(3) // Allows label to expand above operators.
  640. Text("Rec. %")
  641. Text("")
  642. .layoutPriority(-15)
  643. .gridCellColumns(2)
  644. Text("Super Bolus")
  645. }
  646. .secondaryStyle()
  647. // Row 2: Formula.
  648. GridRow {
  649. Text("(")
  650. .operatorStyle()
  651. Text(insulinFormatter(state.wholeCalc)).valueStyle()
  652. Text("×")
  653. .operatorStyle()
  654. Text((100 * state.fraction).formatted() + " %")
  655. .valueStyle()
  656. Text(")")
  657. .operatorStyle()
  658. Text("+")
  659. .operatorStyle()
  660. Text(insulinFormatter(state.superBolusInsulin))
  661. .valueStyle()
  662. Text("=")
  663. .operatorStyle()
  664. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  665. .layoutPriority(-15)
  666. Text(insulinFormatter(state.factoredInsulin))
  667. .solutionStyle(state.factoredInsulin)
  668. }
  669. // Row 3: Units.
  670. GridRow(alignment: .firstTextBaseline) {
  671. Text("")
  672. .layoutPriority(-15)
  673. Text("U")
  674. Text("")
  675. .layoutPriority(-15)
  676. .gridCellColumns(4)
  677. Text("U")
  678. Text("")
  679. .layoutPriority(-15)
  680. Text("U")
  681. }
  682. .unitStyle()
  683. } else {
  684. // Row 1: Header.
  685. GridRow(alignment: .lastTextBaseline) {
  686. Text("Full Bolus")
  687. Text("")
  688. .layoutPriority(-15)
  689. Text("Super Bolus")
  690. }
  691. .secondaryStyle()
  692. // Row 2: Formula.
  693. GridRow {
  694. Text(insulinFormatter(state.wholeCalc)).valueStyle()
  695. Text("+")
  696. .operatorStyle()
  697. Text(insulinFormatter(state.superBolusInsulin))
  698. .valueStyle()
  699. Text("=")
  700. .operatorStyle()
  701. .frame(idealWidth: 10, maxWidth: .infinity, alignment: .trailing)
  702. .layoutPriority(-15)
  703. Text(insulinFormatter(state.factoredInsulin))
  704. .solutionStyle(state.factoredInsulin)
  705. }
  706. // Row 3: Units.
  707. GridRow(alignment: .firstTextBaseline) {
  708. Text("U")
  709. Text("")
  710. .layoutPriority(-15)
  711. Text("U")
  712. Text("")
  713. .layoutPriority(-15)
  714. Text("U")
  715. }
  716. .unitStyle()
  717. }
  718. // This case should never occur as you can't apply a Super Bolus to a Fatty Meal
  719. // Per app logic, these options are mutually exclusive
  720. case (true, true):
  721. Text("")
  722. .layoutPriority(-15)
  723. }
  724. }
  725. .multilineTextAlignment(.center)
  726. }
  727. // MARK: - Result Section
  728. // Final recommendation display with warning conditions and limitations
  729. /// Recommended bolus card that stays fixed at bottom of the view
  730. /// Displays final calculated insulin amount with warnings based on various conditions:
  731. /// - Loop staleness
  732. /// - Very low glucose (current or forecasted)
  733. /// - Max bolus limits
  734. /// - Available IOB limits
  735. private var recommendedBolusCard: some View {
  736. /// Amount of insulin that can be dosed without exceeding Max IOB.
  737. let iobAvailable: Decimal = state.maxIOB - state.iob
  738. /// Checks if last loop was over 15 minutes ago.
  739. let isLoopStale = state.lastLoopDate == nil ||
  740. Date().timeIntervalSince(state.lastLoopDate!) > 15 * 60
  741. /// Computed property to determine if pump-compatible rounding was applied.
  742. /// Only relevant for positive insulin amounts.
  743. var isRoundedForPump: Bool {
  744. // Only check for rounding when we have a positive recommendation amount.
  745. if state.factoredInsulin > 0 {
  746. if state.factoredInsulin > iobAvailable {
  747. // Check if calculated insulin appears different from available IOB (limited by Max IOB)
  748. return insulinFormatter(state.insulinCalculated) != insulinFormatter(iobAvailable)
  749. } else {
  750. // Check if calculated insulin appears different from factored insulin (normal case)
  751. return insulinFormatter(state.insulinCalculated) != insulinFormatter(state.factoredInsulin)
  752. }
  753. }
  754. return false
  755. }
  756. return VStack(alignment: .center, spacing: 4) {
  757. let warningColor: Color = colorScheme == .dark ? .orange : .accentColor
  758. // Display appropriate warnings based on current conditions as a header on this card.
  759. // Each warning indicates a specific safety concern.
  760. if isLoopStale {
  761. Text("Last loop was > 15 m ago.")
  762. .warningStyle(warningColor)
  763. } else if state.currentBG < 54 {
  764. Text("Glucose is very low.")
  765. .warningStyle(.red)
  766. } else if state.minPredBG < 54 {
  767. Text("Glucose forecast is very low.")
  768. .warningStyle(warningColor)
  769. } else if state.factoredInsulin > state.maxBolus, state.maxBolus <= iobAvailable {
  770. Text("Max Bolus = \(insulinFormatter(state.maxBolus)) U")
  771. .warningStyle(warningColor)
  772. } else if state.factoredInsulin > 0, state.factoredInsulin > iobAvailable {
  773. // Available IOB warning with detailed breakdown.
  774. // Shows calculation: Max IOB - IOB = Available IOB
  775. if state.iob > state.maxIOB {
  776. Text("Current IOB (\(insulinFormatter(state.iob)) U) > Max IOB (\(insulinFormatter(state.maxIOB)) U)")
  777. .warningStyle(warningColor)
  778. } else {
  779. Text("Limited by Max IOB.")
  780. .warningStyle(warningColor)
  781. ViewThatFits(in: .horizontal) {
  782. // Option 1: Everything on one line (preferred if it fits)
  783. HStack(alignment: .firstTextBaseline, spacing: 0) {
  784. Text("Max IOB (")
  785. Text(insulinFormatter(state.maxIOB))
  786. .foregroundStyle(.primary)
  787. Text(" U) - Current IOB (")
  788. Text(insulinFormatter(state.iob))
  789. .foregroundStyle(.primary)
  790. Text(" U) = ")
  791. Text(insulinFormatter(iobAvailable))
  792. .foregroundStyle(.orange)
  793. Text(" U")
  794. }
  795. // Option 2: Two lines
  796. Grid {
  797. GridRow {
  798. Text("Max IOB")
  799. Text("")
  800. Text("IOB")
  801. Text("")
  802. Text("Limit")
  803. }
  804. GridRow {
  805. HStack(alignment: .firstTextBaseline, spacing: 0) {
  806. Text(insulinFormatter(state.maxIOB))
  807. .foregroundStyle(.primary)
  808. Text(" U")
  809. }
  810. Text("-")
  811. HStack(alignment: .firstTextBaseline, spacing: 0) {
  812. Text(wrapNegative(state.iob))
  813. .foregroundStyle(.primary)
  814. Text(" U")
  815. }
  816. Text("=")
  817. HStack(alignment: .firstTextBaseline, spacing: 0) {
  818. Text(insulinFormatter(iobAvailable))
  819. .foregroundStyle(.orange)
  820. Text(" U")
  821. }
  822. }
  823. }
  824. }
  825. .secondaryStyle()
  826. }
  827. }
  828. // Recommended Bolus card with accent-colored background
  829. ZStack {
  830. RoundedRectangle(cornerRadius: 12)
  831. .fill(Color.accentColor.opacity(0.1))
  832. HStack {
  833. VStack(alignment: .leading, spacing: 4) {
  834. Text("Recommended Bolus").font(.headline)
  835. // Only show "Rounded for pump" text when rounding was applied.
  836. if isRoundedForPump {
  837. Text("Rounded for pump")
  838. .secondaryStyle()
  839. }
  840. }
  841. .fixedSize(horizontal: true, vertical: true)
  842. Spacer()
  843. // Final insulin recommendation
  844. HStack(alignment: .firstTextBaseline, spacing: 4) {
  845. Text(insulinFormatter(state.insulinCalculated))
  846. .largeSolutionStyle()
  847. .foregroundStyle(state.insulinCalculated > 0 ? Color.accentColor : .primary)
  848. Text("U")
  849. .font(.subheadline)
  850. .foregroundStyle(.secondary)
  851. }
  852. }
  853. .padding(.horizontal, 16)
  854. .padding(.vertical, 12)
  855. }
  856. .fixedSize(horizontal: false, vertical: true)
  857. }
  858. }
  859. // MARK: - Helper Formatters
  860. // Functions for consistent number formatting throughout the view
  861. /// Formats insulin values with consistent decimal places
  862. /// - Parameters:
  863. /// - value: The insulin value to format
  864. /// - roundingMode: The rounding mode to apply (default: .down for conservative dosing)
  865. /// - Returns: A formatted string with 2 decimal places
  866. private func insulinFormatter(_ value: Decimal, _ roundingMode: NSDecimalNumber.RoundingMode = .down) -> String {
  867. let formatter = NumberFormatter()
  868. formatter.numberStyle = .decimal
  869. formatter.minimumFractionDigits = 2
  870. formatter.maximumFractionDigits = 2
  871. formatter.locale = Locale.current
  872. // Create a decimal handler with the specified rounding behavior.
  873. // Always rounds to 2 decimal places (0.01 U precision).
  874. let handler = NSDecimalNumberHandler(
  875. roundingMode: roundingMode,
  876. scale: 2,
  877. raiseOnExactness: false,
  878. raiseOnOverflow: false,
  879. raiseOnUnderflow: false,
  880. raiseOnDivideByZero: false
  881. )
  882. let roundedValue = NSDecimalNumber(decimal: value).rounding(accordingToBehavior: handler)
  883. return formatter.string(from: roundedValue) ?? "\(value)"
  884. }
  885. /// Wraps negative values in parentheses for clearer display in full bolus card.
  886. /// - Parameters:
  887. /// - value: The decimal value to format
  888. /// - roundingMode: The rounding mode to apply (default: .down)
  889. /// - Returns: A formatted string with parentheses for negative values
  890. private func wrapNegative(_ value: Decimal, _ roundingMode: NSDecimalNumber.RoundingMode = .down) -> String {
  891. value < 0 ? "(" + insulinFormatter(value, roundingMode) + ")" : insulinFormatter(value, roundingMode)
  892. }
  893. }