MainChartView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. OverrideView(
  121. state: state,
  122. overrides: state.overrides,
  123. overrideRunStored: state.overrideRunStored,
  124. units: state.units,
  125. viewContext: context
  126. )
  127. TempTargetView(
  128. tempTargetStored: state.tempTargetStored,
  129. tempTargetRunStored: state.tempTargetRunStored,
  130. units: state.units,
  131. viewContext: context
  132. )
  133. GlucoseChartView(
  134. glucoseData: state.glucoseFromPersistence,
  135. units: state.units,
  136. highGlucose: state.highGlucose,
  137. lowGlucose: state.lowGlucose,
  138. currentGlucoseTarget: state.currentGlucoseTarget,
  139. isSmoothingEnabled: state.isSmoothingEnabled,
  140. glucoseColorScheme: state.glucoseColorScheme
  141. )
  142. InsulinView(
  143. glucoseData: state.glucoseFromPersistence,
  144. insulinData: state.insulinFromPersistence,
  145. units: state.units
  146. )
  147. CarbView(
  148. glucoseData: state.glucoseFromPersistence,
  149. units: state.units,
  150. carbData: state.carbsFromPersistence,
  151. fpuData: state.fpusFromPersistence,
  152. minValue: state.minYAxisValue
  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. 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. }