MainChartView.swift 36 KB

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