MainChartView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. ForEach(state.preprocessedData, id: \.id) { tuple in
  409. let forecastValue = tuple.forecastValue
  410. let forecast = tuple.forecast
  411. LineMark(
  412. x: .value("Time", timeForIndex(forecastValue.index)),
  413. y: .value("Value", Int(forecastValue.value))
  414. )
  415. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  416. }
  417. }
  418. private func drawCurrentTimeMarker() -> some ChartContent {
  419. RuleMark(
  420. x: .value(
  421. "",
  422. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  423. unit: .second
  424. )
  425. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  426. }
  427. private func drawStartRuleMark() -> some ChartContent {
  428. RuleMark(
  429. x: .value(
  430. "",
  431. startMarker,
  432. unit: .second
  433. )
  434. ).foregroundStyle(Color.clear)
  435. }
  436. private func drawEndRuleMark() -> some ChartContent {
  437. RuleMark(
  438. x: .value(
  439. "",
  440. endMarker,
  441. unit: .second
  442. )
  443. ).foregroundStyle(Color.clear)
  444. }
  445. private func drawTempTargets() -> some ChartContent {
  446. /// temp targets
  447. ForEach(chartTempTargets, id: \.self) { target in
  448. let targetLimited = min(max(target.amount, 0), upperLimit)
  449. RuleMark(
  450. xStart: .value("Start", target.start),
  451. xEnd: .value("End", target.end),
  452. y: .value("Value", targetLimited)
  453. )
  454. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  455. }
  456. }
  457. private func drawActiveOverrides() -> some ChartContent {
  458. ForEach(state.overrides) { override in
  459. let start: Date = override.date ?? .distantPast
  460. let duration = state.calculateDuration(override: override)
  461. let end: Date = start.addingTimeInterval(duration)
  462. let target = state.calculateTarget(override: override)
  463. RuleMark(
  464. xStart: .value("Start", start, unit: .second),
  465. xEnd: .value("End", end, unit: .second),
  466. y: .value("Value", target)
  467. )
  468. .foregroundStyle(Color.purple.opacity(0.6))
  469. .lineStyle(.init(lineWidth: 8))
  470. // .annotation(position: .overlay, spacing: 0) {
  471. // if let name = override.name {
  472. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  473. // }
  474. // }
  475. }
  476. }
  477. private func drawOverrideRunStored() -> some ChartContent {
  478. ForEach(state.overrideRunStored) { overrideRunStored in
  479. let start: Date = overrideRunStored.startDate ?? .distantPast
  480. let end: Date = overrideRunStored.endDate ?? Date()
  481. let target = overrideRunStored.target?.decimalValue ?? 100
  482. RuleMark(
  483. xStart: .value("Start", start, unit: .second),
  484. xEnd: .value("End", end, unit: .second),
  485. y: .value("Value", target)
  486. )
  487. .foregroundStyle(Color.purple.opacity(0.4))
  488. .lineStyle(.init(lineWidth: 8))
  489. // .annotation(position: .bottom, spacing: 0) {
  490. // if let name = overrideRunStored.override?.name {
  491. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  492. // }
  493. // }
  494. }
  495. }
  496. private func drawManualGlucose() -> some ChartContent {
  497. /// manual glucose mark
  498. ForEach(state.manualGlucoseFromPersistence) { item in
  499. let manualGlucose = item.glucose
  500. PointMark(
  501. x: .value("Time", item.date ?? Date(), unit: .second),
  502. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  503. )
  504. .symbol {
  505. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  506. .foregroundStyle(.red)
  507. }
  508. }
  509. }
  510. private func drawSuspensions() -> some ChartContent {
  511. let suspensions = state.suspensions
  512. return ForEach(suspensions) { suspension in
  513. let now = Date()
  514. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  515. let suspensionEnd = min(
  516. (
  517. suspensions
  518. .first(where: {
  519. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  520. .timestamp
  521. ) ?? now,
  522. now
  523. )
  524. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  525. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  526. RectangleMark(
  527. xStart: .value("start", suspensionStart),
  528. xEnd: .value("end", suspensionEnd),
  529. yStart: .value("suspend-start", 0),
  530. yEnd: .value("suspend-end", suspensionMarkHeight)
  531. )
  532. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  533. }
  534. }
  535. }
  536. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  537. let now = Date()
  538. let tempBasals = state.tempBasals
  539. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  540. let duration = temp.tempBasal?.duration ?? 0
  541. let timestamp = temp.timestamp ?? Date()
  542. let end = min(timestamp + duration.minutes, now)
  543. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  544. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  545. // Check if there's a subsequent temp basal to determine the end time
  546. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  547. return (timestamp, end, rate)
  548. }
  549. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  550. }
  551. }
  552. private func drawTempBasals() -> some ChartContent {
  553. ForEach(prepareTempBasals(), id: \.rate) { basal in
  554. RectangleMark(
  555. xStart: .value("start", basal.start),
  556. xEnd: .value("end", basal.end),
  557. yStart: .value("rate-start", 0),
  558. yEnd: .value("rate-end", basal.rate)
  559. ).foregroundStyle(Color.insulin.opacity(0.2))
  560. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  561. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  562. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  563. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  564. }
  565. }
  566. private func drawBasalProfile() -> some ChartContent {
  567. /// dashed profile line
  568. ForEach(basalProfiles, id: \.self) { profile in
  569. LineMark(
  570. x: .value("Start Date", profile.startDate),
  571. y: .value("Amount", profile.amount),
  572. series: .value("profile", "profile")
  573. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  574. LineMark(
  575. x: .value("End Date", profile.endDate ?? endMarker),
  576. y: .value("Amount", profile.amount),
  577. series: .value("profile", "profile")
  578. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  579. }
  580. }
  581. /// calculates the glucose value thats the nearest to parameter 'time'
  582. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  583. guard !state.glucoseFromPersistence.isEmpty else {
  584. return nil
  585. }
  586. // sort by date
  587. let sortedGlucose = state.glucoseFromPersistence
  588. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  589. var low = 0
  590. var high = sortedGlucose.count - 1
  591. var closestGlucose: GlucoseStored?
  592. // binary search to find next glucose
  593. while low <= high {
  594. let mid = low + (high - low) / 2
  595. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  596. if midTime == time {
  597. return sortedGlucose[mid]
  598. } else if midTime < time {
  599. low = mid + 1
  600. } else {
  601. high = mid - 1
  602. }
  603. // update if necessary
  604. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  605. closestGlucose = sortedGlucose[mid]
  606. }
  607. }
  608. return closestGlucose
  609. }
  610. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  611. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  612. }
  613. /// calculations for temp target bar mark
  614. private func calculateTTs() {
  615. var groupedPackages: [[TempTarget]] = []
  616. var currentPackage: [TempTarget] = []
  617. var calculatedTTs: [ChartTempTarget] = []
  618. for target in tempTargets {
  619. if target.duration > 0 {
  620. if !currentPackage.isEmpty {
  621. groupedPackages.append(currentPackage)
  622. currentPackage = []
  623. }
  624. currentPackage.append(target)
  625. } else {
  626. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  627. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  628. target.createdAt <= lastNonZeroTempTarget.createdAt
  629. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  630. {
  631. currentPackage.append(target)
  632. }
  633. }
  634. }
  635. }
  636. // appends last package, if exists
  637. if !currentPackage.isEmpty {
  638. groupedPackages.append(currentPackage)
  639. }
  640. for package in groupedPackages {
  641. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  642. continue
  643. }
  644. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  645. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  646. if let earliestCancelTarget = earliestCancelTarget {
  647. end = min(earliestCancelTarget.createdAt, end)
  648. }
  649. let now = Date()
  650. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  651. if firstNonZeroTarget.targetTop != nil {
  652. calculatedTTs
  653. .append(ChartTempTarget(
  654. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  655. start: firstNonZeroTarget.createdAt,
  656. end: end
  657. ))
  658. }
  659. }
  660. chartTempTargets = calculatedTTs
  661. }
  662. private func findRegularBasalPoints(
  663. timeBegin: TimeInterval,
  664. timeEnd: TimeInterval,
  665. autotuned: Bool
  666. ) -> [BasalProfile] {
  667. guard timeBegin < timeEnd else {
  668. return []
  669. }
  670. let beginDate = Date(timeIntervalSince1970: timeBegin)
  671. let calendar = Calendar.current
  672. let startOfDay = calendar.startOfDay(for: beginDate)
  673. let profile = autotuned ? autotunedBasalProfile : basalProfile
  674. let basalNormalized = profile.map {
  675. (
  676. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  677. rate: $0.rate
  678. )
  679. } + profile.map {
  680. (
  681. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  682. .timeIntervalSince1970,
  683. rate: $0.rate
  684. )
  685. } + profile.map {
  686. (
  687. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  688. .timeIntervalSince1970,
  689. rate: $0.rate
  690. )
  691. }
  692. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  693. .compactMap { window -> BasalProfile? in
  694. let window = Array(window)
  695. if window[0].time < timeBegin, window[1].time < timeBegin {
  696. return nil
  697. }
  698. if window[0].time < timeBegin, window[1].time >= timeBegin {
  699. let startDate = Date(timeIntervalSince1970: timeBegin)
  700. let rate = window[0].rate
  701. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  702. }
  703. if window[0].time >= timeBegin, window[0].time < timeEnd {
  704. let startDate = Date(timeIntervalSince1970: window[0].time)
  705. let rate = window[0].rate
  706. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  707. }
  708. return nil
  709. }
  710. return basalTruncatedPoints
  711. }
  712. /// update start and end marker to fix scroll update problem with x axis
  713. private func updateStartEndMarkers() {
  714. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  715. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  716. }
  717. private func calculateBasals() {
  718. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  719. let regularPoints = findRegularBasalPoints(
  720. timeBegin: dayAgoTime,
  721. timeEnd: endMarker.timeIntervalSince1970,
  722. autotuned: false
  723. )
  724. let autotunedBasalPoints = findRegularBasalPoints(
  725. timeBegin: dayAgoTime,
  726. timeEnd: endMarker.timeIntervalSince1970,
  727. autotuned: true
  728. )
  729. var totalBasal = regularPoints + autotunedBasalPoints
  730. totalBasal.sort {
  731. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  732. }
  733. var basals: [BasalProfile] = []
  734. totalBasal.indices.forEach { index in
  735. basals.append(BasalProfile(
  736. amount: totalBasal[index].amount,
  737. isOverwritten: totalBasal[index].isOverwritten,
  738. startDate: totalBasal[index].startDate,
  739. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  740. ))
  741. }
  742. basalProfiles = basals
  743. }
  744. // MARK: - Chart formatting
  745. private func yAxisChartData() {
  746. let glucoseMapped = state.glucoseFromPersistence.map(\.glucose)
  747. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  748. // default values
  749. minValue = 45 * conversionFactor - 20 * conversionFactor
  750. maxValue = 270 * conversionFactor + 50 * conversionFactor
  751. return
  752. }
  753. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  754. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  755. debug(.default, "min \(minValue)")
  756. debug(.default, "max \(maxValue)")
  757. }
  758. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  759. plotContent
  760. .rotationEffect(.degrees(180))
  761. .scaleEffect(x: -1, y: 1)
  762. .chartXAxis(.hidden)
  763. }
  764. private var mainChartXAxis: some AxisContent {
  765. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  766. if displayXgridLines {
  767. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  768. } else {
  769. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  770. }
  771. }
  772. }
  773. private var basalChartXAxis: some AxisContent {
  774. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  775. if displayXgridLines {
  776. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  777. } else {
  778. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  779. }
  780. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  781. .font(.footnote)
  782. }
  783. }
  784. private var mainChartYAxis: some AxisContent {
  785. AxisMarks(position: .trailing) { value in
  786. if displayXgridLines {
  787. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  788. } else {
  789. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  790. }
  791. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  792. /// fix offset between the two charts...
  793. if units == .mmolL {
  794. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  795. }
  796. AxisValueLabel().font(.footnote)
  797. }
  798. }
  799. }
  800. }
  801. struct LegendItem: View {
  802. var color: Color
  803. var label: String
  804. var body: some View {
  805. Group {
  806. Circle().fill(color).frame(width: 8, height: 8)
  807. Text(label)
  808. .font(.system(size: 10, weight: .bold))
  809. .foregroundColor(color)
  810. }
  811. }
  812. }
  813. extension Int16 {
  814. var minutes: TimeInterval {
  815. TimeInterval(self) * 60
  816. }
  817. }