MainChartView.swift 16 KB

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