MainChartView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. @Binding var units: GlucoseUnits
  34. @Binding var announcement: [Announcement]
  35. @Binding var hours: Int
  36. @Binding var maxBasal: Decimal
  37. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  38. @Binding var basalProfile: [BasalProfileEntry]
  39. @Binding var tempTargets: [TempTarget]
  40. @Binding var smooth: Bool
  41. @Binding var highGlucose: Decimal
  42. @Binding var lowGlucose: Decimal
  43. @Binding var screenHours: Int16
  44. @Binding var displayXgridLines: Bool
  45. @Binding var displayYgridLines: Bool
  46. @Binding var thresholdLines: Bool
  47. @Binding var isTempTargetActive: Bool
  48. @StateObject var state: Home.StateModel
  49. @State var didAppearTrigger = false
  50. @State private var basalProfiles: [BasalProfile] = []
  51. @State private var chartTempTargets: [ChartTempTarget] = []
  52. @State private var count: Decimal = 1
  53. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  54. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  55. @State private var minValue: Decimal = 45
  56. @State private var maxValue: Decimal = 270
  57. @State private var selection: Date? = nil
  58. private let now = Date.now
  59. private let context = CoreDataStack.shared.persistentContainer.viewContext
  60. @Environment(\.colorScheme) var colorScheme
  61. @Environment(\.calendar) var calendar
  62. private var bolusFormatter: NumberFormatter {
  63. let formatter = NumberFormatter()
  64. formatter.numberStyle = .decimal
  65. formatter.minimumIntegerDigits = 0
  66. formatter.maximumFractionDigits = 2
  67. formatter.decimalSeparator = "."
  68. return formatter
  69. }
  70. private var carbsFormatter: NumberFormatter {
  71. let formatter = NumberFormatter()
  72. formatter.numberStyle = .decimal
  73. formatter.maximumFractionDigits = 0
  74. return formatter
  75. }
  76. private var conversionFactor: Decimal {
  77. units == .mmolL ? 0.0555 : 1
  78. }
  79. private var upperLimit: Decimal {
  80. units == .mgdL ? 400 : 22.2
  81. }
  82. private var defaultBolusPosition: Int {
  83. units == .mgdL ? 120 : 7
  84. }
  85. private var bolusOffset: Decimal {
  86. units == .mgdL ? 30 : 1.66
  87. }
  88. private var selectedGlucose: GlucoseStored? {
  89. if let selection = selection {
  90. let lowerBound = selection.addingTimeInterval(-120)
  91. let upperBound = selection.addingTimeInterval(120)
  92. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  93. } else {
  94. return nil
  95. }
  96. }
  97. var body: some View {
  98. VStack {
  99. ZStack {
  100. VStack {
  101. staticYAxisChart
  102. dummyBasalChart
  103. }
  104. ScrollViewReader { scroller in
  105. ScrollView(.horizontal, showsIndicators: false) {
  106. VStack(spacing: 0) {
  107. mainChart
  108. basalChart
  109. }.onChange(of: screenHours) { _ in
  110. updateStartEndMarkers()
  111. yAxisChartData()
  112. scroller.scrollTo("MainChart", anchor: .trailing)
  113. }
  114. .onChange(of: state.glucoseFromPersistence.last?.glucose) { _ in
  115. updateStartEndMarkers()
  116. yAxisChartData()
  117. scroller.scrollTo("MainChart", anchor: .trailing)
  118. }
  119. .onChange(of: state.determinationsFromPersistence.last?.deliverAt) { _ in
  120. updateStartEndMarkers()
  121. scroller.scrollTo("MainChart", anchor: .trailing)
  122. }
  123. .onChange(of: state.tempBasals) { _ in
  124. updateStartEndMarkers()
  125. scroller.scrollTo("MainChart", anchor: .trailing)
  126. }
  127. .onChange(of: units) { _ in
  128. yAxisChartData()
  129. }
  130. .onAppear {
  131. updateStartEndMarkers()
  132. scroller.scrollTo("MainChart", anchor: .trailing)
  133. }
  134. }
  135. }
  136. }
  137. legendPanel.padding(.top, 8)
  138. }
  139. }
  140. }
  141. // MARK: - Components
  142. struct Backport<Content: View> {
  143. let content: Content
  144. }
  145. extension View {
  146. var backport: Backport<Self> { Backport(content: self) }
  147. }
  148. extension Backport {
  149. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  150. if #available(iOS 17, *) {
  151. content.chartXSelection(value: value)
  152. } else {
  153. content
  154. }
  155. }
  156. }
  157. extension MainChartView {
  158. /// 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
  159. private var staticYAxisChart: some View {
  160. Chart {
  161. /// high and low threshold lines
  162. if thresholdLines {
  163. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  164. .lineStyle(.init(lineWidth: 1, dash: [5]))
  165. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  166. .lineStyle(.init(lineWidth: 1, dash: [5]))
  167. }
  168. }
  169. .id("DummyMainChart")
  170. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  171. .frame(width: screenSize.width - 10)
  172. .chartYAxis { mainChartYAxis }
  173. .chartXAxis(.hidden)
  174. .chartYScale(domain: minValue ... maxValue)
  175. .chartLegend(.hidden)
  176. }
  177. private var dummyBasalChart: some View {
  178. Chart {}
  179. .id("DummyBasalChart")
  180. .frame(height: UIScreen.main.bounds.height * 0.08)
  181. .frame(width: screenSize.width - 10)
  182. .chartYAxis(.hidden)
  183. .chartXAxis(.hidden)
  184. .chartYScale(domain: minValue ... maxValue)
  185. .chartLegend(.hidden)
  186. }
  187. private var mainChart: some View {
  188. VStack {
  189. Chart {
  190. drawStartRuleMark()
  191. drawEndRuleMark()
  192. drawCurrentTimeMarker()
  193. drawCarbs()
  194. drawFpus()
  195. drawBoluses()
  196. drawTempTargets()
  197. drawActiveOverrides()
  198. drawOverrideRunStored()
  199. drawForecasts()
  200. drawGlucose()
  201. drawManualGlucose()
  202. /// show glucose value when hovering over it
  203. if let selectedGlucose {
  204. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  205. .foregroundStyle(Color.tabBar)
  206. .offset(yStart: 70)
  207. .lineStyle(.init(lineWidth: 2, dash: [5]))
  208. .annotation(position: .top) {
  209. selectionPopover
  210. }
  211. }
  212. }
  213. .id("MainChart")
  214. .onChange(of: state.insulinFromPersistence) { _ in
  215. state.roundedTotalBolus = state.calculateTINS()
  216. }
  217. .onChange(of: tempTargets) { _ in
  218. calculateTTs()
  219. }
  220. .onChange(of: didAppearTrigger) { _ in
  221. calculateTTs()
  222. }
  223. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  224. .frame(width: fullWidth(viewWidth: screenSize.width))
  225. .chartXScale(domain: startMarker ... endMarker)
  226. .chartXAxis { mainChartXAxis }
  227. .chartYAxis(.hidden)
  228. .backport.chartXSelection(value: $selection)
  229. .chartYScale(domain: minValue ... maxValue)
  230. .chartForegroundStyleScale([
  231. "zt": Color.zt,
  232. "uam": Color.uam,
  233. "cob": .orange,
  234. "iob": .blue
  235. ])
  236. .chartLegend(.hidden)
  237. }
  238. }
  239. @ViewBuilder var selectionPopover: some View {
  240. if let sgv = selectedGlucose?.glucose {
  241. let glucoseToShow = Decimal(sgv) * conversionFactor
  242. VStack {
  243. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  244. HStack {
  245. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  246. .fontWeight(.bold)
  247. .foregroundStyle(
  248. Decimal(sgv) < lowGlucose ? Color
  249. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  250. )
  251. Text(units.rawValue).foregroundColor(.secondary)
  252. }
  253. }
  254. .padding(6)
  255. .background {
  256. RoundedRectangle(cornerRadius: 4)
  257. .fill(Color.gray.opacity(0.1))
  258. .shadow(color: .blue, radius: 2)
  259. }
  260. }
  261. }
  262. private var basalChart: some View {
  263. VStack {
  264. Chart {
  265. drawStartRuleMark()
  266. drawEndRuleMark()
  267. drawCurrentTimeMarker()
  268. drawTempBasals()
  269. drawBasalProfile()
  270. drawSuspensions()
  271. }.onChange(of: state.tempBasals) { _ in
  272. calculateBasals()
  273. }
  274. .onChange(of: maxBasal) { _ in
  275. calculateBasals()
  276. }
  277. .onChange(of: autotunedBasalProfile) { _ in
  278. calculateBasals()
  279. }
  280. .onChange(of: didAppearTrigger) { _ in
  281. calculateBasals()
  282. }.onChange(of: basalProfile) { _ in
  283. calculateBasals()
  284. }
  285. .frame(height: UIScreen.main.bounds.height * 0.08)
  286. .frame(width: fullWidth(viewWidth: screenSize.width))
  287. .chartXScale(domain: startMarker ... endMarker)
  288. .chartXAxis { basalChartXAxis }
  289. .chartYAxis(.hidden)
  290. }
  291. }
  292. var legendPanel: some View {
  293. HStack(spacing: 10) {
  294. Spacer()
  295. LegendItem(color: .loopGreen, label: "BG")
  296. LegendItem(color: .insulin, label: "IOB")
  297. LegendItem(color: .zt, label: "ZT")
  298. LegendItem(color: .loopYellow, label: "COB")
  299. LegendItem(color: .uam, label: "UAM")
  300. Spacer()
  301. }
  302. .padding(.horizontal, 10)
  303. .frame(maxWidth: .infinity)
  304. }
  305. }
  306. // MARK: - Calculations
  307. extension MainChartView {
  308. private func drawBoluses() -> some ChartContent {
  309. ForEach(state.insulinFromPersistence) { insulin in
  310. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  311. let bolusDate = insulin.timestamp ?? Date()
  312. if amount != 0, let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)?.glucose {
  313. let yPosition = (Decimal(glucose) * conversionFactor) + bolusOffset
  314. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  315. PointMark(
  316. x: .value("Time", bolusDate, unit: .second),
  317. y: .value("Value", yPosition)
  318. )
  319. .symbol {
  320. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  321. }
  322. .annotation(position: .top) {
  323. Text(bolusFormatter.string(from: amount) ?? "")
  324. .font(.caption2)
  325. .foregroundStyle(Color.insulin)
  326. }
  327. }
  328. }
  329. }
  330. private func drawCarbs() -> some ChartContent {
  331. /// carbs
  332. ForEach(state.carbsFromPersistence) { carb in
  333. let carbAmount = carb.carbs
  334. let yPosition = units == .mgdL ? 60 : 3.33
  335. PointMark(
  336. x: .value("Time", carb.date ?? Date(), unit: .second),
  337. y: .value("Value", yPosition)
  338. )
  339. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  340. .foregroundStyle(Color.orange)
  341. .annotation(position: .bottom) {
  342. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  343. .foregroundStyle(Color.orange)
  344. }
  345. }
  346. }
  347. private func drawFpus() -> some ChartContent {
  348. /// fpus
  349. ForEach(state.fpusFromPersistence, id: \.id) { fpu in
  350. let fpuAmount = fpu.carbs
  351. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  352. let yPosition = units == .mgdL ? 60 : 3.33
  353. PointMark(
  354. x: .value("Time", fpu.date ?? Date(), unit: .second),
  355. y: .value("Value", yPosition)
  356. )
  357. .symbolSize(size)
  358. .foregroundStyle(Color.brown)
  359. }
  360. }
  361. private func drawGlucose() -> some ChartContent {
  362. /// glucose point mark
  363. /// filtering for high and low bounds in settings
  364. ForEach(state.glucoseFromPersistence) { item in
  365. if smooth {
  366. if item.glucose > Int(highGlucose) {
  367. PointMark(
  368. x: .value("Time", item.date ?? Date(), unit: .second),
  369. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  370. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  371. } else if item.glucose < Int(lowGlucose) {
  372. PointMark(
  373. x: .value("Time", item.date ?? Date(), unit: .second),
  374. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  375. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  376. } else {
  377. PointMark(
  378. x: .value("Time", item.date ?? Date(), unit: .second),
  379. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  380. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  381. }
  382. } else {
  383. if item.glucose > Int(highGlucose) {
  384. PointMark(
  385. x: .value("Time", item.date ?? Date(), unit: .second),
  386. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  387. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  388. } else if item.glucose < Int(lowGlucose) {
  389. PointMark(
  390. x: .value("Time", item.date ?? Date(), unit: .second),
  391. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  392. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  393. } else {
  394. PointMark(
  395. x: .value("Time", item.date ?? Date(), unit: .second),
  396. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  397. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  398. }
  399. }
  400. }
  401. }
  402. private func timeForIndex(_ index: Int32) -> Date {
  403. let currentTime = Date()
  404. let timeInterval = TimeInterval(index * 300)
  405. return currentTime.addingTimeInterval(timeInterval)
  406. }
  407. private func getForecasts(for determinationID: NSManagedObjectID, in context: NSManagedObjectContext) -> [Forecast] {
  408. do {
  409. guard let determination = try context.existingObject(with: determinationID) as? OrefDetermination,
  410. let forecastSet = determination.forecasts,
  411. let forecasts = Array(forecastSet) as? [Forecast]
  412. else {
  413. return []
  414. }
  415. return forecasts
  416. } catch {
  417. debugPrint(
  418. "Failed \(DebuggingIdentifiers.failed) to fetch OrefDetermination with ID \(determinationID): \(error.localizedDescription)"
  419. )
  420. return []
  421. }
  422. }
  423. private func getForecastValues(for forecastID: NSManagedObjectID, in context: NSManagedObjectContext) -> [ForecastValue] {
  424. do {
  425. guard let forecast = try context.existingObject(with: forecastID) as? Forecast,
  426. let forecastValueSet = forecast.forecastValues,
  427. let forecastValues = Array(forecastValueSet) as? [ForecastValue]
  428. else {
  429. return []
  430. }
  431. return forecastValues.sorted(by: { $0.index < $1.index })
  432. } catch {
  433. debugPrint(
  434. "Failed \(DebuggingIdentifiers.failed) to fetch Forecast with ID \(forecastID): \(error.localizedDescription)"
  435. )
  436. return []
  437. }
  438. }
  439. private func drawForecasts() -> some ChartContent {
  440. let preprocessedData = preprocessForecastData()
  441. return ForEach(preprocessedData, id: \.id) { tuple in
  442. let forecastValue = tuple.forecastValue
  443. let forecast = tuple.forecast
  444. LineMark(
  445. x: .value("Time", timeForIndex(forecastValue.index)),
  446. y: .value("Value", Int(forecastValue.value))
  447. )
  448. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  449. }
  450. }
  451. private func preprocessForecastData() -> [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] {
  452. state.determinationsFromPersistence
  453. .compactMap { determination -> NSManagedObjectID? in
  454. determination.objectID
  455. }
  456. .flatMap { determinationID -> [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] in
  457. let forecasts = getForecasts(for: determinationID, in: context)
  458. return forecasts.flatMap { forecast in
  459. getForecastValues(for: forecast.objectID, in: context).map { forecastValue in
  460. (id: UUID(), forecast: forecast, forecastValue: forecastValue)
  461. }
  462. }
  463. }
  464. }
  465. private func drawCurrentTimeMarker() -> some ChartContent {
  466. RuleMark(
  467. x: .value(
  468. "",
  469. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  470. unit: .second
  471. )
  472. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  473. }
  474. private func drawStartRuleMark() -> some ChartContent {
  475. RuleMark(
  476. x: .value(
  477. "",
  478. startMarker,
  479. unit: .second
  480. )
  481. ).foregroundStyle(Color.clear)
  482. }
  483. private func drawEndRuleMark() -> some ChartContent {
  484. RuleMark(
  485. x: .value(
  486. "",
  487. endMarker,
  488. unit: .second
  489. )
  490. ).foregroundStyle(Color.clear)
  491. }
  492. private func drawTempTargets() -> some ChartContent {
  493. /// temp targets
  494. ForEach(chartTempTargets, id: \.self) { target in
  495. let targetLimited = min(max(target.amount, 0), upperLimit)
  496. RuleMark(
  497. xStart: .value("Start", target.start),
  498. xEnd: .value("End", target.end),
  499. y: .value("Value", targetLimited)
  500. )
  501. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  502. }
  503. }
  504. private func drawActiveOverrides() -> some ChartContent {
  505. ForEach(state.overrides) { override in
  506. let start: Date = override.date ?? .distantPast
  507. let duration = state.calculateDuration(override: override)
  508. let end: Date = start.addingTimeInterval(duration)
  509. let target = state.calculateTarget(override: override)
  510. RuleMark(
  511. xStart: .value("Start", start, unit: .second),
  512. xEnd: .value("End", end, unit: .second),
  513. y: .value("Value", target)
  514. )
  515. .foregroundStyle(Color.purple.opacity(0.6))
  516. .lineStyle(.init(lineWidth: 8))
  517. // .annotation(position: .overlay, spacing: 0) {
  518. // if let name = override.name {
  519. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  520. // }
  521. // }
  522. }
  523. }
  524. private func drawOverrideRunStored() -> some ChartContent {
  525. ForEach(state.overrideRunStored) { overrideRunStored in
  526. let start: Date = overrideRunStored.startDate ?? .distantPast
  527. let end: Date = overrideRunStored.endDate ?? Date()
  528. let target = overrideRunStored.target?.decimalValue ?? 100
  529. RuleMark(
  530. xStart: .value("Start", start, unit: .second),
  531. xEnd: .value("End", end, unit: .second),
  532. y: .value("Value", target)
  533. )
  534. .foregroundStyle(Color.purple.opacity(0.4))
  535. .lineStyle(.init(lineWidth: 8))
  536. // .annotation(position: .bottom, spacing: 0) {
  537. // if let name = overrideRunStored.override?.name {
  538. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  539. // }
  540. // }
  541. }
  542. }
  543. private func drawManualGlucose() -> some ChartContent {
  544. /// manual glucose mark
  545. ForEach(state.manualGlucoseFromPersistence) { item in
  546. let manualGlucose = item.glucose
  547. PointMark(
  548. x: .value("Time", item.date ?? Date(), unit: .second),
  549. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  550. )
  551. .symbol {
  552. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  553. .foregroundStyle(.red)
  554. }
  555. }
  556. }
  557. private func drawSuspensions() -> some ChartContent {
  558. let suspensions = state.suspensions
  559. return ForEach(suspensions) { suspension in
  560. let now = Date()
  561. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  562. let suspensionEnd = min(
  563. (
  564. suspensions
  565. .first(where: {
  566. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  567. .timestamp
  568. ) ?? now,
  569. now
  570. )
  571. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  572. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  573. RectangleMark(
  574. xStart: .value("start", suspensionStart),
  575. xEnd: .value("end", suspensionEnd),
  576. yStart: .value("suspend-start", 0),
  577. yEnd: .value("suspend-end", suspensionMarkHeight)
  578. )
  579. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  580. }
  581. }
  582. }
  583. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  584. let now = Date()
  585. let tempBasals = state.tempBasals
  586. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  587. let duration = temp.tempBasal?.duration ?? 0
  588. let timestamp = temp.timestamp ?? Date()
  589. let end = min(timestamp + duration.minutes, now)
  590. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  591. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  592. // Check if there's a subsequent temp basal to determine the end time
  593. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  594. return (timestamp, end, rate)
  595. }
  596. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  597. }
  598. }
  599. private func drawTempBasals() -> some ChartContent {
  600. ForEach(prepareTempBasals(), id: \.rate) { basal in
  601. RectangleMark(
  602. xStart: .value("start", basal.start),
  603. xEnd: .value("end", basal.end),
  604. yStart: .value("rate-start", 0),
  605. yEnd: .value("rate-end", basal.rate)
  606. ).foregroundStyle(Color.insulin.opacity(0.2))
  607. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  608. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  609. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  610. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  611. }
  612. }
  613. private func drawBasalProfile() -> some ChartContent {
  614. /// dashed profile line
  615. ForEach(basalProfiles, id: \.self) { profile in
  616. LineMark(
  617. x: .value("Start Date", profile.startDate),
  618. y: .value("Amount", profile.amount),
  619. series: .value("profile", "profile")
  620. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  621. LineMark(
  622. x: .value("End Date", profile.endDate ?? endMarker),
  623. y: .value("Amount", profile.amount),
  624. series: .value("profile", "profile")
  625. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  626. }
  627. }
  628. /// calculates the glucose value thats the nearest to parameter 'time'
  629. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  630. guard !state.glucoseFromPersistence.isEmpty else {
  631. return nil
  632. }
  633. // sort by date
  634. let sortedGlucose = state.glucoseFromPersistence
  635. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  636. var low = 0
  637. var high = sortedGlucose.count - 1
  638. var closestGlucose: GlucoseStored?
  639. // binary search to find next glucose
  640. while low <= high {
  641. let mid = low + (high - low) / 2
  642. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  643. if midTime == time {
  644. return sortedGlucose[mid]
  645. } else if midTime < time {
  646. low = mid + 1
  647. } else {
  648. high = mid - 1
  649. }
  650. // update if necessary
  651. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  652. closestGlucose = sortedGlucose[mid]
  653. }
  654. }
  655. return closestGlucose
  656. }
  657. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  658. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  659. }
  660. /// calculations for temp target bar mark
  661. private func calculateTTs() {
  662. var groupedPackages: [[TempTarget]] = []
  663. var currentPackage: [TempTarget] = []
  664. var calculatedTTs: [ChartTempTarget] = []
  665. for target in tempTargets {
  666. if target.duration > 0 {
  667. if !currentPackage.isEmpty {
  668. groupedPackages.append(currentPackage)
  669. currentPackage = []
  670. }
  671. currentPackage.append(target)
  672. } else {
  673. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  674. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  675. target.createdAt <= lastNonZeroTempTarget.createdAt
  676. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  677. {
  678. currentPackage.append(target)
  679. }
  680. }
  681. }
  682. }
  683. // appends last package, if exists
  684. if !currentPackage.isEmpty {
  685. groupedPackages.append(currentPackage)
  686. }
  687. for package in groupedPackages {
  688. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  689. continue
  690. }
  691. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  692. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  693. if let earliestCancelTarget = earliestCancelTarget {
  694. end = min(earliestCancelTarget.createdAt, end)
  695. }
  696. let now = Date()
  697. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  698. if firstNonZeroTarget.targetTop != nil {
  699. calculatedTTs
  700. .append(ChartTempTarget(
  701. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  702. start: firstNonZeroTarget.createdAt,
  703. end: end
  704. ))
  705. }
  706. }
  707. chartTempTargets = calculatedTTs
  708. }
  709. private func findRegularBasalPoints(
  710. timeBegin: TimeInterval,
  711. timeEnd: TimeInterval,
  712. autotuned: Bool
  713. ) -> [BasalProfile] {
  714. guard timeBegin < timeEnd else {
  715. return []
  716. }
  717. let beginDate = Date(timeIntervalSince1970: timeBegin)
  718. let calendar = Calendar.current
  719. let startOfDay = calendar.startOfDay(for: beginDate)
  720. let profile = autotuned ? autotunedBasalProfile : basalProfile
  721. let basalNormalized = profile.map {
  722. (
  723. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  724. rate: $0.rate
  725. )
  726. } + profile.map {
  727. (
  728. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  729. .timeIntervalSince1970,
  730. rate: $0.rate
  731. )
  732. } + profile.map {
  733. (
  734. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  735. .timeIntervalSince1970,
  736. rate: $0.rate
  737. )
  738. }
  739. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  740. .compactMap { window -> BasalProfile? in
  741. let window = Array(window)
  742. if window[0].time < timeBegin, window[1].time < timeBegin {
  743. return nil
  744. }
  745. if window[0].time < timeBegin, window[1].time >= timeBegin {
  746. let startDate = Date(timeIntervalSince1970: timeBegin)
  747. let rate = window[0].rate
  748. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  749. }
  750. if window[0].time >= timeBegin, window[0].time < timeEnd {
  751. let startDate = Date(timeIntervalSince1970: window[0].time)
  752. let rate = window[0].rate
  753. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  754. }
  755. return nil
  756. }
  757. return basalTruncatedPoints
  758. }
  759. /// update start and end marker to fix scroll update problem with x axis
  760. private func updateStartEndMarkers() {
  761. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  762. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  763. }
  764. private func calculateBasals() {
  765. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  766. let regularPoints = findRegularBasalPoints(
  767. timeBegin: dayAgoTime,
  768. timeEnd: endMarker.timeIntervalSince1970,
  769. autotuned: false
  770. )
  771. let autotunedBasalPoints = findRegularBasalPoints(
  772. timeBegin: dayAgoTime,
  773. timeEnd: endMarker.timeIntervalSince1970,
  774. autotuned: true
  775. )
  776. var totalBasal = regularPoints + autotunedBasalPoints
  777. totalBasal.sort {
  778. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  779. }
  780. var basals: [BasalProfile] = []
  781. totalBasal.indices.forEach { index in
  782. basals.append(BasalProfile(
  783. amount: totalBasal[index].amount,
  784. isOverwritten: totalBasal[index].isOverwritten,
  785. startDate: totalBasal[index].startDate,
  786. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  787. ))
  788. }
  789. basalProfiles = basals
  790. }
  791. // MARK: - Chart formatting
  792. private func yAxisChartData() {
  793. let glucoseMapped = state.glucoseFromPersistence.map(\.glucose)
  794. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  795. // default values
  796. minValue = 45 * conversionFactor - 20 * conversionFactor
  797. maxValue = 270 * conversionFactor + 50 * conversionFactor
  798. return
  799. }
  800. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  801. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  802. debug(.default, "min \(minValue)")
  803. debug(.default, "max \(maxValue)")
  804. }
  805. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  806. plotContent
  807. .rotationEffect(.degrees(180))
  808. .scaleEffect(x: -1, y: 1)
  809. .chartXAxis(.hidden)
  810. }
  811. private var mainChartXAxis: some AxisContent {
  812. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  813. if displayXgridLines {
  814. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  815. } else {
  816. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  817. }
  818. }
  819. }
  820. private var basalChartXAxis: some AxisContent {
  821. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  822. if displayXgridLines {
  823. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  824. } else {
  825. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  826. }
  827. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  828. .font(.footnote)
  829. }
  830. }
  831. private var mainChartYAxis: some AxisContent {
  832. AxisMarks(position: .trailing) { value in
  833. if displayXgridLines {
  834. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  835. } else {
  836. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  837. }
  838. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  839. /// fix offset between the two charts...
  840. if units == .mmolL {
  841. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  842. }
  843. AxisValueLabel().font(.footnote)
  844. }
  845. }
  846. }
  847. }
  848. struct LegendItem: View {
  849. var color: Color
  850. var label: String
  851. var body: some View {
  852. Group {
  853. Circle().fill(color).frame(width: 8, height: 8)
  854. Text(label)
  855. .font(.system(size: 10, weight: .bold))
  856. .foregroundColor(color)
  857. }
  858. }
  859. }
  860. extension Int16 {
  861. var minutes: TimeInterval {
  862. TimeInterval(self) * 60
  863. }
  864. }