MainChartView.swift 38 KB

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