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. 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. if let selection = selection {
  36. let lowerBound = selection.addingTimeInterval(-150)
  37. let upperBound = selection.addingTimeInterval(150)
  38. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  39. } else {
  40. return nil
  41. }
  42. }
  43. var selectedCOBValue: OrefDetermination? {
  44. if let selection = selection {
  45. let lowerBound = selection.addingTimeInterval(-120)
  46. let upperBound = selection.addingTimeInterval(120)
  47. return state.enactedAndNonEnactedDeterminations.first {
  48. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  49. }
  50. } else {
  51. return nil
  52. }
  53. }
  54. var selectedIOBValue: OrefDetermination? {
  55. if let selection = selection {
  56. let lowerBound = selection.addingTimeInterval(-120)
  57. let upperBound = selection.addingTimeInterval(120)
  58. return state.enactedAndNonEnactedDeterminations.first {
  59. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  60. }
  61. } else {
  62. return nil
  63. }
  64. }
  65. var body: some View {
  66. VStack {
  67. ZStack {
  68. VStack(spacing: 5) {
  69. dummyBasalChart
  70. staticYAxisChart
  71. Spacer()
  72. dummyCobChart
  73. }
  74. ScrollViewReader { scroller in
  75. ScrollView(.horizontal, showsIndicators: false) {
  76. VStack(spacing: 5) {
  77. basalChart
  78. mainChart
  79. Spacer()
  80. ZStack {
  81. cobChart
  82. iobChart
  83. }
  84. }.onChange(of: screenHours) {
  85. scroller.scrollTo("MainChart", anchor: .trailing)
  86. }
  87. .onChange(of: state.glucoseFromPersistence.last?.glucose) {
  88. scroller.scrollTo("MainChart", anchor: .trailing)
  89. updateStartEndMarkers()
  90. }
  91. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) {
  92. scroller.scrollTo("MainChart", anchor: .trailing)
  93. }
  94. .onChange(of: units) {
  95. // TODO: - Refactor this to only update the Y Axis Scale
  96. state.setupGlucoseArray()
  97. }
  98. .onAppear {
  99. if !mainChartHasInitialized {
  100. scroller.scrollTo("MainChart", anchor: .trailing)
  101. updateStartEndMarkers()
  102. calculateTempBasalsInBackground()
  103. mainChartHasInitialized = true
  104. }
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. }
  112. // MARK: - Main Chart with selection Popover
  113. extension MainChartView {
  114. private var mainChart: some View {
  115. VStack {
  116. Chart {
  117. drawStartRuleMark()
  118. drawEndRuleMark()
  119. drawCurrentTimeMarker()
  120. GlucoseChartView(
  121. glucoseData: state.glucoseFromPersistence,
  122. units: state.units,
  123. highGlucose: state.highGlucose,
  124. lowGlucose: state.lowGlucose,
  125. currentGlucoseTarget: state.currentGlucoseTarget,
  126. isSmoothingEnabled: state.isSmoothingEnabled,
  127. glucoseColorScheme: state.glucoseColorScheme
  128. )
  129. InsulinView(
  130. glucoseData: state.glucoseFromPersistence,
  131. insulinData: state.insulinFromPersistence,
  132. units: state.units
  133. )
  134. CarbView(
  135. glucoseData: state.glucoseFromPersistence,
  136. units: state.units,
  137. carbData: state.carbsFromPersistence,
  138. fpuData: state.fpusFromPersistence,
  139. minValue: state.minYAxisValue
  140. )
  141. OverrideView(
  142. state: state,
  143. overrides: state.overrides,
  144. overrideRunStored: state.overrideRunStored,
  145. units: state.units,
  146. viewContext: context
  147. )
  148. TempTargetView(
  149. tempTargetStored: state.tempTargetStored,
  150. tempTargetRunStored: state.tempTargetRunStored,
  151. units: state.units,
  152. viewContext: context
  153. )
  154. ForecastView(
  155. preprocessedData: state.preprocessedData,
  156. minForecast: state.minForecast,
  157. maxForecast: state.maxForecast,
  158. units: state.units,
  159. maxValue: state.maxYAxisValue,
  160. forecastDisplayType: state.forecastDisplayType
  161. )
  162. /// show glucose value when hovering over it
  163. if #available(iOS 17, *) {
  164. if let selectedGlucose {
  165. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  166. .foregroundStyle(Color.tabBar)
  167. .offset(yStart: 70)
  168. .lineStyle(.init(lineWidth: 2))
  169. .annotation(
  170. position: .top,
  171. alignment: .center,
  172. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  173. ) {
  174. selectionPopover
  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: 15, height: 15))
  182. .foregroundStyle(
  183. Decimal(selectedGlucose.glucose) > highGlucose ? Color.orange
  184. .opacity(0.8) :
  185. (
  186. Decimal(selectedGlucose.glucose) < lowGlucose ? Color.red.opacity(0.8) : Color.green
  187. .opacity(0.8)
  188. )
  189. )
  190. PointMark(
  191. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  192. y: .value("Value", selectedGlucose.glucose)
  193. )
  194. .zIndex(-1)
  195. .symbolSize(CGSize(width: 6, height: 6))
  196. .foregroundStyle(Color.primary)
  197. }
  198. }
  199. }
  200. .id("MainChart")
  201. .onChange(of: state.insulinFromPersistence) {
  202. state.roundedTotalBolus = state.calculateTINS()
  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. }