MainChartView.swift 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. import Charts
  2. import CoreData
  3. import SwiftUI
  4. let screenSize: CGRect = UIScreen.main.bounds
  5. let calendar = Calendar.current
  6. private struct BasalProfile: Hashable {
  7. let amount: Double
  8. var isOverwritten: Bool
  9. let startDate: Date
  10. let endDate: Date?
  11. init(amount: Double, isOverwritten: Bool, startDate: Date, endDate: Date? = nil) {
  12. self.amount = amount
  13. self.isOverwritten = isOverwritten
  14. self.startDate = startDate
  15. self.endDate = endDate
  16. }
  17. }
  18. private struct ChartTempTarget: Hashable {
  19. let amount: Decimal
  20. let start: Date
  21. let end: Date
  22. }
  23. struct MainChartView: View {
  24. private enum Config {
  25. static let bolusSize: CGFloat = 5
  26. static let bolusScale: CGFloat = 1
  27. static let carbsSize: CGFloat = 5
  28. static let carbsScale: CGFloat = 0.3
  29. static let fpuSize: CGFloat = 10
  30. static let maxGlucose = 270
  31. static let minGlucose = 45
  32. }
  33. var geo: GeometryProxy
  34. @Binding var units: GlucoseUnits
  35. @Binding var announcement: [Announcement]
  36. @Binding var hours: Int
  37. @Binding var maxBasal: Decimal
  38. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  39. @Binding var basalProfile: [BasalProfileEntry]
  40. @Binding var tempTargets: [TempTarget]
  41. @Binding var smooth: Bool
  42. @Binding var highGlucose: Decimal
  43. @Binding var lowGlucose: Decimal
  44. @Binding var screenHours: Int16
  45. @Binding var displayXgridLines: Bool
  46. @Binding var displayYgridLines: Bool
  47. @Binding var thresholdLines: Bool
  48. @Binding var isTempTargetActive: Bool
  49. @StateObject var state: Home.StateModel
  50. @State var didAppearTrigger = false
  51. @State private var basalProfiles: [BasalProfile] = []
  52. @State private var chartTempTargets: [ChartTempTarget] = []
  53. @State private var count: Decimal = 1
  54. @State private var startMarker =
  55. Date(timeIntervalSinceNow: TimeInterval(hours: -24))
  56. @State private var minValue: Decimal = 45
  57. @State private var maxValue: Decimal = 270
  58. @State private var selection: Date? = nil
  59. @State private var minValueCobChart: Decimal = 0
  60. @State private var maxValueCobChart: Decimal = 20
  61. @State private var minValueIobChart: Decimal = 0
  62. @State private var maxValueIobChart: Decimal = 5
  63. private let now = Date.now
  64. private let context = CoreDataStack.shared.persistentContainer.viewContext
  65. @Environment(\.colorScheme) var colorScheme
  66. @Environment(\.calendar) var calendar
  67. private var endMarker: Date {
  68. let threeHourSinceNow = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  69. // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  70. let dynamicFutureDateForCone = Date(timeIntervalSinceNow: TimeInterval(
  71. Int(1.5) * 5 * state
  72. .minCount * 60
  73. ))
  74. return state
  75. .displayForecastsAsLines ? threeHourSinceNow : dynamicFutureDateForCone <= threeHourSinceNow ?
  76. dynamicFutureDateForCone.addingTimeInterval(TimeInterval(minutes: 30)) : threeHourSinceNow
  77. }
  78. private var bolusFormatter: NumberFormatter {
  79. let formatter = NumberFormatter()
  80. formatter.numberStyle = .decimal
  81. formatter.minimumIntegerDigits = 0
  82. formatter.maximumFractionDigits = 2
  83. formatter.decimalSeparator = "."
  84. return formatter
  85. }
  86. private var carbsFormatter: NumberFormatter {
  87. let formatter = NumberFormatter()
  88. formatter.numberStyle = .decimal
  89. formatter.maximumFractionDigits = 0
  90. return formatter
  91. }
  92. private var conversionFactor: Decimal {
  93. units == .mmolL ? 0.0555 : 1
  94. }
  95. private var upperLimit: Decimal {
  96. units == .mgdL ? 400 : 22.2
  97. }
  98. private var defaultBolusPosition: Int {
  99. units == .mgdL ? 120 : 7
  100. }
  101. private var bolusOffset: Decimal {
  102. units == .mgdL ? 30 : 1.66
  103. }
  104. private var selectedGlucose: GlucoseStored? {
  105. if let selection = selection {
  106. let lowerBound = selection.addingTimeInterval(-120)
  107. let upperBound = selection.addingTimeInterval(120)
  108. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  109. } else {
  110. return nil
  111. }
  112. }
  113. var body: some View {
  114. VStack {
  115. ZStack {
  116. VStack(spacing: 5) {
  117. dummyBasalChart
  118. staticYAxisChart
  119. Spacer()
  120. dummyCobChart
  121. }
  122. ScrollViewReader { scroller in
  123. ScrollView(.horizontal, showsIndicators: false) {
  124. VStack(spacing: 5) {
  125. basalChart
  126. mainChart
  127. Spacer()
  128. ZStack {
  129. cobChart
  130. iobChart
  131. }
  132. }.onChange(of: screenHours) { _ in
  133. updateStartEndMarkers()
  134. yAxisChartData()
  135. yAxisChartDataCobChart()
  136. yAxisChartDataIobChart()
  137. scroller.scrollTo("MainChart", anchor: .trailing)
  138. }
  139. .onChange(of: state.glucoseFromPersistence.last?.glucose) { _ in
  140. updateStartEndMarkers()
  141. yAxisChartData()
  142. scroller.scrollTo("MainChart", anchor: .trailing)
  143. }
  144. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) { _ in
  145. updateStartEndMarkers()
  146. yAxisChartDataCobChart()
  147. yAxisChartDataIobChart()
  148. scroller.scrollTo("MainChart", anchor: .trailing)
  149. }
  150. .onChange(of: state.tempBasals) { _ in
  151. updateStartEndMarkers()
  152. scroller.scrollTo("MainChart", anchor: .trailing)
  153. }
  154. .onChange(of: units) { _ in
  155. yAxisChartData()
  156. }
  157. .onAppear {
  158. updateStartEndMarkers()
  159. yAxisChartData()
  160. yAxisChartDataCobChart()
  161. yAxisChartDataIobChart()
  162. scroller.scrollTo("MainChart", anchor: .trailing)
  163. }
  164. }
  165. }
  166. }
  167. }
  168. }
  169. }
  170. // MARK: - Components
  171. struct Backport<Content: View> {
  172. let content: Content
  173. }
  174. extension View {
  175. var backport: Backport<Self> { Backport(content: self) }
  176. }
  177. extension Backport {
  178. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  179. if #available(iOS 17, *) {
  180. content.chartXSelection(value: value)
  181. } else {
  182. content
  183. }
  184. }
  185. @ViewBuilder func chartForegroundStyleScale(state: any StateModel) -> some View {
  186. if (state as? Bolus.StateModel)?.displayForecastsAsLines == true ||
  187. (state as? Home.StateModel)?.displayForecastsAsLines == true
  188. {
  189. let modifiedContent = content
  190. .chartForegroundStyleScale([
  191. "iob": .blue,
  192. "uam": Color.uam,
  193. "zt": Color.zt,
  194. "cob": .orange
  195. ])
  196. if state is Home.StateModel {
  197. modifiedContent
  198. .chartLegend(.hidden)
  199. } else {
  200. modifiedContent
  201. }
  202. } else {
  203. content
  204. }
  205. }
  206. }
  207. extension MainChartView {
  208. /// empty chart that just shows the Y axis and Y grid lines. Created separately from `mainChart` to allow main chart to scroll horizontally while having a fixed Y axis
  209. private var staticYAxisChart: some View {
  210. Chart {
  211. /// high and low threshold lines
  212. if thresholdLines {
  213. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  214. .lineStyle(.init(lineWidth: 1, dash: [5]))
  215. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  216. .lineStyle(.init(lineWidth: 1, dash: [5]))
  217. }
  218. }
  219. .id("DummyMainChart")
  220. .frame(minHeight: geo.size.height * 0.28)
  221. .frame(width: screenSize.width - 10)
  222. .chartXAxis { mainChartXAxis }
  223. .chartXScale(domain: startMarker ... endMarker)
  224. .chartXAxis(.hidden)
  225. .chartYAxis { mainChartYAxis }
  226. .chartYScale(domain: minValue ... maxValue)
  227. .chartLegend(.hidden)
  228. }
  229. private var dummyBasalChart: some View {
  230. Chart {}
  231. .id("DummyBasalChart")
  232. .frame(minHeight: geo.size.height * 0.05)
  233. .frame(width: screenSize.width - 10)
  234. .chartXAxis { basalChartXAxis }
  235. .chartXAxis(.hidden)
  236. .chartYAxis(.hidden)
  237. .chartLegend(.hidden)
  238. }
  239. private var dummyCobChart: some View {
  240. Chart {
  241. drawCOB(dummy: true)
  242. }
  243. .id("DummyCobChart")
  244. .frame(minHeight: geo.size.height * 0.12)
  245. .frame(width: screenSize.width - 10)
  246. .chartXScale(domain: startMarker ... endMarker)
  247. .chartXAxis { basalChartXAxis }
  248. .chartXAxis(.hidden)
  249. .chartYAxis { cobChartYAxis }
  250. .chartYAxis(.hidden)
  251. .chartYScale(domain: minValueCobChart ... maxValueCobChart)
  252. .chartLegend(.hidden)
  253. }
  254. private var mainChart: some View {
  255. VStack {
  256. Chart {
  257. drawStartRuleMark()
  258. drawEndRuleMark()
  259. drawCurrentTimeMarker()
  260. drawFpus()
  261. drawBoluses()
  262. drawTempTargets()
  263. drawActiveOverrides()
  264. drawOverrideRunStored()
  265. drawGlucose(dummy: false)
  266. drawManualGlucose()
  267. drawCarbs()
  268. if state.displayForecastsAsLines {
  269. drawForecastsLines()
  270. } else {
  271. drawForecastsCone()
  272. }
  273. /// show glucose value when hovering over it
  274. if #available(iOS 17, *) {
  275. if let selectedGlucose {
  276. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  277. .foregroundStyle(Color.tabBar)
  278. .offset(yStart: 70)
  279. .lineStyle(.init(lineWidth: 2, dash: [5]))
  280. .annotation(
  281. position: .top,
  282. alignment: .center,
  283. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  284. ) {
  285. selectionPopover
  286. }
  287. PointMark(
  288. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  289. y: .value("Value", selectedGlucose.glucose)
  290. )
  291. .symbolSize(CGSize(width: 16, height: 16))
  292. .foregroundStyle(Color.secondary)
  293. PointMark(
  294. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  295. y: .value("Value", selectedGlucose.glucose)
  296. )
  297. .symbolSize(CGSize(width: 6, height: 6))
  298. .foregroundStyle(Color.primary)
  299. }
  300. }
  301. }
  302. .id("MainChart")
  303. .onChange(of: state.insulinFromPersistence) { _ in
  304. state.roundedTotalBolus = state.calculateTINS()
  305. }
  306. .onChange(of: tempTargets) { _ in
  307. calculateTTs()
  308. }
  309. .onChange(of: didAppearTrigger) { _ in
  310. calculateTTs()
  311. }
  312. .frame(minHeight: geo.size.height * 0.28)
  313. .frame(width: fullWidth(viewWidth: screenSize.width))
  314. .chartXScale(domain: startMarker ... endMarker)
  315. .chartXAxis { mainChartXAxis }
  316. .chartYAxis { mainChartYAxis }
  317. .chartYAxis(.hidden)
  318. .backport.chartXSelection(value: $selection)
  319. .chartYScale(domain: minValue ... maxValue)
  320. .backport.chartForegroundStyleScale(state: state)
  321. }
  322. }
  323. @ViewBuilder var selectionPopover: some View {
  324. if let sgv = selectedGlucose?.glucose {
  325. let glucoseToShow = Decimal(sgv) * conversionFactor
  326. VStack {
  327. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  328. HStack {
  329. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  330. .fontWeight(.bold)
  331. .foregroundStyle(
  332. Decimal(sgv) < lowGlucose ? Color
  333. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  334. )
  335. Text(units.rawValue).foregroundColor(.secondary)
  336. }
  337. }
  338. .padding(6)
  339. .background {
  340. RoundedRectangle(cornerRadius: 4)
  341. .fill(Color.gray.opacity(0.1))
  342. .shadow(color: .blue, radius: 2)
  343. .overlay(
  344. RoundedRectangle(cornerRadius: 4)
  345. .stroke(Color.blue, lineWidth: 2)
  346. )
  347. }
  348. }
  349. }
  350. private var basalChart: some View {
  351. VStack {
  352. Chart {
  353. drawStartRuleMark()
  354. drawEndRuleMark()
  355. drawCurrentTimeMarker()
  356. drawTempBasals(dummy: false)
  357. drawBasalProfile()
  358. drawSuspensions()
  359. }.onChange(of: state.tempBasals) { _ in
  360. calculateBasals()
  361. }
  362. .onChange(of: maxBasal) { _ in
  363. calculateBasals()
  364. }
  365. .onChange(of: autotunedBasalProfile) { _ in
  366. calculateBasals()
  367. }
  368. .onChange(of: didAppearTrigger) { _ in
  369. calculateBasals()
  370. }.onChange(of: basalProfile) { _ in
  371. calculateBasals()
  372. }
  373. .frame(minHeight: geo.size.height * 0.05)
  374. .frame(width: fullWidth(viewWidth: screenSize.width))
  375. .chartXScale(domain: startMarker ... endMarker)
  376. .chartXAxis { basalChartXAxis }
  377. .chartXAxis(.hidden)
  378. .chartYAxis(.hidden)
  379. .chartPlotStyle { basalChartPlotStyle($0) }
  380. }
  381. }
  382. private var iobChart: some View {
  383. VStack {
  384. Chart {
  385. drawIOB()
  386. }
  387. .frame(minHeight: geo.size.height * 0.12)
  388. .frame(width: fullWidth(viewWidth: screenSize.width))
  389. .chartXScale(domain: startMarker ... endMarker)
  390. .chartXAxis { basalChartXAxis }
  391. .chartYAxis { cobChartYAxis }
  392. .chartYScale(domain: minValueIobChart ... maxValueIobChart)
  393. .chartYAxis(.hidden)
  394. }
  395. }
  396. private var cobChart: some View {
  397. Chart {
  398. drawCurrentTimeMarker()
  399. drawCOB(dummy: false)
  400. }
  401. .frame(minHeight: geo.size.height * 0.12)
  402. .frame(width: fullWidth(viewWidth: screenSize.width))
  403. .chartXScale(domain: startMarker ... endMarker)
  404. .chartXAxis { basalChartXAxis }
  405. .chartYAxis { cobChartYAxis }
  406. .chartYScale(domain: minValueCobChart ... maxValueCobChart)
  407. }
  408. }
  409. // MARK: - Calculations
  410. extension MainChartView {
  411. private func drawBoluses() -> some ChartContent {
  412. ForEach(state.insulinFromPersistence) { insulin in
  413. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  414. let bolusDate = insulin.timestamp ?? Date()
  415. if amount != 0, let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)?.glucose {
  416. let yPosition = (Decimal(glucose) * conversionFactor) + bolusOffset
  417. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  418. PointMark(
  419. x: .value("Time", bolusDate, unit: .second),
  420. y: .value("Value", yPosition)
  421. )
  422. .symbol {
  423. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  424. }
  425. .annotation(position: .top) {
  426. Text(bolusFormatter.string(from: amount) ?? "")
  427. .font(.caption2)
  428. .foregroundStyle(Color.insulin)
  429. }
  430. }
  431. }
  432. }
  433. private func drawCarbs() -> some ChartContent {
  434. /// carbs
  435. ForEach(state.carbsFromPersistence) { carb in
  436. let carbAmount = carb.carbs
  437. let carbDate = carb.date ?? Date()
  438. if let glucose = timeToNearestGlucose(time: carbDate.timeIntervalSince1970)?.glucose {
  439. let yPosition = (Decimal(glucose) * conversionFactor) - bolusOffset
  440. let size = (Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale)
  441. let limitedSize = size > 30 ? 30 : size
  442. PointMark(
  443. x: .value("Time", carbDate, unit: .second),
  444. y: .value("Value", yPosition)
  445. )
  446. .symbol {
  447. Image(systemName: "arrowtriangle.down.fill").font(.system(size: limitedSize)).foregroundStyle(Color.orange)
  448. .rotationEffect(.degrees(180))
  449. }
  450. .annotation(position: .bottom) {
  451. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  452. .foregroundStyle(Color.orange)
  453. }
  454. }
  455. }
  456. }
  457. private func drawFpus() -> some ChartContent {
  458. /// fpus
  459. ForEach(state.fpusFromPersistence, id: \.id) { fpu in
  460. let fpuAmount = fpu.carbs
  461. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  462. let yPosition = minValue
  463. PointMark(
  464. x: .value("Time", fpu.date ?? Date(), unit: .second),
  465. y: .value("Value", yPosition)
  466. )
  467. .symbolSize(size)
  468. .foregroundStyle(Color.brown)
  469. }
  470. }
  471. private func drawGlucose(dummy _: Bool) -> some ChartContent {
  472. /// glucose point mark
  473. /// filtering for high and low bounds in settings
  474. ForEach(state.glucoseFromPersistence) { item in
  475. if smooth {
  476. if item.glucose > Int(highGlucose) {
  477. PointMark(
  478. x: .value("Time", item.date ?? Date(), unit: .second),
  479. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  480. ).foregroundStyle(Color.orange.gradient).symbolSize(20).interpolationMethod(.cardinal)
  481. } else if item.glucose < Int(lowGlucose) {
  482. PointMark(
  483. x: .value("Time", item.date ?? Date(), unit: .second),
  484. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  485. ).foregroundStyle(Color.red.gradient).symbolSize(20).interpolationMethod(.cardinal)
  486. } else {
  487. PointMark(
  488. x: .value("Time", item.date ?? Date(), unit: .second),
  489. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  490. ).foregroundStyle(Color.green.gradient).symbolSize(20).interpolationMethod(.cardinal)
  491. }
  492. } else {
  493. if item.glucose > Int(highGlucose) {
  494. PointMark(
  495. x: .value("Time", item.date ?? Date(), unit: .second),
  496. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  497. ).foregroundStyle(Color.orange.gradient).symbolSize(20)
  498. } else if item.glucose < Int(lowGlucose) {
  499. PointMark(
  500. x: .value("Time", item.date ?? Date(), unit: .second),
  501. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  502. ).foregroundStyle(Color.red.gradient).symbolSize(20)
  503. } else {
  504. PointMark(
  505. x: .value("Time", item.date ?? Date(), unit: .second),
  506. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  507. ).foregroundStyle(Color.green.gradient).symbolSize(20)
  508. }
  509. }
  510. }
  511. }
  512. private func timeForIndex(_ index: Int32) -> Date {
  513. let currentTime = Date()
  514. let timeInterval = TimeInterval(index * 300)
  515. return currentTime.addingTimeInterval(timeInterval)
  516. }
  517. private func drawForecastsCone() -> some ChartContent {
  518. // Draw AreaMark for the forecast bounds
  519. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  520. if index < state.minForecast.count, index < state.maxForecast.count {
  521. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index]) : Decimal(state.minForecast[index]).asMmolL
  522. let yMaxValue = units == .mgdL ? Decimal(state.maxForecast[index]) : Decimal(state.maxForecast[index]).asMmolL
  523. let xValue = timeForIndex(Int32(index))
  524. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  525. AreaMark(
  526. x: .value("Time", xValue),
  527. // maxValue is already parsed to user units, no need to parse
  528. yStart: .value("Min Value", yMinValue <= maxValue ? yMinValue : maxValue),
  529. yEnd: .value("Max Value", yMaxValue <= maxValue ? yMaxValue : maxValue)
  530. )
  531. .foregroundStyle(Color.blue.opacity(0.5))
  532. .interpolationMethod(.catmullRom)
  533. }
  534. }
  535. }
  536. }
  537. private func drawForecastsLines() -> some ChartContent {
  538. ForEach(state.preprocessedData, id: \.id) { tuple in
  539. let forecastValue = tuple.forecastValue
  540. let forecast = tuple.forecast
  541. let valueAsDecimal = Decimal(forecastValue.value)
  542. let displayValue = units == .mmolL ? valueAsDecimal.asMmolL : valueAsDecimal
  543. let xValue = timeForIndex(forecastValue.index)
  544. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  545. LineMark(
  546. x: .value("Time", xValue),
  547. y: .value("Value", displayValue)
  548. )
  549. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  550. }
  551. }
  552. }
  553. private func drawCurrentTimeMarker() -> some ChartContent {
  554. RuleMark(
  555. x: .value(
  556. "",
  557. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  558. unit: .second
  559. )
  560. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  561. }
  562. private func drawStartRuleMark() -> some ChartContent {
  563. RuleMark(
  564. x: .value(
  565. "",
  566. startMarker,
  567. unit: .second
  568. )
  569. ).foregroundStyle(Color.clear)
  570. }
  571. private func drawEndRuleMark() -> some ChartContent {
  572. RuleMark(
  573. x: .value(
  574. "",
  575. endMarker,
  576. unit: .second
  577. )
  578. ).foregroundStyle(Color.clear)
  579. }
  580. private func drawTempTargets() -> some ChartContent {
  581. /// temp targets
  582. ForEach(chartTempTargets, id: \.self) { target in
  583. let targetLimited = min(max(target.amount, 0), upperLimit)
  584. RuleMark(
  585. xStart: .value("Start", target.start),
  586. xEnd: .value("End", target.end),
  587. y: .value("Value", targetLimited)
  588. )
  589. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  590. }
  591. }
  592. private func drawActiveOverrides() -> some ChartContent {
  593. ForEach(state.overrides) { override in
  594. let start: Date = override.date ?? .distantPast
  595. let duration = state.calculateDuration(override: override)
  596. let end: Date = start.addingTimeInterval(duration)
  597. let target = state.calculateTarget(override: override)
  598. RuleMark(
  599. xStart: .value("Start", start, unit: .second),
  600. xEnd: .value("End", end, unit: .second),
  601. y: .value("Value", target)
  602. )
  603. .foregroundStyle(Color.purple.opacity(0.6))
  604. .lineStyle(.init(lineWidth: 8))
  605. // .annotation(position: .overlay, spacing: 0) {
  606. // if let name = override.name {
  607. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  608. // }
  609. // }
  610. }
  611. }
  612. private func drawOverrideRunStored() -> some ChartContent {
  613. ForEach(state.overrideRunStored) { overrideRunStored in
  614. let start: Date = overrideRunStored.startDate ?? .distantPast
  615. let end: Date = overrideRunStored.endDate ?? Date()
  616. let target = overrideRunStored.target?.decimalValue ?? 100
  617. RuleMark(
  618. xStart: .value("Start", start, unit: .second),
  619. xEnd: .value("End", end, unit: .second),
  620. y: .value("Value", target)
  621. )
  622. .foregroundStyle(Color.purple.opacity(0.4))
  623. .lineStyle(.init(lineWidth: 8))
  624. // .annotation(position: .bottom, spacing: 0) {
  625. // if let name = overrideRunStored.override?.name {
  626. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  627. // }
  628. // }
  629. }
  630. }
  631. private func drawManualGlucose() -> some ChartContent {
  632. /// manual glucose mark
  633. ForEach(state.manualGlucoseFromPersistence) { item in
  634. let manualGlucose = item.glucose
  635. PointMark(
  636. x: .value("Time", item.date ?? Date(), unit: .second),
  637. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  638. )
  639. .symbol {
  640. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  641. .foregroundStyle(.red)
  642. }
  643. }
  644. }
  645. private func drawSuspensions() -> some ChartContent {
  646. let suspensions = state.suspensions
  647. return ForEach(suspensions) { suspension in
  648. let now = Date()
  649. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  650. let suspensionEnd = min(
  651. (
  652. suspensions
  653. .first(where: {
  654. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  655. .timestamp
  656. ) ?? now,
  657. now
  658. )
  659. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  660. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  661. RectangleMark(
  662. xStart: .value("start", suspensionStart),
  663. xEnd: .value("end", suspensionEnd),
  664. yStart: .value("suspend-start", 0),
  665. yEnd: .value("suspend-end", suspensionMarkHeight)
  666. )
  667. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  668. }
  669. }
  670. }
  671. private func drawIOB() -> some ChartContent {
  672. ForEach(state.enactedAndNonEnactedDeterminations) { iob in
  673. let rawAmount = iob.iob?.doubleValue ?? 0
  674. let amount: Double = rawAmount > 0 ? rawAmount : rawAmount * 2 // weigh negative iob with factor 2
  675. let date: Date = iob.deliverAt ?? Date()
  676. LineMark(x: .value("Time", date), y: .value("Amount", amount))
  677. .foregroundStyle(Color.darkerBlue)
  678. AreaMark(x: .value("Time", date), y: .value("Amount", amount))
  679. .foregroundStyle(
  680. LinearGradient(
  681. gradient: Gradient(
  682. colors: [
  683. Color.darkerBlue.opacity(0.8),
  684. Color.darkerBlue.opacity(0.01)
  685. ]
  686. ),
  687. startPoint: .top,
  688. endPoint: .bottom
  689. )
  690. )
  691. }
  692. }
  693. private func drawCOB(dummy: Bool) -> some ChartContent {
  694. ForEach(state.enactedAndNonEnactedDeterminations) { cob in
  695. let amount = Int(cob.cob)
  696. let date: Date = cob.deliverAt ?? Date()
  697. if dummy {
  698. LineMark(x: .value("Time", date), y: .value("Value", amount))
  699. .foregroundStyle(Color.clear)
  700. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  701. Color.clear
  702. )
  703. } else {
  704. LineMark(x: .value("Time", date), y: .value("Value", amount))
  705. .foregroundStyle(Color.orange.gradient)
  706. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  707. LinearGradient(
  708. gradient: Gradient(
  709. colors: [
  710. Color.orange.opacity(0.8),
  711. Color.orange.opacity(0.01)
  712. ]
  713. ),
  714. startPoint: .top,
  715. endPoint: .bottom
  716. )
  717. )
  718. }
  719. }
  720. }
  721. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  722. let now = Date()
  723. let tempBasals = state.tempBasals
  724. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  725. let duration = temp.tempBasal?.duration ?? 0
  726. let timestamp = temp.timestamp ?? Date()
  727. let end = min(timestamp + duration.minutes, now)
  728. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  729. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  730. // Check if there's a subsequent temp basal to determine the end time
  731. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  732. return (timestamp, end, rate)
  733. }
  734. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  735. }
  736. }
  737. private func drawTempBasals(dummy: Bool) -> some ChartContent {
  738. ForEach(prepareTempBasals(), id: \.rate) { basal in
  739. if dummy {
  740. RectangleMark(
  741. xStart: .value("start", basal.start),
  742. xEnd: .value("end", basal.end),
  743. yStart: .value("rate-start", 0),
  744. yEnd: .value("rate-end", basal.rate)
  745. ).foregroundStyle(Color.clear)
  746. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  747. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  748. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  749. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  750. } else {
  751. RectangleMark(
  752. xStart: .value("start", basal.start),
  753. xEnd: .value("end", basal.end),
  754. yStart: .value("rate-start", 0),
  755. yEnd: .value("rate-end", basal.rate)
  756. ).foregroundStyle(
  757. LinearGradient(
  758. gradient: Gradient(
  759. colors: [
  760. Color.insulin.opacity(0.6),
  761. Color.insulin.opacity(0.1)
  762. ]
  763. ),
  764. startPoint: .top,
  765. endPoint: .bottom
  766. )
  767. )
  768. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  769. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  770. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  771. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  772. }
  773. }
  774. }
  775. private func drawBasalProfile() -> some ChartContent {
  776. /// dashed profile line
  777. ForEach(basalProfiles, id: \.self) { profile in
  778. LineMark(
  779. x: .value("Start Date", profile.startDate),
  780. y: .value("Amount", profile.amount),
  781. series: .value("profile", "profile")
  782. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  783. LineMark(
  784. x: .value("End Date", profile.endDate ?? endMarker),
  785. y: .value("Amount", profile.amount),
  786. series: .value("profile", "profile")
  787. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  788. }
  789. }
  790. /// calculates the glucose value thats the nearest to parameter 'time'
  791. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  792. guard !state.glucoseFromPersistence.isEmpty else {
  793. return nil
  794. }
  795. // sort by date
  796. let sortedGlucose = state.glucoseFromPersistence
  797. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  798. var low = 0
  799. var high = sortedGlucose.count - 1
  800. var closestGlucose: GlucoseStored?
  801. // binary search to find next glucose
  802. while low <= high {
  803. let mid = low + (high - low) / 2
  804. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  805. if midTime == time {
  806. return sortedGlucose[mid]
  807. } else if midTime < time {
  808. low = mid + 1
  809. } else {
  810. high = mid - 1
  811. }
  812. // update if necessary
  813. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  814. closestGlucose = sortedGlucose[mid]
  815. }
  816. }
  817. return closestGlucose
  818. }
  819. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  820. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  821. }
  822. /// calculations for temp target bar mark
  823. private func calculateTTs() {
  824. var groupedPackages: [[TempTarget]] = []
  825. var currentPackage: [TempTarget] = []
  826. var calculatedTTs: [ChartTempTarget] = []
  827. for target in tempTargets {
  828. if target.duration > 0 {
  829. if !currentPackage.isEmpty {
  830. groupedPackages.append(currentPackage)
  831. currentPackage = []
  832. }
  833. currentPackage.append(target)
  834. } else {
  835. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  836. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  837. target.createdAt <= lastNonZeroTempTarget.createdAt
  838. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  839. {
  840. currentPackage.append(target)
  841. }
  842. }
  843. }
  844. }
  845. // appends last package, if exists
  846. if !currentPackage.isEmpty {
  847. groupedPackages.append(currentPackage)
  848. }
  849. for package in groupedPackages {
  850. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  851. continue
  852. }
  853. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  854. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  855. if let earliestCancelTarget = earliestCancelTarget {
  856. end = min(earliestCancelTarget.createdAt, end)
  857. }
  858. let now = Date()
  859. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  860. if firstNonZeroTarget.targetTop != nil {
  861. calculatedTTs
  862. .append(ChartTempTarget(
  863. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  864. start: firstNonZeroTarget.createdAt,
  865. end: end
  866. ))
  867. }
  868. }
  869. chartTempTargets = calculatedTTs
  870. }
  871. private func findRegularBasalPoints(
  872. timeBegin: TimeInterval,
  873. timeEnd: TimeInterval,
  874. autotuned: Bool
  875. ) -> [BasalProfile] {
  876. guard timeBegin < timeEnd else {
  877. return []
  878. }
  879. let beginDate = Date(timeIntervalSince1970: timeBegin)
  880. let calendar = Calendar.current
  881. let startOfDay = calendar.startOfDay(for: beginDate)
  882. let profile = autotuned ? autotunedBasalProfile : basalProfile
  883. let basalNormalized = profile.map {
  884. (
  885. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  886. rate: $0.rate
  887. )
  888. } + profile.map {
  889. (
  890. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  891. .timeIntervalSince1970,
  892. rate: $0.rate
  893. )
  894. } + profile.map {
  895. (
  896. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  897. .timeIntervalSince1970,
  898. rate: $0.rate
  899. )
  900. }
  901. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  902. .compactMap { window -> BasalProfile? in
  903. let window = Array(window)
  904. if window[0].time < timeBegin, window[1].time < timeBegin {
  905. return nil
  906. }
  907. if window[0].time < timeBegin, window[1].time >= timeBegin {
  908. let startDate = Date(timeIntervalSince1970: timeBegin)
  909. let rate = window[0].rate
  910. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  911. }
  912. if window[0].time >= timeBegin, window[0].time < timeEnd {
  913. let startDate = Date(timeIntervalSince1970: window[0].time)
  914. let rate = window[0].rate
  915. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  916. }
  917. return nil
  918. }
  919. return basalTruncatedPoints
  920. }
  921. /// update start and end marker to fix scroll update problem with x axis
  922. private func updateStartEndMarkers() {
  923. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  924. // endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  925. }
  926. private func calculateBasals() {
  927. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  928. let regularPoints = findRegularBasalPoints(
  929. timeBegin: dayAgoTime,
  930. timeEnd: endMarker.timeIntervalSince1970,
  931. autotuned: false
  932. )
  933. let autotunedBasalPoints = findRegularBasalPoints(
  934. timeBegin: dayAgoTime,
  935. timeEnd: endMarker.timeIntervalSince1970,
  936. autotuned: true
  937. )
  938. var totalBasal = regularPoints + autotunedBasalPoints
  939. totalBasal.sort {
  940. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  941. }
  942. var basals: [BasalProfile] = []
  943. totalBasal.indices.forEach { index in
  944. basals.append(BasalProfile(
  945. amount: totalBasal[index].amount,
  946. isOverwritten: totalBasal[index].isOverwritten,
  947. startDate: totalBasal[index].startDate,
  948. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  949. ))
  950. }
  951. basalProfiles = basals
  952. }
  953. // MARK: - Chart formatting
  954. private func yAxisChartData() {
  955. let glucoseMapped = state.glucoseFromPersistence.map { Decimal($0.glucose) }
  956. let forecastValues = state.preprocessedData.map { Decimal($0.forecastValue.value) }
  957. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max(),
  958. let minForecast = forecastValues.min(), let maxForecast = forecastValues.max()
  959. else {
  960. // default values
  961. minValue = 45 * conversionFactor - 20 * conversionFactor
  962. maxValue = 270 * conversionFactor + 50 * conversionFactor
  963. return
  964. }
  965. // Ensure maxForecast is not more than 100 over maxGlucose
  966. let adjustedMaxForecast = min(maxForecast, maxGlucose + 100)
  967. let minOverall = min(minGlucose, minForecast)
  968. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  969. minValue = minOverall * conversionFactor - 50 * conversionFactor
  970. maxValue = maxOverall * conversionFactor + 80 * conversionFactor
  971. }
  972. private func yAxisChartDataCobChart() {
  973. let cobMapped = state.enactedAndNonEnactedDeterminations.map { Decimal($0.cob) }
  974. guard let maxCob = cobMapped.max() else {
  975. // default values
  976. minValueCobChart = 0
  977. maxValueCobChart = 20
  978. return
  979. }
  980. maxValueCobChart = maxCob == 0 ? 20 : maxCob +
  981. 20 // 2 is added to the max of iob and to keep the 1:10 ratio we add 20 here
  982. }
  983. private func yAxisChartDataIobChart() {
  984. let iobMapped = state.enactedAndNonEnactedDeterminations.compactMap { $0.iob?.decimalValue }
  985. guard let minIob = iobMapped.min(), let maxIob = iobMapped.max() else {
  986. // default values
  987. minValueIobChart = 0
  988. maxValueIobChart = 5
  989. return
  990. }
  991. minValueIobChart = minIob // we need to set this here because IOB can also be negative
  992. minValueCobChart = minIob < 0 ? minIob - 2 :
  993. 0 // if there is negative IOB the COB-X-Axis should still align with the IOB-X-Axis; 2 is only subtracted to make the charts align
  994. maxValueIobChart = maxIob + 2
  995. }
  996. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  997. plotContent
  998. .rotationEffect(.degrees(180))
  999. .scaleEffect(x: -1, y: 1)
  1000. }
  1001. private var mainChartXAxis: some AxisContent {
  1002. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1003. if displayXgridLines {
  1004. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1005. } else {
  1006. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1007. }
  1008. }
  1009. }
  1010. private var basalChartXAxis: some AxisContent {
  1011. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1012. if displayXgridLines {
  1013. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1014. } else {
  1015. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1016. }
  1017. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  1018. .font(.footnote).foregroundStyle(Color.primary)
  1019. }
  1020. }
  1021. private var mainChartYAxis: some AxisContent {
  1022. AxisMarks(position: .trailing) { value in
  1023. if displayXgridLines {
  1024. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1025. } else {
  1026. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1027. }
  1028. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  1029. /// fix offset between the two charts...
  1030. if units == .mmolL {
  1031. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  1032. }
  1033. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  1034. }
  1035. }
  1036. }
  1037. private var cobChartYAxis: some AxisContent {
  1038. AxisMarks(position: .trailing) { _ in
  1039. if displayXgridLines {
  1040. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1041. } else {
  1042. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1043. }
  1044. }
  1045. }
  1046. }
  1047. struct LegendItem: View {
  1048. var color: Color
  1049. var label: String
  1050. var body: some View {
  1051. Group {
  1052. Circle().fill(color).frame(width: 8, height: 8)
  1053. Text(label)
  1054. .font(.system(size: 10, weight: .bold))
  1055. .foregroundColor(color)
  1056. }
  1057. }
  1058. }
  1059. extension Int16 {
  1060. var minutes: TimeInterval {
  1061. TimeInterval(self) * 60
  1062. }
  1063. }