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