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