MainChartView.swift 19 KB

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