MainChartView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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.forecastsForChart, sortedBy: "date", ascending: true),
  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 drawPredictions() -> some View {
  425. ForEach(forecasts, id: \.self) { forecast in
  426. ForEach(forecast.forecastValuesArray) { value in
  427. LineMark(
  428. x: .value("Time", value.timestamp),
  429. y: .value("Value", Decimal(value.value) * conversionFactor)
  430. // series: .value("Series", forecast.type)
  431. )
  432. // .foregroundStyle(colorForType(PredictionType(rawValue: forecast.type ?? "") ?? .unknown))
  433. }
  434. }
  435. }
  436. private func colorForType(_ type: PredictionType) -> Color {
  437. switch type {
  438. case .uam:
  439. return .uam
  440. case .cob:
  441. return .orange
  442. case .iob:
  443. return .insulin
  444. case .zt:
  445. return .zt
  446. default:
  447. return .gray // Default color for unknown types
  448. }
  449. }
  450. private func drawCurrentTimeMarker() -> some ChartContent {
  451. RuleMark(
  452. x: .value(
  453. "",
  454. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  455. unit: .second
  456. )
  457. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  458. }
  459. private func drawStartRuleMark() -> some ChartContent {
  460. RuleMark(
  461. x: .value(
  462. "",
  463. startMarker,
  464. unit: .second
  465. )
  466. ).foregroundStyle(Color.clear)
  467. }
  468. private func drawEndRuleMark() -> some ChartContent {
  469. RuleMark(
  470. x: .value(
  471. "",
  472. endMarker,
  473. unit: .second
  474. )
  475. ).foregroundStyle(Color.clear)
  476. }
  477. private func drawTempTargets() -> some ChartContent {
  478. /// temp targets
  479. ForEach(ChartTempTargets, id: \.self) { target in
  480. let targetLimited = min(max(target.amount, 0), upperLimit)
  481. RuleMark(
  482. xStart: .value("Start", target.start),
  483. xEnd: .value("End", target.end),
  484. y: .value("Value", targetLimited)
  485. )
  486. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  487. }
  488. }
  489. private func drawManualGlucose() -> some ChartContent {
  490. /// manual glucose mark
  491. ForEach(manualGlucose) { item in
  492. if let manualGlucose = item.glucose {
  493. PointMark(
  494. x: .value("Time", item.dateString, unit: .second),
  495. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  496. )
  497. .symbol {
  498. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  499. .foregroundStyle(.red)
  500. }
  501. }
  502. }
  503. }
  504. private func drawSuspensions() -> some ChartContent {
  505. /// pump suspensions
  506. ForEach(suspensions) { suspension in
  507. let now = Date()
  508. if suspension.type == EventType.pumpSuspend {
  509. let suspensionStart = suspension.timestamp
  510. let suspensionEnd = min(
  511. suspensions
  512. .first(where: { $0.timestamp > suspension.timestamp && $0.type == EventType.pumpResume })?
  513. .timestamp ?? now,
  514. now
  515. )
  516. let basalProfileDuringSuspension = BasalProfiles.first(where: { $0.startDate <= suspensionStart })
  517. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  518. RectangleMark(
  519. xStart: .value("start", suspensionStart),
  520. xEnd: .value("end", suspensionEnd),
  521. yStart: .value("suspend-start", 0),
  522. yEnd: .value("suspend-end", suspensionMarkHeight)
  523. )
  524. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  525. }
  526. }
  527. }
  528. private func drawTempBasals() -> some ChartContent {
  529. /// temp basal rects
  530. ForEach(TempBasals) { temp in
  531. /// calculate end time of temp basal adding duration to start time
  532. let end = temp.timestamp + (temp.durationMin ?? 0).minutes.timeInterval
  533. let now = Date()
  534. /// ensure that temp basals that are set cannot exceed current date -> i.e. scheduled temp basals are not shown
  535. /// we could display scheduled temp basals with opacity etc... in the future
  536. let maxEndTime = min(end, now)
  537. /// set mark height to 0 when insulin delivery is suspended
  538. let isInsulinSuspended = suspensions
  539. .first(where: { $0.timestamp >= temp.timestamp && $0.timestamp <= maxEndTime }) != nil
  540. let rate = (temp.rate ?? 0) * (isInsulinSuspended ? 0 : 1)
  541. /// find next basal entry and if available set end of current entry to start of next entry
  542. if let nextTemp = TempBasals.first(where: { $0.timestamp > temp.timestamp }) {
  543. let nextTempStart = nextTemp.timestamp
  544. RectangleMark(
  545. xStart: .value("start", temp.timestamp),
  546. xEnd: .value("end", nextTempStart),
  547. yStart: .value("rate-start", 0),
  548. yEnd: .value("rate-end", rate)
  549. ).foregroundStyle(Color.insulin.opacity(0.2))
  550. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  551. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  552. LineMark(x: .value("End Date", nextTempStart), y: .value("Amount", rate))
  553. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  554. } else {
  555. RectangleMark(
  556. xStart: .value("start", temp.timestamp),
  557. xEnd: .value("end", maxEndTime),
  558. yStart: .value("rate-start", 0),
  559. yEnd: .value("rate-end", rate)
  560. ).foregroundStyle(Color.insulin.opacity(0.2))
  561. LineMark(x: .value("Start Date", temp.timestamp), y: .value("Amount", rate))
  562. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  563. LineMark(x: .value("End Date", maxEndTime), y: .value("Amount", rate))
  564. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  565. }
  566. }
  567. }
  568. private func drawBasalProfile() -> some ChartContent {
  569. /// dashed profile line
  570. ForEach(BasalProfiles, id: \.self) { profile in
  571. LineMark(
  572. x: .value("Start Date", profile.startDate),
  573. y: .value("Amount", profile.amount),
  574. series: .value("profile", "profile")
  575. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  576. LineMark(
  577. x: .value("End Date", profile.endDate ?? endMarker),
  578. y: .value("Amount", profile.amount),
  579. series: .value("profile", "profile")
  580. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  581. }
  582. }
  583. /// calculates the glucose value thats the nearest to parameter 'time'
  584. /// if time is later than all the arrays values return the last element of BloodGlucose
  585. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  586. /// If the glucose array is empty, return a default BloodGlucose object or handle it accordingly
  587. guard let lastGlucose = glucose.last else {
  588. return BloodGlucose(
  589. date: 0,
  590. dateString: Date(),
  591. unfiltered: nil,
  592. filtered: nil,
  593. noise: nil,
  594. type: nil
  595. )
  596. }
  597. /// If the last glucose entry is before the specified time, return the last entry
  598. if lastGlucose.dateString.timeIntervalSince1970 < time {
  599. return lastGlucose
  600. }
  601. /// Find the index of the first element in the array whose date is greater than the specified time
  602. if let nextIndex = glucose.firstIndex(where: { $0.dateString.timeIntervalSince1970 > time }) {
  603. return glucose[nextIndex]
  604. } else {
  605. /// If no such element is found, return the last element in the array
  606. return lastGlucose
  607. }
  608. }
  609. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  610. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  611. }
  612. /// calculations for temp target bar mark
  613. private func calculateTTs() {
  614. var groupedPackages: [[TempTarget]] = []
  615. var currentPackage: [TempTarget] = []
  616. var calculatedTTs: [ChartTempTarget] = []
  617. for target in tempTargets {
  618. if target.duration > 0 {
  619. if !currentPackage.isEmpty {
  620. groupedPackages.append(currentPackage)
  621. currentPackage = []
  622. }
  623. currentPackage.append(target)
  624. } else {
  625. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  626. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  627. target.createdAt <= lastNonZeroTempTarget.createdAt
  628. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  629. {
  630. currentPackage.append(target)
  631. }
  632. }
  633. }
  634. }
  635. // appends last package, if exists
  636. if !currentPackage.isEmpty {
  637. groupedPackages.append(currentPackage)
  638. }
  639. for package in groupedPackages {
  640. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  641. continue
  642. }
  643. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  644. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  645. if let earliestCancelTarget = earliestCancelTarget {
  646. end = min(earliestCancelTarget.createdAt, end)
  647. }
  648. let now = Date()
  649. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  650. if firstNonZeroTarget.targetTop != nil {
  651. calculatedTTs
  652. .append(ChartTempTarget(
  653. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  654. start: firstNonZeroTarget.createdAt,
  655. end: end
  656. ))
  657. }
  658. }
  659. ChartTempTargets = calculatedTTs
  660. }
  661. private func calculateTempBasals() {
  662. let basals = tempBasals
  663. var returnTempBasalRates: [PumpHistoryEvent] = []
  664. var finished: [Int: Bool] = [:]
  665. basals.indices.forEach { i in
  666. basals.indices.forEach { j in
  667. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  668. let rate = basals[i].rate ?? basals[j].rate
  669. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  670. finished[i] = true
  671. if rate != 0 || durationMin != 0 {
  672. returnTempBasalRates.append(
  673. PumpHistoryEvent(
  674. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  675. timestamp: basals[i].timestamp,
  676. durationMin: durationMin,
  677. rate: rate
  678. )
  679. )
  680. }
  681. }
  682. }
  683. }
  684. TempBasals = returnTempBasalRates
  685. }
  686. private func addPredictions(_ predictions: [Int], type: PredictionType, deliveredAt: Date, endMarker: Date) -> [Prediction] {
  687. var calculatedPredictions: [Prediction] = []
  688. predictions.indices.forEach { index in
  689. let predTime = Date(
  690. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  691. )
  692. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  693. calculatedPredictions.append(
  694. Prediction(amount: predictions[index], timestamp: predTime, type: type)
  695. )
  696. }
  697. }
  698. return calculatedPredictions
  699. }
  700. private func findRegularBasalPoints(
  701. timeBegin: TimeInterval,
  702. timeEnd: TimeInterval,
  703. autotuned: Bool
  704. ) -> [BasalProfile] {
  705. guard timeBegin < timeEnd else {
  706. return []
  707. }
  708. let beginDate = Date(timeIntervalSince1970: timeBegin)
  709. let calendar = Calendar.current
  710. let startOfDay = calendar.startOfDay(for: beginDate)
  711. let profile = autotuned ? autotunedBasalProfile : basalProfile
  712. let basalNormalized = profile.map {
  713. (
  714. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  715. rate: $0.rate
  716. )
  717. } + profile.map {
  718. (
  719. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  720. .timeIntervalSince1970,
  721. rate: $0.rate
  722. )
  723. } + profile.map {
  724. (
  725. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  726. .timeIntervalSince1970,
  727. rate: $0.rate
  728. )
  729. }
  730. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  731. .compactMap { window -> BasalProfile? in
  732. let window = Array(window)
  733. if window[0].time < timeBegin, window[1].time < timeBegin {
  734. return nil
  735. }
  736. if window[0].time < timeBegin, window[1].time >= timeBegin {
  737. let startDate = Date(timeIntervalSince1970: timeBegin)
  738. let rate = window[0].rate
  739. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  740. }
  741. if window[0].time >= timeBegin, window[0].time < timeEnd {
  742. let startDate = Date(timeIntervalSince1970: window[0].time)
  743. let rate = window[0].rate
  744. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  745. }
  746. return nil
  747. }
  748. return basalTruncatedPoints
  749. }
  750. /// update start and end marker to fix scroll update problem with x axis
  751. private func updateStartEndMarkers() {
  752. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  753. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  754. }
  755. private func calculateBasals() {
  756. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  757. let regularPoints = findRegularBasalPoints(
  758. timeBegin: dayAgoTime,
  759. timeEnd: endMarker.timeIntervalSince1970,
  760. autotuned: false
  761. )
  762. let autotunedBasalPoints = findRegularBasalPoints(
  763. timeBegin: dayAgoTime,
  764. timeEnd: endMarker.timeIntervalSince1970,
  765. autotuned: true
  766. )
  767. var totalBasal = regularPoints + autotunedBasalPoints
  768. totalBasal.sort {
  769. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  770. }
  771. var basals: [BasalProfile] = []
  772. totalBasal.indices.forEach { index in
  773. basals.append(BasalProfile(
  774. amount: totalBasal[index].amount,
  775. isOverwritten: totalBasal[index].isOverwritten,
  776. startDate: totalBasal[index].startDate,
  777. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  778. ))
  779. print(
  780. "Basal",
  781. totalBasal[index].startDate,
  782. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  783. totalBasal[index].amount,
  784. totalBasal[index].isOverwritten
  785. )
  786. }
  787. BasalProfiles = basals
  788. }
  789. // MARK: - Chart formatting
  790. private func yAxisChartData() {
  791. let glucoseMapped = glucose.compactMap(\.glucose)
  792. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  793. // default values
  794. minValue = 45 * conversionFactor - 20 * conversionFactor
  795. maxValue = 270 * conversionFactor + 50 * conversionFactor
  796. return
  797. }
  798. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  799. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  800. debug(.default, "min \(minValue)")
  801. debug(.default, "max \(maxValue)")
  802. }
  803. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  804. plotContent
  805. .rotationEffect(.degrees(180))
  806. .scaleEffect(x: -1, y: 1)
  807. .chartXAxis(.hidden)
  808. }
  809. private var mainChartXAxis: some AxisContent {
  810. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  811. if displayXgridLines {
  812. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  813. } else {
  814. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  815. }
  816. }
  817. }
  818. private var basalChartXAxis: some AxisContent {
  819. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  820. if displayXgridLines {
  821. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  822. } else {
  823. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  824. }
  825. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  826. .font(.footnote)
  827. }
  828. }
  829. private var mainChartYAxis: some AxisContent {
  830. AxisMarks(position: .trailing) { value in
  831. if displayXgridLines {
  832. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  833. } else {
  834. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  835. }
  836. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  837. /// fix offset between the two charts...
  838. if units == .mmolL {
  839. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  840. }
  841. AxisValueLabel().font(.footnote)
  842. }
  843. }
  844. }
  845. private var basalChartYAxis: some AxisContent {
  846. AxisMarks(position: .trailing) { _ in
  847. AxisTick(length: units == .mmolL ? 25 : 27, stroke: .init(lineWidth: 4))
  848. .foregroundStyle(Color.clear).font(.footnote)
  849. }
  850. }
  851. }
  852. struct LegendItem: View {
  853. var color: Color
  854. var label: String
  855. var body: some View {
  856. Group {
  857. Circle().fill(color).frame(width: 8, height: 8)
  858. Text(label)
  859. .font(.system(size: 10, weight: .bold))
  860. .foregroundColor(color)
  861. }
  862. }
  863. }