MainChartView.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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: MealsStored.fetch(NSPredicate.carbsForChart),
  79. animation: Animation.bouncy
  80. ) var carbsFromPersistence: FetchedResults<MealsStored>
  81. @FetchRequest(
  82. fetchRequest: MealsStored.fetch(NSPredicate.fpusForChart),
  83. animation: Animation.bouncy
  84. ) var fpusFromPersistence: FetchedResults<MealsStored>
  85. @FetchRequest(
  86. fetchRequest: InsulinStored.fetch(NSPredicate.insulinForChart),
  87. animation: Animation.bouncy
  88. ) var insulinFromPersistence: FetchedResults<InsulinStored>
  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. drawPredictions()
  205. drawGlucose()
  206. drawManualGlucose()
  207. /// high and low treshold 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: glucoseFromPersistence.map(\.id)) { _ in
  227. // calculatePredictions()
  228. }
  229. .onChange(of: boluses) { _ in
  230. state.roundedTotalBolus = state.calculateTINS()
  231. }
  232. .onChange(of: tempTargets) { _ in
  233. calculateTTs()
  234. }
  235. .onChange(of: didAppearTrigger) { _ in
  236. // calculatePredictions()
  237. calculateTTs()
  238. }
  239. .onChange(of: determinations.map(\.id)) { _ in
  240. // calculatePredictions()
  241. }
  242. .onReceive(
  243. Foundation.NotificationCenter.default
  244. .publisher(for: UIApplication.willEnterForegroundNotification)
  245. ) { _ in
  246. // calculatePredictions()
  247. }
  248. .frame(minHeight: UIScreen.main.bounds.height * 0.3)
  249. .frame(width: fullWidth(viewWidth: screenSize.width))
  250. .chartXScale(domain: startMarker ... endMarker)
  251. .chartXAxis { mainChartXAxis }
  252. // .chartXAxis(.hidden)
  253. .chartYAxis { mainChartYAxis }
  254. .chartYScale(domain: minValue ... maxValue)
  255. .backport.chartXSelection(value: $selection)
  256. }
  257. }
  258. @ViewBuilder var selectionPopover: some View {
  259. if let sgv = selectedGlucose?.glucose {
  260. let glucoseToShow = Decimal(sgv) * conversionFactor
  261. VStack {
  262. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  263. HStack {
  264. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  265. .fontWeight(.bold)
  266. .foregroundStyle(
  267. Decimal(sgv) < lowGlucose ? Color
  268. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  269. )
  270. Text(units.rawValue).foregroundColor(.secondary)
  271. }
  272. }
  273. .padding(6)
  274. .background {
  275. RoundedRectangle(cornerRadius: 4)
  276. .fill(Color.gray.opacity(0.1))
  277. .shadow(color: .blue, radius: 2)
  278. }
  279. }
  280. }
  281. private var basalChart: some View {
  282. VStack {
  283. Chart {
  284. drawStartRuleMark()
  285. drawEndRuleMark()
  286. drawCurrentTimeMarker()
  287. drawTempBasals()
  288. drawBasalProfile()
  289. drawSuspensions()
  290. }.onChange(of: tempBasals) { _ in
  291. calculateBasals()
  292. calculateTempBasals()
  293. }
  294. .onChange(of: maxBasal) { _ in
  295. calculateBasals()
  296. calculateTempBasals()
  297. }
  298. .onChange(of: autotunedBasalProfile) { _ in
  299. calculateBasals()
  300. calculateTempBasals()
  301. }
  302. .onChange(of: didAppearTrigger) { _ in
  303. calculateBasals()
  304. calculateTempBasals()
  305. }.onChange(of: basalProfile) { _ in
  306. calculateTempBasals()
  307. }
  308. .frame(maxHeight: UIScreen.main.bounds.height * 0.05)
  309. .frame(width: fullWidth(viewWidth: screenSize.width))
  310. .chartXScale(domain: startMarker ... endMarker)
  311. .chartXAxis { basalChartXAxis }
  312. .chartYAxis { basalChartYAxis }
  313. }
  314. }
  315. var legendPanel: some View {
  316. HStack(spacing: 10) {
  317. Spacer()
  318. LegendItem(color: .loopGreen, label: "BG")
  319. LegendItem(color: .insulin, label: "IOB")
  320. LegendItem(color: .zt, label: "ZT")
  321. LegendItem(color: .loopYellow, label: "COB")
  322. LegendItem(color: .uam, label: "UAM")
  323. Spacer()
  324. }
  325. .padding(.horizontal, 10)
  326. .frame(maxWidth: .infinity)
  327. }
  328. }
  329. // MARK: - Calculations
  330. extension MainChartView {
  331. private func drawBoluses() -> some ChartContent {
  332. /// smbs in triangle form
  333. ForEach(insulinFromPersistence) { bolus in
  334. let bolusAmount = bolus.amount ?? 0 as NSDecimalNumber
  335. let bolusDate = bolus.date ?? Date()
  336. let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)
  337. let yPosition = (Decimal(glucose.glucose) * conversionFactor) + bolusOffset
  338. let size = (Config.bolusSize + CGFloat(truncating: bolusAmount) * Config.bolusScale) * 1.8
  339. PointMark(
  340. x: .value("Time", bolus.date ?? Date(), unit: .second),
  341. y: .value("Value", yPosition)
  342. )
  343. .symbol {
  344. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  345. }
  346. .annotation(position: .top) {
  347. Text(bolusFormatter.string(from: bolusAmount) ?? "")
  348. .font(.caption2)
  349. .foregroundStyle(Color.insulin)
  350. }
  351. }
  352. }
  353. private func drawCarbs() -> some ChartContent {
  354. /// carbs
  355. ForEach(carbsFromPersistence) { carb in
  356. let carbAmount = carb.carbs
  357. let yPosition = units == .mgdL ? 60 : 3.33
  358. PointMark(
  359. x: .value("Time", carb.date ?? Date(), unit: .second),
  360. y: .value("Value", yPosition)
  361. )
  362. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  363. .foregroundStyle(Color.orange)
  364. .annotation(position: .bottom) {
  365. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  366. .foregroundStyle(Color.orange)
  367. }
  368. }
  369. }
  370. private func drawFpus() -> some ChartContent {
  371. /// fpus
  372. ForEach(fpusFromPersistence) { fpu in
  373. let fpuAmount = fpu.carbs
  374. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  375. let yPosition = units == .mgdL ? 60 : 3.33
  376. PointMark(
  377. x: .value("Time", fpu.date ?? Date(), unit: .second),
  378. y: .value("Value", yPosition)
  379. )
  380. .symbolSize(size)
  381. .foregroundStyle(Color.brown)
  382. }
  383. }
  384. private func drawGlucose() -> some ChartContent {
  385. /// glucose point mark
  386. /// filtering for high and low bounds in settings
  387. ForEach(glucoseFromPersistence) { item in
  388. if smooth {
  389. if item.glucose > Int(highGlucose) {
  390. PointMark(
  391. x: .value("Time", item.date ?? Date(), unit: .second),
  392. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  393. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  394. } else if item.glucose < Int(lowGlucose) {
  395. PointMark(
  396. x: .value("Time", item.date ?? Date(), unit: .second),
  397. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  398. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  399. } else {
  400. PointMark(
  401. x: .value("Time", item.date ?? Date(), unit: .second),
  402. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  403. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  404. }
  405. } else {
  406. if item.glucose > Int(highGlucose) {
  407. PointMark(
  408. x: .value("Time", item.date ?? Date(), unit: .second),
  409. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  410. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  411. } else if item.glucose < Int(lowGlucose) {
  412. PointMark(
  413. x: .value("Time", item.date ?? Date(), unit: .second),
  414. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  415. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  416. } else {
  417. PointMark(
  418. x: .value("Time", item.date ?? Date(), unit: .second),
  419. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  420. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  421. }
  422. }
  423. }
  424. }
  425. private func timeForIndex(_ index: Int32) -> Date {
  426. let currentTime = Date()
  427. let timeInterval = TimeInterval(index * 300)
  428. return currentTime.addingTimeInterval(timeInterval)
  429. }
  430. private func getForecasts(_ determination: OrefDetermination) -> [Forecast] {
  431. guard let forecastSet = determination.forecasts, let forecasts = Array(forecastSet) as? [Forecast] else {
  432. return []
  433. }
  434. return forecasts
  435. }
  436. private func getForecastValues(_ forecast: Forecast) -> [ForecastValue] {
  437. guard let forecastValueSet = forecast.forecastValues,
  438. let forecastValues = Array(forecastValueSet) as? [ForecastValue]
  439. else {
  440. return []
  441. }
  442. return forecastValues.sorted(by: { $0.index < $1.index })
  443. }
  444. private func drawPredictions() -> some ChartContent {
  445. ForEach(determinations) { determination in
  446. let forecasts = getForecasts(determination)
  447. ForEach(forecasts) { forecast in
  448. let forecastValues = getForecastValues(forecast)
  449. ForEach(forecastValues) { forecastValue in
  450. LineMark(
  451. x: .value("Time", timeForIndex(forecastValue.index)),
  452. y: .value("Value", Int(forecastValue.value))
  453. )
  454. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  455. }
  456. }
  457. }
  458. }
  459. private func colorForType(_ type: PredictionType) -> Color {
  460. switch type {
  461. case .uam:
  462. return .uam
  463. case .cob:
  464. return .orange
  465. case .iob:
  466. return .insulin
  467. case .zt:
  468. return .zt
  469. default:
  470. return .gray // Default color for unknown types
  471. }
  472. }
  473. private func drawCurrentTimeMarker() -> some ChartContent {
  474. RuleMark(
  475. x: .value(
  476. "",
  477. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  478. unit: .second
  479. )
  480. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  481. }
  482. private func drawStartRuleMark() -> some ChartContent {
  483. RuleMark(
  484. x: .value(
  485. "",
  486. startMarker,
  487. unit: .second
  488. )
  489. ).foregroundStyle(Color.clear)
  490. }
  491. private func drawEndRuleMark() -> some ChartContent {
  492. RuleMark(
  493. x: .value(
  494. "",
  495. endMarker,
  496. unit: .second
  497. )
  498. ).foregroundStyle(Color.clear)
  499. }
  500. private func drawTempTargets() -> some ChartContent {
  501. /// temp targets
  502. ForEach(ChartTempTargets, id: \.self) { target in
  503. let targetLimited = min(max(target.amount, 0), upperLimit)
  504. RuleMark(
  505. xStart: .value("Start", target.start),
  506. xEnd: .value("End", target.end),
  507. y: .value("Value", targetLimited)
  508. )
  509. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  510. }
  511. }
  512. private func drawManualGlucose() -> some ChartContent {
  513. /// manual glucose mark
  514. ForEach(manualGlucoseFromPersistence) { item in
  515. let manualGlucose = item.glucose
  516. PointMark(
  517. x: .value("Time", item.date ?? Date(), unit: .second),
  518. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  519. )
  520. .symbol {
  521. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  522. .foregroundStyle(.red)
  523. }
  524. }
  525. }
  526. private func drawSuspensions() -> some ChartContent {
  527. /// pump suspensions
  528. ForEach(suspensions) { suspension in
  529. let now = Date()
  530. if suspension.type == EventType.pumpSuspend {
  531. let suspensionStart = suspension.timestamp
  532. let suspensionEnd = min(
  533. suspensions
  534. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  535. .timestamp ?? now,
  536. now
  537. )
  538. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  539. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  540. RectangleMark(
  541. xStart: .value("start", suspensionStart),
  542. xEnd: .value("end", suspensionEnd),
  543. yStart: .value("suspend-start", 0),
  544. yEnd: .value("suspend-end", suspensionMarkHeight)
  545. )
  546. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  547. }
  548. }
  549. }
  550. private func drawTempBasals() -> some ChartContent {
  551. /// temp basal rects
  552. ForEach(TempBasals) { temp in
  553. /// calculate end time of temp basal adding duration to start time
  554. let end = temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval
  555. let now = Date()
  556. /// ensure that temp basals that are set cannot exceed current date -> i.e. scheduled temp basals are not shown
  557. /// we could display scheduled temp basals with opacity etc... in the future
  558. let maxEndTime = min(end, now)
  559. /// set mark height to 0 when insulin delivery is suspended
  560. let isInsulinSuspended = suspensions
  561. .first(where: { $0.timestamp >= temp.timestamp && $0.timestamp <= maxEndTime }) != nil
  562. let rate = (temp.rate ?? 0) * (isInsulinSuspended ? 0 : 1)
  563. /// find next basal entry and if available set end of current entry to start of next entry
  564. if let nextTemp = TempBasals.first(where: { $0.timestamp > temp.timestamp }) {
  565. let nextTempStart = nextTemp.timestamp
  566. RectangleMark(
  567. xStart: .value("start", temp.timestamp),
  568. xEnd: .value("end", nextTempStart),
  569. yStart: .value("rate-start", 0),
  570. yEnd: .value("rate-end", rate)
  571. ).foregroundStyle(Color.insulin.opacity(0.2))
  572. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  573. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  574. LineMark(x: .value("End Date", nextTempStart), y: .value("Amount", rate))
  575. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  576. } else {
  577. RectangleMark(
  578. xStart: .value("start", temp.timestamp),
  579. xEnd: .value("end", maxEndTime),
  580. yStart: .value("rate-start", 0),
  581. yEnd: .value("rate-end", rate)
  582. ).foregroundStyle(Color.insulin.opacity(0.2))
  583. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  584. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  585. LineMark(x: .value("End Date", maxEndTime), y: .value("Amount", rate))
  586. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  587. }
  588. }
  589. }
  590. private func drawBasalProfile() -> some ChartContent {
  591. /// dashed profile line
  592. ForEach(BasalProfiles, id: \.self) { profile in
  593. LineMark(
  594. x: .value("Start Date", profile.startDate),
  595. y: .value("Amount", profile.amount),
  596. series: .value("profile", "profile")
  597. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  598. LineMark(
  599. x: .value("End Date", profile.endDate ?? endMarker),
  600. y: .value("Amount", profile.amount),
  601. series: .value("profile", "profile")
  602. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  603. }
  604. }
  605. /// calculates the glucose value thats the nearest to parameter 'time'
  606. /// if time is later than all the arrays values return the last element of BloodGlucose
  607. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored {
  608. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  609. guard let lastGlucose = glucoseFromPersistence.last else {
  610. return GlucoseStored()
  611. }
  612. /// If the last glucose entry is before the specified time, return the last entry
  613. if lastGlucose.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  614. return lastGlucose
  615. }
  616. /// Find the index of the first element in the array whose date is greater than the specified time
  617. if let nextIndex = glucoseFromPersistence
  618. .firstIndex(where: { $0.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 > time })
  619. {
  620. return glucoseFromPersistence[nextIndex]
  621. } else {
  622. /// If no such element is found, return the last element in the array
  623. return lastGlucose
  624. }
  625. }
  626. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  627. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  628. }
  629. /// calculations for temp target bar mark
  630. private func calculateTTs() {
  631. var groupedPackages: [[TempTarget]] = []
  632. var currentPackage: [TempTarget] = []
  633. var calculatedTTs: [ChartTempTarget] = []
  634. for target in tempTargets {
  635. if target.duration > 0 {
  636. if !currentPackage.isEmpty {
  637. groupedPackages.append(currentPackage)
  638. currentPackage = []
  639. }
  640. currentPackage.append(target)
  641. } else {
  642. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  643. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  644. target.createdAt <= lastNonZeroTempTarget.createdAt
  645. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  646. {
  647. currentPackage.append(target)
  648. }
  649. }
  650. }
  651. }
  652. // appends last package, if exists
  653. if !currentPackage.isEmpty {
  654. groupedPackages.append(currentPackage)
  655. }
  656. for package in groupedPackages {
  657. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  658. continue
  659. }
  660. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  661. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  662. if let earliestCancelTarget = earliestCancelTarget {
  663. end = min(earliestCancelTarget.createdAt, end)
  664. }
  665. let now = Date()
  666. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  667. if firstNonZeroTarget.targetTop != nil {
  668. calculatedTTs
  669. .append(ChartTempTarget(
  670. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  671. start: firstNonZeroTarget.createdAt,
  672. end: end
  673. ))
  674. }
  675. }
  676. ChartTempTargets = calculatedTTs
  677. }
  678. private func calculateTempBasals() {
  679. let basals = tempBasals
  680. var returnTempBasalRates: [PumpHistoryEvent] = []
  681. var finished: [Int: Bool] = [:]
  682. basals.indices.forEach { i in
  683. basals.indices.forEach { j in
  684. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  685. let rate = basals[i].rate ?? basals[j].rate
  686. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  687. finished[i] = true
  688. if rate != 0 || durationMin != 0 {
  689. returnTempBasalRates.append(
  690. PumpHistoryEvent(
  691. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  692. timestamp: basals[i].timestamp,
  693. durationMin: durationMin,
  694. rate: rate
  695. )
  696. )
  697. }
  698. }
  699. }
  700. }
  701. TempBasals = returnTempBasalRates
  702. }
  703. // private func addPredictions(_ predictions: [Int], type: PredictionType, deliveredAt: Date, endMarker: Date) -> [Prediction] {
  704. // var calculatedPredictions: [Prediction] = []
  705. // predictions.indices.forEach { index in
  706. // let predTime = Date(
  707. // timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  708. // )
  709. // if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  710. // calculatedPredictions.append(
  711. // Prediction(amount: predictions[index], timestamp: predTime, type: type)
  712. // )
  713. // }
  714. // }
  715. // return calculatedPredictions
  716. // }
  717. private func findRegularBasalPoints(
  718. timeBegin: TimeInterval,
  719. timeEnd: TimeInterval,
  720. autotuned: Bool
  721. ) -> [BasalProfile] {
  722. guard timeBegin < timeEnd else {
  723. return []
  724. }
  725. let beginDate = Date(timeIntervalSince1970: timeBegin)
  726. let calendar = Calendar.current
  727. let startOfDay = calendar.startOfDay(for: beginDate)
  728. let profile = autotuned ? autotunedBasalProfile : basalProfile
  729. let basalNormalized = profile.map {
  730. (
  731. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  732. rate: $0.rate
  733. )
  734. } + profile.map {
  735. (
  736. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  737. .timeIntervalSince1970,
  738. rate: $0.rate
  739. )
  740. } + profile.map {
  741. (
  742. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  743. .timeIntervalSince1970,
  744. rate: $0.rate
  745. )
  746. }
  747. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  748. .compactMap { window -> BasalProfile? in
  749. let window = Array(window)
  750. if window[0].time < timeBegin, window[1].time < timeBegin {
  751. return nil
  752. }
  753. if window[0].time < timeBegin, window[1].time >= timeBegin {
  754. let startDate = Date(timeIntervalSince1970: timeBegin)
  755. let rate = window[0].rate
  756. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  757. }
  758. if window[0].time >= timeBegin, window[0].time < timeEnd {
  759. let startDate = Date(timeIntervalSince1970: window[0].time)
  760. let rate = window[0].rate
  761. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  762. }
  763. return nil
  764. }
  765. return basalTruncatedPoints
  766. }
  767. /// update start and end marker to fix scroll update problem with x axis
  768. private func updateStartEndMarkers() {
  769. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  770. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  771. }
  772. private func calculateBasals() {
  773. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  774. let regularPoints = findRegularBasalPoints(
  775. timeBegin: dayAgoTime,
  776. timeEnd: endMarker.timeIntervalSince1970,
  777. autotuned: false
  778. )
  779. let autotunedBasalPoints = findRegularBasalPoints(
  780. timeBegin: dayAgoTime,
  781. timeEnd: endMarker.timeIntervalSince1970,
  782. autotuned: true
  783. )
  784. var totalBasal = regularPoints + autotunedBasalPoints
  785. totalBasal.sort {
  786. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  787. }
  788. var basals: [BasalProfile] = []
  789. totalBasal.indices.forEach { index in
  790. basals.append(BasalProfile(
  791. amount: totalBasal[index].amount,
  792. isOverwritten: totalBasal[index].isOverwritten,
  793. startDate: totalBasal[index].startDate,
  794. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  795. ))
  796. print(
  797. "Basal",
  798. totalBasal[index].startDate,
  799. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  800. totalBasal[index].amount,
  801. totalBasal[index].isOverwritten
  802. )
  803. }
  804. BasalProfiles = basals
  805. }
  806. // MARK: - Chart formatting
  807. private func yAxisChartData() {
  808. let glucoseMapped = glucoseFromPersistence.map(\.glucose)
  809. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  810. // default values
  811. minValue = 45 * conversionFactor - 20 * conversionFactor
  812. maxValue = 270 * conversionFactor + 50 * conversionFactor
  813. return
  814. }
  815. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  816. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  817. debug(.default, "min \(minValue)")
  818. debug(.default, "max \(maxValue)")
  819. }
  820. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  821. plotContent
  822. .rotationEffect(.degrees(180))
  823. .scaleEffect(x: -1, y: 1)
  824. .chartXAxis(.hidden)
  825. }
  826. private var mainChartXAxis: some AxisContent {
  827. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  828. if displayXgridLines {
  829. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  830. } else {
  831. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  832. }
  833. }
  834. }
  835. private var basalChartXAxis: some AxisContent {
  836. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  837. if displayXgridLines {
  838. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  839. } else {
  840. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  841. }
  842. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  843. .font(.footnote)
  844. }
  845. }
  846. private var mainChartYAxis: some AxisContent {
  847. AxisMarks(position: .trailing) { value in
  848. if displayXgridLines {
  849. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  850. } else {
  851. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  852. }
  853. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  854. /// fix offset between the two charts...
  855. if units == .mmolL {
  856. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  857. }
  858. AxisValueLabel().font(.footnote)
  859. }
  860. }
  861. }
  862. private var basalChartYAxis: some AxisContent {
  863. AxisMarks(position: .trailing) { _ in
  864. AxisTick(length: units == .mmolL ? 25 : 27, stroke: .init(lineWidth: 4))
  865. .foregroundStyle(Color.clear).font(.footnote)
  866. }
  867. }
  868. }
  869. struct LegendItem: View {
  870. var color: Color
  871. var label: String
  872. var body: some View {
  873. Group {
  874. Circle().fill(color).frame(width: 8, height: 8)
  875. Text(label)
  876. .font(.system(size: 10, weight: .bold))
  877. .foregroundColor(color)
  878. }
  879. }
  880. }