MainChartView.swift 19 KB

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