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