MainChartView.swift 36 KB

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