MainChartView.swift 35 KB

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