MainChartView.swift 34 KB

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