MainChartView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. let screenSize: CGRect = UIScreen.main.bounds
  5. let calendar = Calendar.current
  6. struct MainChartView: View {
  7. var geo: GeometryProxy
  8. @Binding var units: GlucoseUnits
  9. @Binding var hours: Int
  10. @Binding var tempTargets: [TempTarget]
  11. @Binding var highGlucose: Decimal
  12. @Binding var lowGlucose: Decimal
  13. @Binding var screenHours: Int16
  14. @Binding var displayXgridLines: Bool
  15. @Binding var displayYgridLines: Bool
  16. @Binding var thresholdLines: Bool
  17. @StateObject var state: Home.StateModel
  18. @State var basalProfiles: [BasalProfile] = []
  19. @State var chartTempTargets: [ChartTempTarget] = []
  20. @State var startMarker =
  21. Date(timeIntervalSinceNow: TimeInterval(hours: -24))
  22. @State var endMarker = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  23. @State var minValue: Decimal = 45
  24. @State var maxValue: Decimal = 270
  25. @State var selection: Date? = nil
  26. @State var minValueCobChart: Decimal = 0
  27. @State var maxValueCobChart: Decimal = 20
  28. @State var minValueIobChart: Decimal = 0
  29. @State var maxValueIobChart: Decimal = 5
  30. @State var mainChartHasInitialized = false
  31. let now = Date.now
  32. private let context = CoreDataStack.shared.persistentContainer.viewContext
  33. @Environment(\.colorScheme) var colorScheme
  34. @Environment(\.calendar) var calendar
  35. var upperLimit: Decimal {
  36. units == .mgdL ? 400 : 22.2
  37. }
  38. private var selectedGlucose: GlucoseStored? {
  39. if let selection = selection {
  40. let lowerBound = selection.addingTimeInterval(-150)
  41. let upperBound = selection.addingTimeInterval(150)
  42. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  43. } else {
  44. return nil
  45. }
  46. }
  47. var selectedCOBValue: OrefDetermination? {
  48. if let selection = selection {
  49. let lowerBound = selection.addingTimeInterval(-120)
  50. let upperBound = selection.addingTimeInterval(120)
  51. return state.enactedAndNonEnactedDeterminations.first {
  52. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  53. }
  54. } else {
  55. return nil
  56. }
  57. }
  58. var selectedIOBValue: OrefDetermination? {
  59. if let selection = selection {
  60. let lowerBound = selection.addingTimeInterval(-120)
  61. let upperBound = selection.addingTimeInterval(120)
  62. return state.enactedAndNonEnactedDeterminations.first {
  63. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  64. }
  65. } else {
  66. return nil
  67. }
  68. }
  69. var body: some View {
  70. VStack {
  71. ZStack {
  72. VStack(spacing: 5) {
  73. dummyBasalChart
  74. staticYAxisChart
  75. Spacer()
  76. dummyCobChart
  77. }
  78. ScrollViewReader { scroller in
  79. ScrollView(.horizontal, showsIndicators: false) {
  80. VStack(spacing: 5) {
  81. basalChart
  82. mainChart
  83. Spacer()
  84. ZStack {
  85. cobChart
  86. iobChart
  87. }
  88. }.onChange(of: screenHours) { _ in
  89. scroller.scrollTo("MainChart", anchor: .trailing)
  90. }
  91. .onChange(of: state.glucoseFromPersistence.last?.glucose) { _ in
  92. updateStartEndMarkers()
  93. yAxisChartData()
  94. scroller.scrollTo("MainChart", anchor: .trailing)
  95. }
  96. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) { _ in
  97. yAxisChartDataCobChart()
  98. yAxisChartDataIobChart()
  99. scroller.scrollTo("MainChart", anchor: .trailing)
  100. }
  101. .onChange(of: units) { _ in
  102. yAxisChartData()
  103. yAxisChartDataCobChart()
  104. yAxisChartDataIobChart()
  105. }
  106. .onAppear {
  107. if !mainChartHasInitialized {
  108. updateStartEndMarkers()
  109. yAxisChartData()
  110. yAxisChartDataCobChart()
  111. yAxisChartDataIobChart()
  112. mainChartHasInitialized = true
  113. scroller.scrollTo("MainChart", anchor: .trailing)
  114. }
  115. }
  116. }
  117. }
  118. }
  119. }
  120. }
  121. }
  122. // MARK: - Main Chart with selection Popover
  123. extension MainChartView {
  124. private var mainChart: some View {
  125. VStack {
  126. Chart {
  127. drawStartRuleMark()
  128. drawEndRuleMark()
  129. drawCurrentTimeMarker()
  130. drawTempTargets()
  131. GlucoseChartView(
  132. glucoseData: state.glucoseFromPersistence,
  133. manualGlucoseData: state.manualGlucoseFromPersistence,
  134. units: state.units,
  135. highGlucose: state.highGlucose,
  136. lowGlucose: state.lowGlucose,
  137. isSmoothingEnabled: state.isSmoothingEnabled
  138. )
  139. InsulinView(
  140. glucoseData: state.glucoseFromPersistence,
  141. insulinData: state.insulinFromPersistence,
  142. units: state.units
  143. )
  144. CarbView(
  145. glucoseData: state.glucoseFromPersistence,
  146. units: state.units,
  147. carbData: state.carbsFromPersistence,
  148. fpuData: state.fpusFromPersistence,
  149. minValue: minValue
  150. )
  151. OverrideView(
  152. overrides: state.overrides,
  153. overrideRunStored: state.overrideRunStored,
  154. units: state.units,
  155. viewContext: context
  156. )
  157. ForecastView(
  158. preprocessedData: state.preprocessedData,
  159. minForecast: state.minForecast,
  160. maxForecast: state.maxForecast,
  161. units: state.units,
  162. maxValue: maxValue,
  163. forecastDisplayType: state.forecastDisplayType
  164. )
  165. /// show glucose value when hovering over it
  166. if #available(iOS 17, *) {
  167. if let selectedGlucose {
  168. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  169. .foregroundStyle(Color.tabBar)
  170. .offset(yStart: 70)
  171. .lineStyle(.init(lineWidth: 2))
  172. .annotation(
  173. position: .top,
  174. alignment: .center,
  175. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  176. ) {
  177. selectionPopover
  178. }
  179. PointMark(
  180. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  181. y: .value("Value", selectedGlucose.glucose)
  182. )
  183. .zIndex(-1)
  184. .symbolSize(CGSize(width: 15, height: 15))
  185. .foregroundStyle(
  186. Decimal(selectedGlucose.glucose) > highGlucose ? Color.orange
  187. .opacity(0.8) :
  188. (
  189. Decimal(selectedGlucose.glucose) < lowGlucose ? Color.red.opacity(0.8) : Color.green
  190. .opacity(0.8)
  191. )
  192. )
  193. PointMark(
  194. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  195. y: .value("Value", selectedGlucose.glucose)
  196. )
  197. .zIndex(-1)
  198. .symbolSize(CGSize(width: 6, height: 6))
  199. .foregroundStyle(Color.primary)
  200. }
  201. }
  202. }
  203. .id("MainChart")
  204. .onChange(of: state.insulinFromPersistence) { _ in
  205. state.roundedTotalBolus = state.calculateTINS()
  206. }
  207. .onChange(of: tempTargets) { _ in
  208. Task {
  209. await calculateTTs()
  210. }
  211. }
  212. .frame(minHeight: geo.size.height * 0.28)
  213. .frame(width: fullWidth(viewWidth: screenSize.width))
  214. .chartXScale(domain: startMarker ... endMarker)
  215. .chartXAxis { mainChartXAxis }
  216. .chartYAxis { mainChartYAxis }
  217. .chartYAxis(.hidden)
  218. .backport.chartXSelection(value: $selection)
  219. .chartYScale(domain: units == .mgdL ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  220. .backport.chartForegroundStyleScale(state: state)
  221. }
  222. }
  223. @ViewBuilder var selectionPopover: some View {
  224. if let sgv = selectedGlucose?.glucose {
  225. let glucoseToShow = units == .mgdL ? Decimal(sgv) : Decimal(sgv).asMmolL
  226. VStack(alignment: .leading) {
  227. HStack {
  228. Image(systemName: "clock")
  229. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  230. .font(.body).bold()
  231. }.font(.body).padding(.bottom, 5)
  232. HStack {
  233. Text(units == .mgdL ? glucoseToShow.description : Decimal(sgv).formattedAsMmolL)
  234. .bold()
  235. + Text(" \(units.rawValue)")
  236. }.foregroundStyle(
  237. glucoseToShow < lowGlucose ? Color
  238. .red : (glucoseToShow > highGlucose ? Color.orange : Color.primary)
  239. ).font(.body)
  240. if let selectedIOBValue, let iob = selectedIOBValue.iob {
  241. HStack {
  242. Image(systemName: "syringe.fill").frame(width: 15)
  243. Text(MainChartHelper.bolusFormatter.string(from: iob) ?? "")
  244. .bold()
  245. + Text(NSLocalizedString(" U", comment: "Insulin unit"))
  246. }.foregroundStyle(Color.insulin).font(.body)
  247. }
  248. if let selectedCOBValue {
  249. HStack {
  250. Image(systemName: "fork.knife").frame(width: 15)
  251. Text(MainChartHelper.carbsFormatter.string(from: selectedCOBValue.cob as NSNumber) ?? "")
  252. .bold()
  253. + Text(NSLocalizedString(" g", comment: "gram of carbs"))
  254. }.foregroundStyle(Color.orange).font(.body)
  255. }
  256. }
  257. .padding()
  258. .background {
  259. RoundedRectangle(cornerRadius: 4)
  260. .fill(Color.chart.opacity(0.85))
  261. .shadow(color: Color.secondary, radius: 2)
  262. .overlay(
  263. RoundedRectangle(cornerRadius: 4)
  264. .stroke(Color.secondary, lineWidth: 2)
  265. )
  266. }
  267. }
  268. }
  269. }
  270. // MARK: - Rule Marks and Charts configurations
  271. extension MainChartView {
  272. func drawCurrentTimeMarker() -> some ChartContent {
  273. RuleMark(
  274. x: .value(
  275. "",
  276. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  277. unit: .second
  278. )
  279. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  280. }
  281. func drawStartRuleMark() -> some ChartContent {
  282. RuleMark(
  283. x: .value(
  284. "",
  285. startMarker,
  286. unit: .second
  287. )
  288. ).foregroundStyle(Color.clear)
  289. }
  290. func drawEndRuleMark() -> some ChartContent {
  291. RuleMark(
  292. x: .value(
  293. "",
  294. endMarker,
  295. unit: .second
  296. )
  297. ).foregroundStyle(Color.clear)
  298. }
  299. func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  300. plotContent
  301. .rotationEffect(.degrees(180))
  302. .scaleEffect(x: -1, y: 1)
  303. }
  304. var mainChartXAxis: some AxisContent {
  305. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  306. if displayXgridLines {
  307. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  308. } else {
  309. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  310. }
  311. }
  312. }
  313. var basalChartXAxis: some AxisContent {
  314. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  315. if displayXgridLines {
  316. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  317. } else {
  318. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  319. }
  320. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  321. .font(.footnote).foregroundStyle(Color.primary)
  322. }
  323. }
  324. var mainChartYAxis: some AxisContent {
  325. AxisMarks(position: .trailing) { value in
  326. if displayYgridLines {
  327. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  328. } else {
  329. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  330. }
  331. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  332. /// fix offset between the two charts...
  333. if units == .mmolL {
  334. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  335. }
  336. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  337. }
  338. }
  339. }
  340. var cobChartYAxis: some AxisContent {
  341. AxisMarks(position: .trailing) { _ in
  342. if displayYgridLines {
  343. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  344. } else {
  345. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  346. }
  347. }
  348. }
  349. }
  350. // MARK: - Calculations and formatting
  351. extension MainChartView {
  352. func fullWidth(viewWidth: CGFloat) -> CGFloat {
  353. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  354. }
  355. // Update start and end marker to fix scroll update problem with x axis
  356. func updateStartEndMarkers() {
  357. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  358. let threeHourSinceNow = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  359. // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  360. let dynamicFutureDateForCone = Date(timeIntervalSinceNow: TimeInterval(
  361. Int(1.5) * 5 * state
  362. .minCount * 60
  363. ))
  364. endMarker = state
  365. .forecastDisplayType == .lines ? threeHourSinceNow : dynamicFutureDateForCone <= threeHourSinceNow ?
  366. dynamicFutureDateForCone.addingTimeInterval(TimeInterval(minutes: 30)) : threeHourSinceNow
  367. }
  368. private func yAxisChartData() {
  369. Task {
  370. let (minGlucose, maxGlucose, minForecast, maxForecast) = await Task
  371. .detached { () -> (Decimal?, Decimal?, Decimal?, Decimal?) in
  372. let glucoseMapped = await state.glucoseFromPersistence.map { Decimal($0.glucose) }
  373. let forecastValues = await state.preprocessedData.map { Decimal($0.forecastValue.value) }
  374. // Calculate min and max values for glucose and forecast
  375. return (glucoseMapped.min(), glucoseMapped.max(), forecastValues.min(), forecastValues.max())
  376. }.value
  377. // Ensure all values exist, otherwise set default values
  378. guard let minGlucose = minGlucose, let maxGlucose = maxGlucose,
  379. let minForecast = minForecast, let maxForecast = maxForecast
  380. else {
  381. await updateChartBounds(minValue: 45 - 20, maxValue: 270 + 50)
  382. return
  383. }
  384. // Adjust max forecast to be no more than 100 over max glucose
  385. let adjustedMaxForecast = min(maxForecast, maxGlucose + 100)
  386. let minOverall = min(minGlucose, minForecast)
  387. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  388. // Update the chart bounds on the main thread
  389. await updateChartBounds(minValue: minOverall - 50, maxValue: maxOverall + 80)
  390. }
  391. }
  392. @MainActor private func updateChartBounds(minValue: Decimal, maxValue: Decimal) async {
  393. self.minValue = minValue
  394. self.maxValue = maxValue
  395. }
  396. private func yAxisChartDataCobChart() {
  397. Task {
  398. let maxCob = await Task.detached { () -> Decimal? in
  399. let cobMapped = await state.enactedAndNonEnactedDeterminations.map { Decimal($0.cob) }
  400. return cobMapped.max()
  401. }.value
  402. // Ensure the result exists or set default values
  403. if let maxCob = maxCob {
  404. let calculatedMax = maxCob == 0 ? 20 : maxCob + 20
  405. await updateCobChartBounds(minValue: 0, maxValue: calculatedMax)
  406. } else {
  407. await updateCobChartBounds(minValue: 0, maxValue: 20)
  408. }
  409. }
  410. }
  411. @MainActor private func updateCobChartBounds(minValue: Decimal, maxValue: Decimal) async {
  412. minValueCobChart = minValue
  413. maxValueCobChart = maxValue
  414. }
  415. private func yAxisChartDataIobChart() {
  416. Task {
  417. let (minIob, maxIob) = await Task.detached { () -> (Decimal?, Decimal?) in
  418. let iobMapped = await state.enactedAndNonEnactedDeterminations.compactMap { $0.iob?.decimalValue }
  419. return (iobMapped.min(), iobMapped.max())
  420. }.value
  421. // Ensure min and max IOB values exist, or set defaults
  422. if let minIob = minIob, let maxIob = maxIob {
  423. let adjustedMin = minIob < 0 ? minIob - 2 : 0
  424. await updateIobChartBounds(minValue: adjustedMin, maxValue: maxIob + 2)
  425. } else {
  426. await updateIobChartBounds(minValue: 0, maxValue: 5)
  427. }
  428. }
  429. }
  430. @MainActor private func updateIobChartBounds(minValue: Decimal, maxValue: Decimal) async {
  431. minValueIobChart = minValue
  432. maxValueIobChart = maxValue
  433. }
  434. }
  435. extension Int16 {
  436. var minutes: TimeInterval {
  437. TimeInterval(self) * 60
  438. }
  439. }