MainChartView.swift 37 KB

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