MainChartView.swift 36 KB

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