MainChartView.swift 15 KB

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