MainChartView.swift 34 KB

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