InsulinSensitivityStepView.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //
  2. // InsulinSensitivityStepView.swift
  3. // Trio
  4. //
  5. // Created by Marvin Polscheit on 19.03.25.
  6. //
  7. import Charts
  8. import SwiftUI
  9. import UIKit
  10. /// Insulin sensitivity step view for setting insulin sensitivity factor.
  11. struct InsulinSensitivityStepView: View {
  12. @Bindable var state: Onboarding.StateModel
  13. @State private var refreshUI = UUID() // to update chart when slider value changes
  14. @State private var therapyItems: [TherapySettingItem] = []
  15. // For chart scaling
  16. private let chartScale = Calendar.current
  17. .date(from: DateComponents(year: 2001, month: 01, day: 01, hour: 0, minute: 0, second: 0))
  18. private var numberFormatter: NumberFormatter {
  19. let formatter = NumberFormatter()
  20. formatter.numberStyle = .decimal
  21. formatter.maximumFractionDigits = state.units == .mmolL ? 1 : 0
  22. return formatter
  23. }
  24. private var dateFormatter: DateFormatter {
  25. let formatter = DateFormatter()
  26. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  27. formatter.timeStyle = .short
  28. return formatter
  29. }
  30. var body: some View {
  31. ScrollView {
  32. VStack(alignment: .leading, spacing: 0) {
  33. // Chart visualization
  34. if !state.isfItems.isEmpty {
  35. VStack(alignment: .leading) {
  36. isfChart
  37. .frame(height: 180)
  38. .padding(.horizontal)
  39. }
  40. .padding(.vertical, 5)
  41. .background(Color.chart.opacity(0.45))
  42. .cornerRadius(10)
  43. }
  44. TimeValueEditorView(
  45. items: $therapyItems,
  46. unit: String(localized: "\(state.units.rawValue)/U"),
  47. valueOptions: state.isfRateValues
  48. ).scaledToFit()
  49. // Example calculation based on first ISF
  50. if !state.isfItems.isEmpty {
  51. Divider()
  52. .padding(.horizontal)
  53. VStack(alignment: .leading, spacing: 8) {
  54. Text("Example Calculation")
  55. .font(.headline)
  56. .padding(.horizontal)
  57. VStack(alignment: .leading, spacing: 4) {
  58. // Current glucose is 40 mg/dL or 2.2 mmol/L above target
  59. let aboveTarget = state.units == .mgdL ? 40.0 : 2.2
  60. let isfValue = state.isfRateValues.isEmpty || state.isfItems.isEmpty ?
  61. Double(truncating: state.isf as NSNumber) :
  62. Double(
  63. truncating: state
  64. .isfRateValues[state.isfItems.first!.rateIndex] as NSNumber
  65. )
  66. let insulinNeeded = aboveTarget / isfValue
  67. Text(
  68. "If you are \(numberFormatter.string(from: NSNumber(value: aboveTarget)) ?? "--") \(state.units == .mgdL ? "mg/dL" : "mmol/L") above target:"
  69. )
  70. .font(.subheadline)
  71. .padding(.horizontal)
  72. Text(
  73. "\(numberFormatter.string(from: NSNumber(value: aboveTarget)) ?? "--") ÷ \(numberFormatter.string(from: isfValue as NSNumber) ?? "--") = \(String(format: "%.1f", insulinNeeded)) units of insulin"
  74. )
  75. .font(.system(.body, design: .monospaced))
  76. .foregroundColor(.red)
  77. .padding(.vertical, 8)
  78. .padding(.horizontal, 12)
  79. .frame(maxWidth: .infinity, alignment: .leading)
  80. .background(Color.red.opacity(0.1))
  81. .cornerRadius(8)
  82. .padding(.horizontal)
  83. }
  84. .padding(.vertical, 4)
  85. }
  86. // Information about ISF
  87. VStack(alignment: .leading, spacing: 8) {
  88. Text("What This Means")
  89. .font(.headline)
  90. .padding(.horizontal)
  91. VStack(alignment: .leading, spacing: 4) {
  92. if state.units == .mgdL {
  93. Text("• An ISF of 50 mg/dL means 1 unit of insulin lowers your BG by 50 mg/dL")
  94. Text("• A lower number means you're more sensitive to insulin")
  95. Text("• A higher number means you're less sensitive to insulin")
  96. Text("• ISF may vary throughout the day")
  97. } else {
  98. Text("• An ISF of 2.8 mmol/L means 1 unit of insulin lowers your BG by 2.8 mmol/L")
  99. Text("• A lower number means you're more sensitive to insulin")
  100. Text("• A higher number means you're less sensitive to insulin")
  101. Text("• ISF may vary throughout the day")
  102. }
  103. }
  104. .font(.caption)
  105. .foregroundColor(.secondary)
  106. .padding(.horizontal)
  107. }
  108. }
  109. }
  110. }
  111. .onAppear {
  112. if state.isfItems.isEmpty {
  113. state.addISFValue()
  114. }
  115. therapyItems = state.getSensitivityTherapyItems(from: state.isfItems)
  116. }.onChange(of: therapyItems) { _, newItems in
  117. state.updateSensitivies(from: newItems)
  118. refreshUI = UUID()
  119. }
  120. }
  121. // Add initial ISF value
  122. private func addInitialISF() {
  123. // Default to midnight (00:00) and 50 mg/dL (or 2.8 mmol/L)
  124. let timeIndex = state.isfTimeValues.firstIndex { abs($0 - 0) < 1 } ?? 0
  125. let defaultISF = state.units == .mgdL ? 50.0 : 2.8
  126. let rateIndex = state.isfRateValues.firstIndex { abs(Double($0) - defaultISF) < 0.5 } ?? 45
  127. let newItem = ISFEditor.Item(rateIndex: rateIndex, timeIndex: timeIndex)
  128. state.isfItems.append(newItem)
  129. }
  130. // Computed property to check if we can add more ISF values
  131. private var canAddISF: Bool {
  132. guard let lastItem = state.isfItems.last else { return true }
  133. return lastItem.timeIndex < state.isfTimeValues.count - 1
  134. }
  135. // Chart for visualizing ISF profile
  136. private var isfChart: some View {
  137. Chart {
  138. ForEach(Array(state.isfItems.enumerated()), id: \.element.id) { index, item in
  139. let displayValue = state.isfRateValues[item.rateIndex]
  140. let tzOffset = TimeZone.current.secondsFromGMT() * -1
  141. let startDate = Date(timeIntervalSinceReferenceDate: state.isfTimeValues[item.timeIndex])
  142. .addingTimeInterval(TimeInterval(tzOffset))
  143. let endDate = state.isfItems.count > index + 1 ?
  144. Date(
  145. timeIntervalSinceReferenceDate: state
  146. .isfTimeValues[state.isfItems[index + 1].timeIndex]
  147. )
  148. .addingTimeInterval(TimeInterval(tzOffset)) :
  149. Date(timeIntervalSinceReferenceDate: state.isfTimeValues.last!).addingTimeInterval(30 * 60)
  150. .addingTimeInterval(TimeInterval(tzOffset))
  151. RectangleMark(
  152. xStart: .value("start", startDate),
  153. xEnd: .value("end", endDate),
  154. yStart: .value("rate-start", displayValue),
  155. yEnd: .value("rate-end", 0)
  156. ).foregroundStyle(
  157. .linearGradient(
  158. colors: [
  159. Color.red.opacity(0.6),
  160. Color.red.opacity(0.1)
  161. ],
  162. startPoint: .bottom,
  163. endPoint: .top
  164. )
  165. ).alignsMarkStylesWithPlotArea()
  166. LineMark(x: .value("End Date", startDate), y: .value("ISF", displayValue))
  167. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.red)
  168. LineMark(x: .value("Start Date", endDate), y: .value("ISF", displayValue))
  169. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.red)
  170. }
  171. }
  172. .id(refreshUI) // Force chart update
  173. .chartXAxis {
  174. AxisMarks(values: .automatic(desiredCount: 6)) { _ in
  175. AxisValueLabel(format: .dateTime.hour())
  176. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  177. }
  178. }
  179. .chartXScale(
  180. domain: Calendar.current.startOfDay(for: chartScale!) ... Calendar.current.startOfDay(for: chartScale!)
  181. .addingTimeInterval(60 * 60 * 24)
  182. )
  183. .chartYAxis {
  184. AxisMarks(values: .automatic(desiredCount: 4)) { _ in
  185. AxisValueLabel()
  186. AxisGridLine(centered: true, stroke: StrokeStyle(lineWidth: 1, dash: [2, 4]))
  187. }
  188. }
  189. }
  190. }