MainChartView.swift 34 KB

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