MainChartView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. 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) {
  86. scroller.scrollTo("MainChart", anchor: .trailing)
  87. }
  88. .onChange(of: state.glucoseFromPersistence.last?.glucose) {
  89. scroller.scrollTo("MainChart", anchor: .trailing)
  90. updateStartEndMarkers()
  91. }
  92. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) {
  93. scroller.scrollTo("MainChart", anchor: .trailing)
  94. }
  95. .onChange(of: units) {
  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. OverrideView(
  123. overrides: state.overrides,
  124. overrideRunStored: state.overrideRunStored,
  125. units: state.units,
  126. viewContext: context
  127. )
  128. GlucoseChartView(
  129. glucoseData: state.glucoseFromPersistence,
  130. units: state.units,
  131. highGlucose: state.highGlucose,
  132. lowGlucose: state.lowGlucose,
  133. currentGlucoseTarget: state.currentGlucoseTarget,
  134. isSmoothingEnabled: state.isSmoothingEnabled,
  135. glucoseColorScheme: state.glucoseColorScheme
  136. )
  137. InsulinView(
  138. glucoseData: state.glucoseFromPersistence,
  139. insulinData: state.insulinFromPersistence,
  140. units: state.units
  141. )
  142. CarbView(
  143. glucoseData: state.glucoseFromPersistence,
  144. units: state.units,
  145. carbData: state.carbsFromPersistence,
  146. fpuData: state.fpusFromPersistence,
  147. minValue: state.minYAxisValue
  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) {
  197. state.roundedTotalBolus = state.calculateTINS()
  198. }
  199. .onChange(of: tempTargets) {
  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. VStack(alignment: .leading) {
  221. HStack {
  222. Image(systemName: "clock")
  223. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  224. .font(.body).bold()
  225. }.font(.body).padding(.bottom, 5)
  226. // 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
  227. let hardCodedLow = Decimal(55)
  228. let hardCodedHigh = Decimal(220)
  229. let isDynamicColorScheme = glucoseColorScheme == .dynamicColor
  230. let glucoseColor = FreeAPS.getDynamicGlucoseColor(
  231. glucoseValue: Decimal(sgv),
  232. highGlucoseColorValue: isDynamicColorScheme ? hardCodedHigh : highGlucose,
  233. lowGlucoseColorValue: isDynamicColorScheme ? hardCodedLow : lowGlucose,
  234. targetGlucose: currentGlucoseTarget,
  235. glucoseColorScheme: glucoseColorScheme
  236. )
  237. HStack {
  238. Text(units == .mgdL ? Decimal(sgv).description : Decimal(sgv).formattedAsMmolL)
  239. .bold()
  240. + Text(" \(units.rawValue)")
  241. }.foregroundStyle(
  242. Color(glucoseColor)
  243. ).font(.body)
  244. if let selectedIOBValue, let iob = selectedIOBValue.iob {
  245. HStack {
  246. Image(systemName: "syringe.fill").frame(width: 15)
  247. Text(MainChartHelper.bolusFormatter.string(from: iob) ?? "")
  248. .bold()
  249. + Text(NSLocalizedString(" U", comment: "Insulin unit"))
  250. }.foregroundStyle(Color.insulin).font(.body)
  251. }
  252. if let selectedCOBValue {
  253. HStack {
  254. Image(systemName: "fork.knife").frame(width: 15)
  255. Text(MainChartHelper.carbsFormatter.string(from: selectedCOBValue.cob as NSNumber) ?? "")
  256. .bold()
  257. + Text(NSLocalizedString(" g", comment: "gram of carbs"))
  258. }.foregroundStyle(Color.orange).font(.body)
  259. }
  260. }
  261. .padding()
  262. .background {
  263. RoundedRectangle(cornerRadius: 4)
  264. .fill(Color.chart.opacity(0.85))
  265. .shadow(color: Color.secondary, radius: 2)
  266. .overlay(
  267. RoundedRectangle(cornerRadius: 4)
  268. .stroke(Color.secondary, lineWidth: 2)
  269. )
  270. }
  271. }
  272. }
  273. }
  274. // MARK: - Rule Marks and Charts configurations
  275. extension MainChartView {
  276. func drawCurrentTimeMarker() -> some ChartContent {
  277. RuleMark(
  278. x: .value(
  279. "",
  280. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  281. unit: .second
  282. )
  283. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  284. }
  285. func drawStartRuleMark() -> some ChartContent {
  286. RuleMark(
  287. x: .value(
  288. "",
  289. startMarker,
  290. unit: .second
  291. )
  292. ).foregroundStyle(Color.clear)
  293. }
  294. func drawEndRuleMark() -> some ChartContent {
  295. RuleMark(
  296. x: .value(
  297. "",
  298. endMarker,
  299. unit: .second
  300. )
  301. ).foregroundStyle(Color.clear)
  302. }
  303. func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  304. plotContent
  305. .rotationEffect(.degrees(180))
  306. .scaleEffect(x: -1, y: 1)
  307. }
  308. var mainChartXAxis: some AxisContent {
  309. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  310. if displayXgridLines {
  311. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  312. } else {
  313. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  314. }
  315. }
  316. }
  317. var basalChartXAxis: some AxisContent {
  318. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  319. if displayXgridLines {
  320. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  321. } else {
  322. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  323. }
  324. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  325. .font(.footnote).foregroundStyle(Color.primary)
  326. }
  327. }
  328. var mainChartYAxis: some AxisContent {
  329. AxisMarks(position: .trailing) { value in
  330. if displayYgridLines {
  331. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  332. } else {
  333. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  334. }
  335. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  336. /// fix offset between the two charts...
  337. if units == .mmolL {
  338. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  339. }
  340. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  341. }
  342. }
  343. }
  344. var cobChartYAxis: some AxisContent {
  345. AxisMarks(position: .trailing) { _ in
  346. if displayYgridLines {
  347. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  348. } else {
  349. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  350. }
  351. }
  352. }
  353. }
  354. // MARK: - Calculations and formatting
  355. extension MainChartView {
  356. func fullWidth(viewWidth: CGFloat) -> CGFloat {
  357. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  358. }
  359. // Update start and end marker to fix scroll update problem with x axis
  360. func updateStartEndMarkers() {
  361. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  362. let threeHourSinceNow = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  363. // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  364. let dynamicFutureDateForCone = Date(timeIntervalSinceNow: TimeInterval(
  365. Int(1.5) * 5 * state
  366. .minCount * 60
  367. ))
  368. endMarker = state
  369. .forecastDisplayType == .lines ? threeHourSinceNow : dynamicFutureDateForCone <= threeHourSinceNow ?
  370. dynamicFutureDateForCone.addingTimeInterval(TimeInterval(minutes: 30)) : threeHourSinceNow
  371. }
  372. }
  373. extension Int16 {
  374. var minutes: TimeInterval {
  375. TimeInterval(self) * 60
  376. }
  377. }