MainChartView.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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: 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. 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) { bolus in
  327. let bolusAmount = bolus.amount ?? 0 as NSDecimalNumber
  328. let bolusDate = bolus.date ?? Date()
  329. let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)
  330. let yPosition = (Decimal(glucose.glucose) * conversionFactor) + bolusOffset
  331. let size = (Config.bolusSize + CGFloat(truncating: bolusAmount) * Config.bolusScale) * 1.8
  332. PointMark(
  333. x: .value("Time", bolus.date ?? Date(), unit: .second),
  334. y: .value("Value", yPosition)
  335. )
  336. .symbol {
  337. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  338. }
  339. .annotation(position: .top) {
  340. Text(bolusFormatter.string(from: bolusAmount) ?? "")
  341. .font(.caption2)
  342. .foregroundStyle(Color.insulin)
  343. }
  344. }
  345. }
  346. private func drawCarbs() -> some ChartContent {
  347. /// carbs
  348. ForEach(carbsFromPersistence) { carb in
  349. let carbAmount = carb.carbs
  350. let yPosition = units == .mgdL ? 60 : 3.33
  351. PointMark(
  352. x: .value("Time", carb.date ?? Date(), unit: .second),
  353. y: .value("Value", yPosition)
  354. )
  355. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  356. .foregroundStyle(Color.orange)
  357. .annotation(position: .bottom) {
  358. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  359. .foregroundStyle(Color.orange)
  360. }
  361. }
  362. }
  363. private func drawFpus() -> some ChartContent {
  364. /// fpus
  365. ForEach(fpusFromPersistence) { fpu in
  366. let fpuAmount = fpu.carbs
  367. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  368. let yPosition = units == .mgdL ? 60 : 3.33
  369. PointMark(
  370. x: .value("Time", fpu.date ?? Date(), unit: .second),
  371. y: .value("Value", yPosition)
  372. )
  373. .symbolSize(size)
  374. .foregroundStyle(Color.brown)
  375. }
  376. }
  377. private func drawGlucose() -> some ChartContent {
  378. /// glucose point mark
  379. /// filtering for high and low bounds in settings
  380. ForEach(glucoseFromPersistence) { item in
  381. if smooth {
  382. if item.glucose > Int(highGlucose) {
  383. PointMark(
  384. x: .value("Time", item.date ?? Date(), unit: .second),
  385. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  386. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  387. } else if item.glucose < Int(lowGlucose) {
  388. PointMark(
  389. x: .value("Time", item.date ?? Date(), unit: .second),
  390. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  391. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  392. } else {
  393. PointMark(
  394. x: .value("Time", item.date ?? Date(), unit: .second),
  395. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  396. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  397. }
  398. } else {
  399. if item.glucose > Int(highGlucose) {
  400. PointMark(
  401. x: .value("Time", item.date ?? Date(), unit: .second),
  402. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  403. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  404. } else if item.glucose < Int(lowGlucose) {
  405. PointMark(
  406. x: .value("Time", item.date ?? Date(), unit: .second),
  407. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  408. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  409. } else {
  410. PointMark(
  411. x: .value("Time", item.date ?? Date(), unit: .second),
  412. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  413. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  414. }
  415. }
  416. }
  417. }
  418. private func timeForIndex(_ index: Int32) -> Date {
  419. let currentTime = Date()
  420. let timeInterval = TimeInterval(index * 300)
  421. return currentTime.addingTimeInterval(timeInterval)
  422. }
  423. private func getForecasts(_ determination: OrefDetermination) -> [Forecast] {
  424. guard let forecastSet = determination.forecasts, let forecasts = Array(forecastSet) as? [Forecast] else {
  425. return []
  426. }
  427. return forecasts
  428. }
  429. private func getForecastValues(_ forecast: Forecast) -> [ForecastValue] {
  430. guard let forecastValueSet = forecast.forecastValues,
  431. let forecastValues = Array(forecastValueSet) as? [ForecastValue]
  432. else {
  433. return []
  434. }
  435. return forecastValues.sorted(by: { $0.index < $1.index })
  436. }
  437. private func drawForecasts() -> some ChartContent {
  438. /// for every determination in determinations get the forecasts
  439. ForEach(determinations.flatMap { determination -> [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] in
  440. let forecasts = getForecasts(determination) /// returns array of Forecast objects
  441. /// now get the values for every forecast and add it to a tuple, identify it with an ID
  442. return forecasts.flatMap { forecast in
  443. getForecastValues(forecast).map { forecastValue in
  444. (id: UUID(), forecast: forecast, forecastValue: forecastValue)
  445. }
  446. }
  447. }, id: \.id) { tuple in
  448. LineMark(
  449. x: .value("Time", timeForIndex(tuple.forecastValue.index)),
  450. y: .value("Value", Int(tuple.forecastValue.value))
  451. )
  452. .foregroundStyle(by: .value("Predictions", tuple.forecast.type ?? ""))
  453. }
  454. }
  455. private func drawCurrentTimeMarker() -> some ChartContent {
  456. RuleMark(
  457. x: .value(
  458. "",
  459. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  460. unit: .second
  461. )
  462. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  463. }
  464. private func drawStartRuleMark() -> some ChartContent {
  465. RuleMark(
  466. x: .value(
  467. "",
  468. startMarker,
  469. unit: .second
  470. )
  471. ).foregroundStyle(Color.clear)
  472. }
  473. private func drawEndRuleMark() -> some ChartContent {
  474. RuleMark(
  475. x: .value(
  476. "",
  477. endMarker,
  478. unit: .second
  479. )
  480. ).foregroundStyle(Color.clear)
  481. }
  482. private func drawTempTargets() -> some ChartContent {
  483. /// temp targets
  484. ForEach(ChartTempTargets, id: \.self) { target in
  485. let targetLimited = min(max(target.amount, 0), upperLimit)
  486. RuleMark(
  487. xStart: .value("Start", target.start),
  488. xEnd: .value("End", target.end),
  489. y: .value("Value", targetLimited)
  490. )
  491. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  492. }
  493. }
  494. private func drawManualGlucose() -> some ChartContent {
  495. /// manual glucose mark
  496. ForEach(manualGlucoseFromPersistence) { item in
  497. let manualGlucose = item.glucose
  498. PointMark(
  499. x: .value("Time", item.date ?? Date(), unit: .second),
  500. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  501. )
  502. .symbol {
  503. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  504. .foregroundStyle(.red)
  505. }
  506. }
  507. }
  508. private func drawSuspensions() -> some ChartContent {
  509. /// pump suspensions
  510. ForEach(suspensions) { suspension in
  511. let now = Date()
  512. if suspension.type == EventType.pumpSuspend {
  513. let suspensionStart = suspension.timestamp
  514. let suspensionEnd = min(
  515. suspensions
  516. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  517. .timestamp ?? now,
  518. now
  519. )
  520. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  521. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  522. RectangleMark(
  523. xStart: .value("start", suspensionStart),
  524. xEnd: .value("end", suspensionEnd),
  525. yStart: .value("suspend-start", 0),
  526. yEnd: .value("suspend-end", suspensionMarkHeight)
  527. )
  528. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  529. }
  530. }
  531. }
  532. private func filteredTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  533. let now = Date()
  534. return TempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  535. let end = min(temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval, now)
  536. let isInsulinSuspended = suspensions.contains { $0.timestamp >= temp.timestamp && $0.timestamp <= end }
  537. let rate = Double(temp.rate ?? Decimal.zero) * (isInsulinSuspended ? 0 : 1)
  538. // Check if there's a subsequent temp basal to determine the end time
  539. guard let nextTemp = TempBasals.first(where: { $0.timestamp > temp.timestamp }) else {
  540. return (temp.timestamp, end, rate)
  541. }
  542. return (temp.timestamp, nextTemp.timestamp, rate)
  543. }
  544. }
  545. private func drawTempBasals() -> some ChartContent {
  546. ForEach(filteredTempBasals(), id: \.rate) { basal in
  547. RectangleMark(
  548. xStart: .value("start", basal.start),
  549. xEnd: .value("end", basal.end),
  550. yStart: .value("rate-start", 0),
  551. yEnd: .value("rate-end", basal.rate)
  552. ).foregroundStyle(Color.insulin.opacity(0.2))
  553. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  554. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  555. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  556. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  557. }
  558. }
  559. private func drawBasalProfile() -> some ChartContent {
  560. /// dashed profile line
  561. ForEach(BasalProfiles, id: \.self) { profile in
  562. LineMark(
  563. x: .value("Start Date", profile.startDate),
  564. y: .value("Amount", profile.amount),
  565. series: .value("profile", "profile")
  566. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  567. LineMark(
  568. x: .value("End Date", profile.endDate ?? endMarker),
  569. y: .value("Amount", profile.amount),
  570. series: .value("profile", "profile")
  571. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  572. }
  573. }
  574. /// calculates the glucose value thats the nearest to parameter 'time'
  575. /// if time is later than all the arrays values return the last element of BloodGlucose
  576. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored {
  577. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  578. guard let lastGlucose = glucoseFromPersistence.last else {
  579. return GlucoseStored()
  580. }
  581. /// If the last glucose entry is before the specified time, return the last entry
  582. if lastGlucose.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  583. return lastGlucose
  584. }
  585. /// Find the index of the first element in the array whose date is greater than the specified time
  586. if let nextIndex = glucoseFromPersistence
  587. .firstIndex(where: { $0.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 > time })
  588. {
  589. return glucoseFromPersistence[nextIndex]
  590. } else {
  591. /// If no such element is found, return the last element in the array
  592. return lastGlucose
  593. }
  594. }
  595. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  596. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  597. }
  598. /// calculations for temp target bar mark
  599. private func calculateTTs() {
  600. var groupedPackages: [[TempTarget]] = []
  601. var currentPackage: [TempTarget] = []
  602. var calculatedTTs: [ChartTempTarget] = []
  603. for target in tempTargets {
  604. if target.duration > 0 {
  605. if !currentPackage.isEmpty {
  606. groupedPackages.append(currentPackage)
  607. currentPackage = []
  608. }
  609. currentPackage.append(target)
  610. } else {
  611. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  612. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  613. target.createdAt <= lastNonZeroTempTarget.createdAt
  614. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  615. {
  616. currentPackage.append(target)
  617. }
  618. }
  619. }
  620. }
  621. // appends last package, if exists
  622. if !currentPackage.isEmpty {
  623. groupedPackages.append(currentPackage)
  624. }
  625. for package in groupedPackages {
  626. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  627. continue
  628. }
  629. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  630. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  631. if let earliestCancelTarget = earliestCancelTarget {
  632. end = min(earliestCancelTarget.createdAt, end)
  633. }
  634. let now = Date()
  635. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  636. if firstNonZeroTarget.targetTop != nil {
  637. calculatedTTs
  638. .append(ChartTempTarget(
  639. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  640. start: firstNonZeroTarget.createdAt,
  641. end: end
  642. ))
  643. }
  644. }
  645. ChartTempTargets = calculatedTTs
  646. }
  647. private func calculateTempBasals() {
  648. let basals = tempBasals
  649. var returnTempBasalRates: [PumpHistoryEvent] = []
  650. var finished: [Int: Bool] = [:]
  651. basals.indices.forEach { i in
  652. basals.indices.forEach { j in
  653. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  654. let rate = basals[i].rate ?? basals[j].rate
  655. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  656. finished[i] = true
  657. if rate != 0 || durationMin != 0 {
  658. returnTempBasalRates.append(
  659. PumpHistoryEvent(
  660. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  661. timestamp: basals[i].timestamp,
  662. durationMin: durationMin,
  663. rate: rate
  664. )
  665. )
  666. }
  667. }
  668. }
  669. }
  670. TempBasals = returnTempBasalRates
  671. }
  672. private func findRegularBasalPoints(
  673. timeBegin: TimeInterval,
  674. timeEnd: TimeInterval,
  675. autotuned: Bool
  676. ) -> [BasalProfile] {
  677. guard timeBegin < timeEnd else {
  678. return []
  679. }
  680. let beginDate = Date(timeIntervalSince1970: timeBegin)
  681. let calendar = Calendar.current
  682. let startOfDay = calendar.startOfDay(for: beginDate)
  683. let profile = autotuned ? autotunedBasalProfile : basalProfile
  684. let basalNormalized = profile.map {
  685. (
  686. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  687. rate: $0.rate
  688. )
  689. } + profile.map {
  690. (
  691. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  692. .timeIntervalSince1970,
  693. rate: $0.rate
  694. )
  695. } + profile.map {
  696. (
  697. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  698. .timeIntervalSince1970,
  699. rate: $0.rate
  700. )
  701. }
  702. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  703. .compactMap { window -> BasalProfile? in
  704. let window = Array(window)
  705. if window[0].time < timeBegin, window[1].time < timeBegin {
  706. return nil
  707. }
  708. if window[0].time < timeBegin, window[1].time >= timeBegin {
  709. let startDate = Date(timeIntervalSince1970: timeBegin)
  710. let rate = window[0].rate
  711. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  712. }
  713. if window[0].time >= timeBegin, window[0].time < timeEnd {
  714. let startDate = Date(timeIntervalSince1970: window[0].time)
  715. let rate = window[0].rate
  716. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  717. }
  718. return nil
  719. }
  720. return basalTruncatedPoints
  721. }
  722. /// update start and end marker to fix scroll update problem with x axis
  723. private func updateStartEndMarkers() {
  724. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  725. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  726. }
  727. private func calculateBasals() {
  728. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  729. let regularPoints = findRegularBasalPoints(
  730. timeBegin: dayAgoTime,
  731. timeEnd: endMarker.timeIntervalSince1970,
  732. autotuned: false
  733. )
  734. let autotunedBasalPoints = findRegularBasalPoints(
  735. timeBegin: dayAgoTime,
  736. timeEnd: endMarker.timeIntervalSince1970,
  737. autotuned: true
  738. )
  739. var totalBasal = regularPoints + autotunedBasalPoints
  740. totalBasal.sort {
  741. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  742. }
  743. var basals: [BasalProfile] = []
  744. totalBasal.indices.forEach { index in
  745. basals.append(BasalProfile(
  746. amount: totalBasal[index].amount,
  747. isOverwritten: totalBasal[index].isOverwritten,
  748. startDate: totalBasal[index].startDate,
  749. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  750. ))
  751. print(
  752. "Basal",
  753. totalBasal[index].startDate,
  754. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  755. totalBasal[index].amount,
  756. totalBasal[index].isOverwritten
  757. )
  758. }
  759. BasalProfiles = basals
  760. }
  761. // MARK: - Chart formatting
  762. private func yAxisChartData() {
  763. let glucoseMapped = glucoseFromPersistence.map(\.glucose)
  764. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  765. // default values
  766. minValue = 45 * conversionFactor - 20 * conversionFactor
  767. maxValue = 270 * conversionFactor + 50 * conversionFactor
  768. return
  769. }
  770. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  771. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  772. debug(.default, "min \(minValue)")
  773. debug(.default, "max \(maxValue)")
  774. }
  775. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  776. plotContent
  777. .rotationEffect(.degrees(180))
  778. .scaleEffect(x: -1, y: 1)
  779. .chartXAxis(.hidden)
  780. }
  781. private var mainChartXAxis: some AxisContent {
  782. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  783. if displayXgridLines {
  784. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  785. } else {
  786. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  787. }
  788. }
  789. }
  790. private var basalChartXAxis: 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. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  798. .font(.footnote)
  799. }
  800. }
  801. private var mainChartYAxis: some AxisContent {
  802. AxisMarks(position: .trailing) { value in
  803. if displayXgridLines {
  804. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  805. } else {
  806. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  807. }
  808. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  809. /// fix offset between the two charts...
  810. if units == .mmolL {
  811. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  812. }
  813. AxisValueLabel().font(.footnote)
  814. }
  815. }
  816. }
  817. private var basalChartYAxis: some AxisContent {
  818. AxisMarks(position: .trailing) { _ in
  819. AxisTick(length: units == .mmolL ? 25 : 27, stroke: .init(lineWidth: 4))
  820. .foregroundStyle(Color.clear).font(.footnote)
  821. }
  822. }
  823. }
  824. struct LegendItem: View {
  825. var color: Color
  826. var label: String
  827. var body: some View {
  828. Group {
  829. Circle().fill(color).frame(width: 8, height: 8)
  830. Text(label)
  831. .font(.system(size: 10, weight: .bold))
  832. .foregroundColor(color)
  833. }
  834. }
  835. }