MainChartView.swift 37 KB

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