MainChartView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. ZStack {
  70. cobChart
  71. iobChart
  72. }
  73. }.onChange(of: screenHours) {
  74. scroller.scrollTo("MainChart", anchor: .trailing)
  75. }
  76. .onChange(of: state.glucoseFromPersistence.last?.glucose) {
  77. scroller.scrollTo("MainChart", anchor: .trailing)
  78. updateStartEndMarkers()
  79. }
  80. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) {
  81. scroller.scrollTo("MainChart", anchor: .trailing)
  82. }
  83. .onChange(of: units) {
  84. // TODO: - Refactor this to only update the Y Axis Scale
  85. state.setupGlucoseArray()
  86. }
  87. .onAppear {
  88. if !mainChartHasInitialized {
  89. scroller.scrollTo("MainChart", anchor: .trailing)
  90. updateStartEndMarkers()
  91. calculateTempBasalsInBackground()
  92. mainChartHasInitialized = true
  93. }
  94. }
  95. }
  96. }
  97. }
  98. }
  99. }
  100. }
  101. // MARK: - Main Chart with selection Popover
  102. extension MainChartView {
  103. private var mainChart: some View {
  104. VStack {
  105. Chart {
  106. drawStartRuleMark()
  107. drawEndRuleMark()
  108. drawCurrentTimeMarker()
  109. OverrideView(
  110. state: state,
  111. overrides: state.overrides,
  112. overrideRunStored: state.overrideRunStored,
  113. units: state.units,
  114. viewContext: context
  115. )
  116. TempTargetView(
  117. tempTargetStored: state.tempTargetStored,
  118. tempTargetRunStored: state.tempTargetRunStored,
  119. units: state.units,
  120. viewContext: context
  121. )
  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. ForecastView(
  144. preprocessedData: state.preprocessedData,
  145. minForecast: state.minForecast,
  146. maxForecast: state.maxForecast,
  147. units: state.units,
  148. maxValue: state.maxYAxisValue,
  149. forecastDisplayType: state.forecastDisplayType
  150. )
  151. /// show glucose value when hovering over it
  152. if #available(iOS 17, *) {
  153. if let selectedGlucose {
  154. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  155. .foregroundStyle(Color.tabBar)
  156. .offset(yStart: 70)
  157. .lineStyle(.init(lineWidth: 2))
  158. .annotation(
  159. position: .top,
  160. alignment: .center,
  161. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  162. ) {
  163. selectionPopover
  164. }
  165. PointMark(
  166. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  167. y: .value("Value", selectedGlucose.glucose)
  168. )
  169. .zIndex(-1)
  170. .symbolSize(CGSize(width: 15, height: 15))
  171. .foregroundStyle(
  172. Decimal(selectedGlucose.glucose) > highGlucose ? Color.orange
  173. .opacity(0.8) :
  174. (
  175. Decimal(selectedGlucose.glucose) < lowGlucose ? Color.red.opacity(0.8) : Color.green
  176. .opacity(0.8)
  177. )
  178. )
  179. PointMark(
  180. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  181. y: .value("Value", selectedGlucose.glucose)
  182. )
  183. .zIndex(-1)
  184. .symbolSize(CGSize(width: 6, height: 6))
  185. .foregroundStyle(Color.primary)
  186. }
  187. }
  188. }
  189. .id("MainChart")
  190. .onChange(of: state.insulinFromPersistence) {
  191. state.roundedTotalBolus = state.calculateTINS()
  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. }