MainChartView.swift 37 KB

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