MainChartView.swift 16 KB

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