MainChartView.swift 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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. var geo: GeometryProxy
  34. @Binding var units: GlucoseUnits
  35. @Binding var announcement: [Announcement]
  36. @Binding var hours: Int
  37. @Binding var maxBasal: Decimal
  38. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  39. @Binding var basalProfile: [BasalProfileEntry]
  40. @Binding var tempTargets: [TempTarget]
  41. @Binding var smooth: Bool
  42. @Binding var highGlucose: Decimal
  43. @Binding var lowGlucose: Decimal
  44. @Binding var screenHours: Int16
  45. @Binding var displayXgridLines: Bool
  46. @Binding var displayYgridLines: Bool
  47. @Binding var thresholdLines: Bool
  48. @Binding var isTempTargetActive: Bool
  49. @StateObject var state: Home.StateModel
  50. @State var didAppearTrigger = false
  51. @State private var basalProfiles: [BasalProfile] = []
  52. @State private var chartTempTargets: [ChartTempTarget] = []
  53. @State private var count: Decimal = 1
  54. @State private var startMarker =
  55. Date(timeIntervalSinceNow: TimeInterval(hours: -24))
  56. @State private var endMarker = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  57. @State private var minValue: Decimal = 45
  58. @State private var maxValue: Decimal = 270
  59. @State private var selection: Date? = nil
  60. @State private var minValueCobChart: Decimal = 0
  61. @State private var maxValueCobChart: Decimal = 20
  62. @State private var minValueIobChart: Decimal = 0
  63. @State private var maxValueIobChart: Decimal = 5
  64. private let now = Date.now
  65. private let context = CoreDataStack.shared.persistentContainer.viewContext
  66. @Environment(\.colorScheme) var colorScheme
  67. @Environment(\.calendar) var calendar
  68. private var bolusFormatter: NumberFormatter {
  69. let formatter = NumberFormatter()
  70. formatter.numberStyle = .decimal
  71. formatter.minimumIntegerDigits = 0
  72. formatter.maximumFractionDigits = 2
  73. formatter.decimalSeparator = "."
  74. return formatter
  75. }
  76. private var carbsFormatter: NumberFormatter {
  77. let formatter = NumberFormatter()
  78. formatter.numberStyle = .decimal
  79. formatter.maximumFractionDigits = 0
  80. return formatter
  81. }
  82. private var upperLimit: Decimal {
  83. units == .mgdL ? 400 : 22.2
  84. }
  85. private var defaultBolusPosition: Int {
  86. units == .mgdL ? 120 : 7
  87. }
  88. private var bolusOffset: Decimal {
  89. units == .mgdL ? 30 : 1.66
  90. }
  91. private var selectedGlucose: GlucoseStored? {
  92. if let selection = selection {
  93. let lowerBound = selection.addingTimeInterval(-120)
  94. let upperBound = selection.addingTimeInterval(120)
  95. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  96. } else {
  97. return nil
  98. }
  99. }
  100. private var selectedCOBValue: OrefDetermination? {
  101. if let selection = selection {
  102. let lowerBound = selection.addingTimeInterval(-120)
  103. let upperBound = selection.addingTimeInterval(120)
  104. return state.enactedAndNonEnactedDeterminations.first {
  105. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  106. }
  107. } else {
  108. return nil
  109. }
  110. }
  111. private var selectedIOBValue: OrefDetermination? {
  112. if let selection = selection {
  113. let lowerBound = selection.addingTimeInterval(-120)
  114. let upperBound = selection.addingTimeInterval(120)
  115. return state.enactedAndNonEnactedDeterminations.first {
  116. $0.deliverAt ?? now >= lowerBound && $0.deliverAt ?? now <= upperBound
  117. }
  118. } else {
  119. return nil
  120. }
  121. }
  122. var body: some View {
  123. VStack {
  124. ZStack {
  125. VStack(spacing: 5) {
  126. dummyBasalChart
  127. staticYAxisChart
  128. Spacer()
  129. dummyCobChart
  130. }
  131. ScrollViewReader { scroller in
  132. ScrollView(.horizontal, showsIndicators: false) {
  133. VStack(spacing: 5) {
  134. basalChart
  135. mainChart
  136. Spacer()
  137. ZStack {
  138. cobChart
  139. iobChart
  140. }
  141. }.onChange(of: screenHours) { _ in
  142. updateStartEndMarkers()
  143. yAxisChartData()
  144. yAxisChartDataCobChart()
  145. yAxisChartDataIobChart()
  146. scroller.scrollTo("MainChart", anchor: .trailing)
  147. }
  148. .onChange(of: state.glucoseFromPersistence.last?.glucose) { _ in
  149. updateStartEndMarkers()
  150. yAxisChartData()
  151. scroller.scrollTo("MainChart", anchor: .trailing)
  152. }
  153. .onChange(of: state.enactedAndNonEnactedDeterminations.first?.deliverAt) { _ in
  154. updateStartEndMarkers()
  155. yAxisChartDataCobChart()
  156. yAxisChartDataIobChart()
  157. scroller.scrollTo("MainChart", anchor: .trailing)
  158. }
  159. .onChange(of: state.tempBasals) { _ in
  160. updateStartEndMarkers()
  161. scroller.scrollTo("MainChart", anchor: .trailing)
  162. }
  163. .onChange(of: units) { _ in
  164. yAxisChartData()
  165. }
  166. .onAppear {
  167. updateStartEndMarkers()
  168. yAxisChartData()
  169. yAxisChartDataCobChart()
  170. yAxisChartDataIobChart()
  171. scroller.scrollTo("MainChart", anchor: .trailing)
  172. }
  173. }
  174. }
  175. }
  176. }
  177. }
  178. }
  179. // MARK: - Components
  180. extension MainChartView {
  181. /// 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
  182. private var staticYAxisChart: some View {
  183. Chart {
  184. /// high and low threshold lines
  185. if thresholdLines {
  186. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  187. .lineStyle(.init(lineWidth: 1, dash: [5]))
  188. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  189. .lineStyle(.init(lineWidth: 1, dash: [5]))
  190. }
  191. }
  192. .id("DummyMainChart")
  193. .frame(minHeight: geo.size.height * 0.28)
  194. .frame(width: screenSize.width - 10)
  195. .chartXAxis { mainChartXAxis }
  196. .chartXScale(domain: startMarker ... endMarker)
  197. .chartXAxis(.hidden)
  198. .chartYAxis { mainChartYAxis }
  199. .chartYScale(domain: units == .mgdL ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  200. .chartLegend(.hidden)
  201. }
  202. private var dummyBasalChart: some View {
  203. Chart {}
  204. .id("DummyBasalChart")
  205. .frame(minHeight: geo.size.height * 0.05)
  206. .frame(width: screenSize.width - 10)
  207. .chartXAxis { basalChartXAxis }
  208. .chartXAxis(.hidden)
  209. .chartYAxis(.hidden)
  210. .chartLegend(.hidden)
  211. }
  212. private var dummyCobChart: some View {
  213. Chart {
  214. drawCOB(dummy: true)
  215. }
  216. .id("DummyCobChart")
  217. .frame(minHeight: geo.size.height * 0.12)
  218. .frame(width: screenSize.width - 10)
  219. .chartXScale(domain: startMarker ... endMarker)
  220. .chartXAxis { basalChartXAxis }
  221. .chartXAxis(.hidden)
  222. .chartYAxis { cobChartYAxis }
  223. .chartYAxis(.hidden)
  224. .chartYScale(domain: minValueCobChart ... maxValueCobChart)
  225. .chartLegend(.hidden)
  226. }
  227. private var mainChart: some View {
  228. VStack {
  229. Chart {
  230. drawStartRuleMark()
  231. drawEndRuleMark()
  232. drawCurrentTimeMarker()
  233. drawFpus()
  234. drawBoluses()
  235. drawTempTargets()
  236. drawActiveOverrides()
  237. drawOverrideRunStored()
  238. drawGlucose(dummy: false)
  239. drawManualGlucose()
  240. drawCarbs()
  241. if state.forecastDisplayType == .lines {
  242. drawForecastsLines()
  243. } else {
  244. drawForecastsCone()
  245. }
  246. /// show glucose value when hovering over it
  247. if #available(iOS 17, *) {
  248. if let selectedGlucose {
  249. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  250. .foregroundStyle(Color.tabBar)
  251. .offset(yStart: 70)
  252. .lineStyle(.init(lineWidth: 2))
  253. .annotation(
  254. position: .top,
  255. alignment: .center,
  256. overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))
  257. ) {
  258. selectionPopover
  259. }
  260. PointMark(
  261. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  262. y: .value("Value", selectedGlucose.glucose)
  263. )
  264. .zIndex(-1)
  265. .symbolSize(CGSize(width: 15, height: 15))
  266. .foregroundStyle(
  267. Decimal(selectedGlucose.glucose) > highGlucose ? Color.orange
  268. .opacity(0.8) :
  269. (
  270. Decimal(selectedGlucose.glucose) < lowGlucose ? Color.red.opacity(0.8) : Color.green
  271. .opacity(0.8)
  272. )
  273. )
  274. PointMark(
  275. x: .value("Time", selectedGlucose.date ?? now, unit: .minute),
  276. y: .value("Value", selectedGlucose.glucose)
  277. )
  278. .zIndex(-1)
  279. .symbolSize(CGSize(width: 6, height: 6))
  280. .foregroundStyle(Color.primary)
  281. }
  282. }
  283. }
  284. .id("MainChart")
  285. .onChange(of: state.insulinFromPersistence) { _ in
  286. state.roundedTotalBolus = state.calculateTINS()
  287. }
  288. .onChange(of: tempTargets) { _ in
  289. calculateTTs()
  290. }
  291. .onChange(of: didAppearTrigger) { _ in
  292. calculateTTs()
  293. }
  294. .frame(minHeight: geo.size.height * 0.28)
  295. .frame(width: fullWidth(viewWidth: screenSize.width))
  296. .chartXScale(domain: startMarker ... endMarker)
  297. .chartXAxis { mainChartXAxis }
  298. .chartYAxis { mainChartYAxis }
  299. .chartYAxis(.hidden)
  300. .backport.chartXSelection(value: $selection)
  301. .chartYScale(domain: units == .mgdL ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  302. .backport.chartForegroundStyleScale(state: state)
  303. }
  304. }
  305. @ViewBuilder var selectionPopover: some View {
  306. if let sgv = selectedGlucose?.glucose {
  307. let glucoseToShow = units == .mgdL ? Decimal(sgv) : Decimal(sgv).asMmolL
  308. VStack(alignment: .leading) {
  309. HStack {
  310. Image(systemName: "clock")
  311. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  312. .font(.body).bold()
  313. }.font(.body).padding(.bottom, 5)
  314. HStack {
  315. Text(units == .mgdL ? glucoseToShow.description : Decimal(sgv).formattedAsMmolL)
  316. .bold()
  317. + Text(" \(units.rawValue)")
  318. }.foregroundStyle(
  319. glucoseToShow < lowGlucose ? Color
  320. .red : (glucoseToShow > highGlucose ? Color.orange : Color.primary)
  321. ).font(.body)
  322. if let selectedIOBValue, let iob = selectedIOBValue.iob {
  323. HStack {
  324. Image(systemName: "syringe.fill").frame(width: 15)
  325. Text(bolusFormatter.string(from: iob) ?? "")
  326. .bold()
  327. + Text(NSLocalizedString(" U", comment: "Insulin unit"))
  328. }.foregroundStyle(Color.insulin).font(.body)
  329. }
  330. if let selectedCOBValue {
  331. HStack {
  332. Image(systemName: "fork.knife").frame(width: 15)
  333. Text(carbsFormatter.string(from: selectedCOBValue.cob as NSNumber) ?? "")
  334. .bold()
  335. + Text(NSLocalizedString(" g", comment: "gram of carbs"))
  336. }.foregroundStyle(Color.orange).font(.body)
  337. }
  338. }
  339. .padding()
  340. .background {
  341. RoundedRectangle(cornerRadius: 4)
  342. .fill(Color.chart.opacity(0.85))
  343. .shadow(color: Color.secondary, radius: 2)
  344. .overlay(
  345. RoundedRectangle(cornerRadius: 4)
  346. .stroke(Color.secondary, lineWidth: 2)
  347. )
  348. }
  349. }
  350. }
  351. private var basalChart: some View {
  352. VStack {
  353. Chart {
  354. drawStartRuleMark()
  355. drawEndRuleMark()
  356. drawCurrentTimeMarker()
  357. drawTempBasals(dummy: false)
  358. drawBasalProfile()
  359. drawSuspensions()
  360. }.onChange(of: state.tempBasals) { _ in
  361. calculateBasals()
  362. }
  363. .onChange(of: maxBasal) { _ in
  364. calculateBasals()
  365. }
  366. .onChange(of: autotunedBasalProfile) { _ in
  367. calculateBasals()
  368. }
  369. .onChange(of: didAppearTrigger) { _ in
  370. calculateBasals()
  371. }.onChange(of: basalProfile) { _ in
  372. calculateBasals()
  373. }
  374. .frame(minHeight: geo.size.height * 0.05)
  375. .frame(width: fullWidth(viewWidth: screenSize.width))
  376. .chartXScale(domain: startMarker ... endMarker)
  377. .chartXAxis { basalChartXAxis }
  378. .chartXAxis(.hidden)
  379. .chartYAxis(.hidden)
  380. .chartPlotStyle { basalChartPlotStyle($0) }
  381. }
  382. }
  383. private var iobChart: some View {
  384. VStack {
  385. Chart {
  386. drawIOB()
  387. if #available(iOS 17, *) {
  388. if let selectedIOBValue {
  389. PointMark(
  390. x: .value("Time", selectedIOBValue.deliverAt ?? now, unit: .minute),
  391. y: .value("Value", Int(truncating: selectedIOBValue.iob ?? 0))
  392. )
  393. .symbolSize(CGSize(width: 15, height: 15))
  394. .foregroundStyle(Color.darkerBlue.opacity(0.8))
  395. PointMark(
  396. x: .value("Time", selectedIOBValue.deliverAt ?? now, unit: .minute),
  397. y: .value("Value", Int(truncating: selectedIOBValue.iob ?? 0))
  398. )
  399. .symbolSize(CGSize(width: 6, height: 6))
  400. .foregroundStyle(Color.primary)
  401. }
  402. }
  403. }
  404. .frame(minHeight: geo.size.height * 0.12)
  405. .frame(width: fullWidth(viewWidth: screenSize.width))
  406. .chartXScale(domain: startMarker ... endMarker)
  407. .backport.chartXSelection(value: $selection)
  408. .chartXAxis { basalChartXAxis }
  409. .chartYAxis { cobChartYAxis }
  410. .chartYScale(domain: minValueIobChart ... maxValueIobChart)
  411. .chartYAxis(.hidden)
  412. }
  413. }
  414. private var cobChart: some View {
  415. Chart {
  416. drawCurrentTimeMarker()
  417. drawCOB(dummy: false)
  418. if #available(iOS 17, *) {
  419. if let selectedCOBValue {
  420. PointMark(
  421. x: .value("Time", selectedCOBValue.deliverAt ?? now, unit: .minute),
  422. y: .value("Value", selectedCOBValue.cob)
  423. )
  424. .symbolSize(CGSize(width: 15, height: 15))
  425. .foregroundStyle(Color.orange.opacity(0.8))
  426. PointMark(
  427. x: .value("Time", selectedCOBValue.deliverAt ?? now, unit: .minute),
  428. y: .value("Value", selectedCOBValue.cob)
  429. )
  430. .symbolSize(CGSize(width: 6, height: 6))
  431. .foregroundStyle(Color.primary)
  432. }
  433. }
  434. }
  435. .frame(minHeight: geo.size.height * 0.12)
  436. .frame(width: fullWidth(viewWidth: screenSize.width))
  437. .chartXScale(domain: startMarker ... endMarker)
  438. .backport.chartXSelection(value: $selection)
  439. .chartXAxis { basalChartXAxis }
  440. .chartYAxis { cobChartYAxis }
  441. .chartYScale(domain: minValueCobChart ... maxValueCobChart)
  442. }
  443. }
  444. // MARK: - Calculations
  445. extension MainChartView {
  446. private func drawBoluses() -> some ChartContent {
  447. ForEach(state.insulinFromPersistence) { insulin in
  448. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  449. let bolusDate = insulin.timestamp ?? Date()
  450. if amount != 0, let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)?.glucose {
  451. let yPosition = (units == .mgdL ? Decimal(glucose) : Decimal(glucose).asMmolL) + bolusOffset
  452. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  453. PointMark(
  454. x: .value("Time", bolusDate, unit: .second),
  455. y: .value("Value", yPosition)
  456. )
  457. .symbol {
  458. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  459. }
  460. .annotation(position: .top) {
  461. Text(bolusFormatter.string(from: amount) ?? "")
  462. .font(.caption2)
  463. .foregroundStyle(Color.primary)
  464. }
  465. }
  466. }
  467. }
  468. private func drawCarbs() -> some ChartContent {
  469. /// carbs
  470. ForEach(state.carbsFromPersistence) { carb in
  471. let carbAmount = carb.carbs
  472. let carbDate = carb.date ?? Date()
  473. if let glucose = timeToNearestGlucose(time: carbDate.timeIntervalSince1970)?.glucose {
  474. let yPosition = (units == .mgdL ? Decimal(glucose) : Decimal(glucose).asMmolL) - bolusOffset
  475. let size = (Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale)
  476. let limitedSize = size > 30 ? 30 : size
  477. PointMark(
  478. x: .value("Time", carbDate, unit: .second),
  479. y: .value("Value", yPosition)
  480. )
  481. .symbol {
  482. Image(systemName: "arrowtriangle.down.fill").font(.system(size: limitedSize)).foregroundStyle(Color.orange)
  483. .rotationEffect(.degrees(180))
  484. }
  485. .annotation(position: .bottom) {
  486. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  487. .foregroundStyle(Color.primary)
  488. }
  489. }
  490. }
  491. }
  492. private func drawFpus() -> some ChartContent {
  493. /// fpus
  494. ForEach(state.fpusFromPersistence, id: \.id) { fpu in
  495. let fpuAmount = fpu.carbs
  496. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  497. let yPosition = minValue
  498. PointMark(
  499. x: .value("Time", fpu.date ?? Date(), unit: .second),
  500. y: .value("Value", yPosition)
  501. )
  502. .symbolSize(size)
  503. .foregroundStyle(Color.brown)
  504. }
  505. }
  506. private func drawGlucose(dummy _: Bool) -> some ChartContent {
  507. /// glucose point mark
  508. /// filtering for high and low bounds in settings
  509. ForEach(state.glucoseFromPersistence) { item in
  510. let glucoseToDisplay = units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  511. if smooth {
  512. LineMark(x: .value("Time", item.date ?? Date()), y: .value("Value", glucoseToDisplay))
  513. .foregroundStyle(
  514. .linearGradient(stops: state.gradientStops, startPoint: .bottom, endPoint: .top)
  515. )
  516. .symbol(.circle).symbolSize(34)
  517. } else {
  518. if glucoseToDisplay > highGlucose {
  519. PointMark(
  520. x: .value("Time", item.date ?? Date(), unit: .second),
  521. y: .value("Value", glucoseToDisplay)
  522. ).foregroundStyle(Color.orange.gradient).symbolSize(20)
  523. } else if glucoseToDisplay < lowGlucose {
  524. PointMark(
  525. x: .value("Time", item.date ?? Date(), unit: .second),
  526. y: .value("Value", glucoseToDisplay)
  527. ).foregroundStyle(Color.red.gradient).symbolSize(20)
  528. } else {
  529. PointMark(
  530. x: .value("Time", item.date ?? Date(), unit: .second),
  531. y: .value("Value", glucoseToDisplay)
  532. ).foregroundStyle(Color.green.gradient).symbolSize(20)
  533. }
  534. }
  535. }
  536. }
  537. private func timeForIndex(_ index: Int32) -> Date {
  538. let currentTime = Date()
  539. let timeInterval = TimeInterval(index * 300)
  540. return currentTime.addingTimeInterval(timeInterval)
  541. }
  542. private func drawForecastsCone() -> some ChartContent {
  543. // Draw AreaMark for the forecast bounds
  544. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  545. if index < state.minForecast.count, index < state.maxForecast.count {
  546. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  547. let xValue = timeForIndex(Int32(index))
  548. // if distance between respective min and max is 0, provide a default range
  549. if yMinMaxDelta == 0 {
  550. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  551. Decimal(state.minForecast[index] - 1)
  552. .asMmolL
  553. let yMaxValue = units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  554. Decimal(state.minForecast[index] + 1)
  555. .asMmolL
  556. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  557. AreaMark(
  558. x: .value("Time", xValue),
  559. // maxValue is already parsed to user units, no need to parse
  560. yStart: .value("Min Value", yMinValue <= maxValue ? yMinValue : maxValue),
  561. yEnd: .value("Max Value", yMaxValue <= maxValue ? yMaxValue : maxValue)
  562. )
  563. .foregroundStyle(Color.blue.opacity(0.5))
  564. .interpolationMethod(.catmullRom)
  565. }
  566. } else {
  567. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index]) : Decimal(state.minForecast[index]).asMmolL
  568. let yMaxValue = units == .mgdL ? Decimal(state.maxForecast[index]) : Decimal(state.maxForecast[index]).asMmolL
  569. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  570. AreaMark(
  571. x: .value("Time", xValue),
  572. // maxValue is already parsed to user units, no need to parse
  573. yStart: .value("Min Value", yMinValue <= maxValue ? yMinValue : maxValue),
  574. yEnd: .value("Max Value", yMaxValue <= maxValue ? yMaxValue : maxValue)
  575. )
  576. .foregroundStyle(Color.blue.opacity(0.5))
  577. .interpolationMethod(.catmullRom)
  578. }
  579. }
  580. }
  581. }
  582. }
  583. private func drawForecastsLines() -> some ChartContent {
  584. ForEach(state.preprocessedData, id: \.id) { tuple in
  585. let forecastValue = tuple.forecastValue
  586. let forecast = tuple.forecast
  587. let valueAsDecimal = Decimal(forecastValue.value)
  588. let displayValue = units == .mmolL ? valueAsDecimal.asMmolL : valueAsDecimal
  589. let xValue = timeForIndex(forecastValue.index)
  590. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  591. LineMark(
  592. x: .value("Time", xValue),
  593. y: .value("Value", displayValue)
  594. )
  595. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  596. }
  597. }
  598. }
  599. private func drawCurrentTimeMarker() -> some ChartContent {
  600. RuleMark(
  601. x: .value(
  602. "",
  603. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  604. unit: .second
  605. )
  606. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  607. }
  608. private func drawStartRuleMark() -> some ChartContent {
  609. RuleMark(
  610. x: .value(
  611. "",
  612. startMarker,
  613. unit: .second
  614. )
  615. ).foregroundStyle(Color.clear)
  616. }
  617. private func drawEndRuleMark() -> some ChartContent {
  618. RuleMark(
  619. x: .value(
  620. "",
  621. endMarker,
  622. unit: .second
  623. )
  624. ).foregroundStyle(Color.clear)
  625. }
  626. private func drawTempTargets() -> some ChartContent {
  627. /// temp targets
  628. ForEach(chartTempTargets, id: \.self) { target in
  629. let targetLimited = min(max(target.amount, 0), upperLimit)
  630. RuleMark(
  631. xStart: .value("Start", target.start),
  632. xEnd: .value("End", target.end),
  633. y: .value("Value", targetLimited)
  634. )
  635. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  636. }
  637. }
  638. private func drawActiveOverrides() -> some ChartContent {
  639. ForEach(state.overrides) { override in
  640. let start: Date = override.date ?? .distantPast
  641. let duration = state.calculateDuration(override: override)
  642. let end: Date = start.addingTimeInterval(duration)
  643. let target = state.calculateTarget(override: override)
  644. RuleMark(
  645. xStart: .value("Start", start, unit: .second),
  646. xEnd: .value("End", end, unit: .second),
  647. y: .value("Value", target)
  648. )
  649. .foregroundStyle(Color.purple.opacity(0.6))
  650. .lineStyle(.init(lineWidth: 8))
  651. // .annotation(position: .overlay, spacing: 0) {
  652. // if let name = override.name {
  653. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  654. // }
  655. // }
  656. }
  657. }
  658. private func drawOverrideRunStored() -> some ChartContent {
  659. ForEach(state.overrideRunStored) { overrideRunStored in
  660. let start: Date = overrideRunStored.startDate ?? .distantPast
  661. let end: Date = overrideRunStored.endDate ?? Date()
  662. let target = overrideRunStored.target?.decimalValue ?? 100
  663. RuleMark(
  664. xStart: .value("Start", start, unit: .second),
  665. xEnd: .value("End", end, unit: .second),
  666. y: .value("Value", target)
  667. )
  668. .foregroundStyle(Color.purple.opacity(0.4))
  669. .lineStyle(.init(lineWidth: 8))
  670. // .annotation(position: .bottom, spacing: 0) {
  671. // if let name = overrideRunStored.override?.name {
  672. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  673. // }
  674. // }
  675. }
  676. }
  677. private func drawManualGlucose() -> some ChartContent {
  678. /// manual glucose mark
  679. ForEach(state.manualGlucoseFromPersistence) { item in
  680. let manualGlucose = units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  681. PointMark(
  682. x: .value("Time", item.date ?? Date(), unit: .second),
  683. y: .value("Value", manualGlucose)
  684. )
  685. .symbol {
  686. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  687. .foregroundStyle(.red)
  688. }
  689. }
  690. }
  691. private func drawSuspensions() -> some ChartContent {
  692. let suspensions = state.suspensions
  693. return ForEach(suspensions) { suspension in
  694. let now = Date()
  695. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  696. let suspensionEnd = min(
  697. (
  698. suspensions
  699. .first(where: {
  700. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  701. .timestamp
  702. ) ?? now,
  703. now
  704. )
  705. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  706. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  707. RectangleMark(
  708. xStart: .value("start", suspensionStart),
  709. xEnd: .value("end", suspensionEnd),
  710. yStart: .value("suspend-start", 0),
  711. yEnd: .value("suspend-end", suspensionMarkHeight)
  712. )
  713. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  714. }
  715. }
  716. }
  717. private func drawIOB() -> some ChartContent {
  718. ForEach(state.enactedAndNonEnactedDeterminations) { iob in
  719. let rawAmount = iob.iob?.doubleValue ?? 0
  720. let amount: Double = rawAmount > 0 ? rawAmount : rawAmount * 2 // weigh negative iob with factor 2
  721. let date: Date = iob.deliverAt ?? Date()
  722. LineMark(x: .value("Time", date), y: .value("Amount", amount))
  723. .foregroundStyle(Color.darkerBlue)
  724. AreaMark(x: .value("Time", date), y: .value("Amount", amount))
  725. .foregroundStyle(
  726. LinearGradient(
  727. gradient: Gradient(
  728. colors: [
  729. Color.darkerBlue.opacity(0.8),
  730. Color.darkerBlue.opacity(0.01)
  731. ]
  732. ),
  733. startPoint: .top,
  734. endPoint: .bottom
  735. )
  736. )
  737. }
  738. }
  739. private func drawCOB(dummy: Bool) -> some ChartContent {
  740. ForEach(state.enactedAndNonEnactedDeterminations) { cob in
  741. let amount = Int(cob.cob)
  742. let date: Date = cob.deliverAt ?? Date()
  743. if dummy {
  744. LineMark(x: .value("Time", date), y: .value("Value", amount))
  745. .foregroundStyle(Color.clear)
  746. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  747. Color.clear
  748. )
  749. } else {
  750. LineMark(x: .value("Time", date), y: .value("Value", amount))
  751. .foregroundStyle(Color.orange.gradient)
  752. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  753. LinearGradient(
  754. gradient: Gradient(
  755. colors: [
  756. Color.orange.opacity(0.8),
  757. Color.orange.opacity(0.01)
  758. ]
  759. ),
  760. startPoint: .top,
  761. endPoint: .bottom
  762. )
  763. )
  764. }
  765. }
  766. }
  767. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  768. let now = Date()
  769. let tempBasals = state.tempBasals
  770. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  771. let duration = temp.tempBasal?.duration ?? 0
  772. let timestamp = temp.timestamp ?? Date()
  773. let end = min(timestamp + duration.minutes, now)
  774. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  775. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  776. // Check if there's a subsequent temp basal to determine the end time
  777. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  778. return (timestamp, end, rate)
  779. }
  780. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  781. }
  782. }
  783. private func drawTempBasals(dummy: Bool) -> some ChartContent {
  784. ForEach(prepareTempBasals(), id: \.rate) { basal in
  785. if dummy {
  786. RectangleMark(
  787. xStart: .value("start", basal.start),
  788. xEnd: .value("end", basal.end),
  789. yStart: .value("rate-start", 0),
  790. yEnd: .value("rate-end", basal.rate)
  791. ).foregroundStyle(Color.clear)
  792. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  793. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  794. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  795. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  796. } else {
  797. RectangleMark(
  798. xStart: .value("start", basal.start),
  799. xEnd: .value("end", basal.end),
  800. yStart: .value("rate-start", 0),
  801. yEnd: .value("rate-end", basal.rate)
  802. ).foregroundStyle(
  803. LinearGradient(
  804. gradient: Gradient(
  805. colors: [
  806. Color.insulin.opacity(0.6),
  807. Color.insulin.opacity(0.1)
  808. ]
  809. ),
  810. startPoint: .top,
  811. endPoint: .bottom
  812. )
  813. )
  814. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  815. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  816. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  817. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  818. }
  819. }
  820. }
  821. private func drawBasalProfile() -> some ChartContent {
  822. /// dashed profile line
  823. ForEach(basalProfiles, id: \.self) { profile in
  824. LineMark(
  825. x: .value("Start Date", profile.startDate),
  826. y: .value("Amount", profile.amount),
  827. series: .value("profile", "profile")
  828. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  829. LineMark(
  830. x: .value("End Date", profile.endDate ?? endMarker),
  831. y: .value("Amount", profile.amount),
  832. series: .value("profile", "profile")
  833. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  834. }
  835. }
  836. /// calculates the glucose value thats the nearest to parameter 'time'
  837. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  838. guard !state.glucoseFromPersistence.isEmpty else {
  839. return nil
  840. }
  841. var low = 0
  842. var high = state.glucoseFromPersistence.count - 1
  843. var closestGlucose: GlucoseStored?
  844. // binary search to find next glucose
  845. while low <= high {
  846. let mid = low + (high - low) / 2
  847. let midTime = state.glucoseFromPersistence[mid].date?.timeIntervalSince1970 ?? 0
  848. if midTime == time {
  849. return state.glucoseFromPersistence[mid]
  850. } else if midTime < time {
  851. low = mid + 1
  852. } else {
  853. high = mid - 1
  854. }
  855. // update if necessary
  856. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  857. closestGlucose = state.glucoseFromPersistence[mid]
  858. }
  859. }
  860. return closestGlucose
  861. }
  862. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  863. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  864. }
  865. /// calculations for temp target bar mark
  866. private func calculateTTs() {
  867. var groupedPackages: [[TempTarget]] = []
  868. var currentPackage: [TempTarget] = []
  869. var calculatedTTs: [ChartTempTarget] = []
  870. for target in tempTargets {
  871. if target.duration > 0 {
  872. if !currentPackage.isEmpty {
  873. groupedPackages.append(currentPackage)
  874. currentPackage = []
  875. }
  876. currentPackage.append(target)
  877. } else {
  878. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  879. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  880. target.createdAt <= lastNonZeroTempTarget.createdAt
  881. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  882. {
  883. currentPackage.append(target)
  884. }
  885. }
  886. }
  887. }
  888. // appends last package, if exists
  889. if !currentPackage.isEmpty {
  890. groupedPackages.append(currentPackage)
  891. }
  892. for package in groupedPackages {
  893. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  894. continue
  895. }
  896. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  897. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  898. if let earliestCancelTarget = earliestCancelTarget {
  899. end = min(earliestCancelTarget.createdAt, end)
  900. }
  901. let now = Date()
  902. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  903. if firstNonZeroTarget.targetTop != nil {
  904. let targetTop = firstNonZeroTarget.targetTop ?? 0
  905. calculatedTTs
  906. .append(ChartTempTarget(
  907. amount: units == .mgdL ? targetTop : targetTop.asMmolL,
  908. start: firstNonZeroTarget.createdAt,
  909. end: end
  910. ))
  911. }
  912. }
  913. chartTempTargets = calculatedTTs
  914. }
  915. private func findRegularBasalPoints(
  916. timeBegin: TimeInterval,
  917. timeEnd: TimeInterval,
  918. autotuned: Bool
  919. ) async -> [BasalProfile] {
  920. guard timeBegin < timeEnd else { return [] }
  921. let beginDate = Date(timeIntervalSince1970: timeBegin)
  922. let startOfDay = Calendar.current.startOfDay(for: beginDate)
  923. let profile = autotuned ? autotunedBasalProfile : basalProfile
  924. var basalPoints: [BasalProfile] = []
  925. // Iterate over the next three days, multiplying the time intervals
  926. for dayOffset in 0 ..< 3 {
  927. let dayTimeOffset = TimeInterval(dayOffset * 24 * 60 * 60) // One Day in seconds
  928. for entry in profile {
  929. let basalTime = startOfDay.addingTimeInterval(entry.minutes.minutes.timeInterval + dayTimeOffset)
  930. let basalTimeInterval = basalTime.timeIntervalSince1970
  931. // Only append points within the timeBegin and timeEnd range
  932. if basalTimeInterval >= timeBegin, basalTimeInterval < timeEnd {
  933. basalPoints.append(BasalProfile(
  934. amount: Double(entry.rate),
  935. isOverwritten: false,
  936. startDate: basalTime
  937. ))
  938. }
  939. }
  940. }
  941. return basalPoints
  942. }
  943. /// update start and end marker to fix scroll update problem with x axis
  944. private func updateStartEndMarkers() {
  945. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  946. let threeHourSinceNow = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  947. // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  948. let dynamicFutureDateForCone = Date(timeIntervalSinceNow: TimeInterval(
  949. Int(1.5) * 5 * state
  950. .minCount * 60
  951. ))
  952. endMarker = state
  953. .forecastDisplayType == .lines ? threeHourSinceNow : dynamicFutureDateForCone <= threeHourSinceNow ?
  954. dynamicFutureDateForCone.addingTimeInterval(TimeInterval(minutes: 30)) : threeHourSinceNow
  955. }
  956. private func calculateBasals() {
  957. Task {
  958. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  959. // Get Regular and Autotuned Basal parallel
  960. async let getRegularBasalPoints = findRegularBasalPoints(
  961. timeBegin: dayAgoTime,
  962. timeEnd: endMarker.timeIntervalSince1970,
  963. autotuned: false
  964. )
  965. async let getAutotunedBasalPoints = findRegularBasalPoints(
  966. timeBegin: dayAgoTime,
  967. timeEnd: endMarker.timeIntervalSince1970,
  968. autotuned: true
  969. )
  970. let (regularPoints, autotunedBasalPoints) = await (getRegularBasalPoints, getAutotunedBasalPoints)
  971. var totalBasal = regularPoints + autotunedBasalPoints
  972. totalBasal.sort {
  973. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  974. }
  975. var basals: [BasalProfile] = []
  976. totalBasal.indices.forEach { index in
  977. basals.append(BasalProfile(
  978. amount: totalBasal[index].amount,
  979. isOverwritten: totalBasal[index].isOverwritten,
  980. startDate: totalBasal[index].startDate,
  981. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  982. ))
  983. }
  984. await MainActor.run {
  985. basalProfiles = basals
  986. }
  987. }
  988. }
  989. // MARK: - Chart formatting
  990. private func yAxisChartData() {
  991. let glucoseMapped = state.glucoseFromPersistence.map { Decimal($0.glucose) }
  992. let forecastValues = state.preprocessedData.map { Decimal($0.forecastValue.value) }
  993. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max(),
  994. let minForecast = forecastValues.min(), let maxForecast = forecastValues.max()
  995. else {
  996. // default values
  997. minValue = 45 - 20
  998. maxValue = 270 + 50
  999. return
  1000. }
  1001. // Ensure maxForecast is not more than 100 over maxGlucose
  1002. let adjustedMaxForecast = min(maxForecast, maxGlucose + 100)
  1003. let minOverall = min(minGlucose, minForecast)
  1004. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  1005. minValue = minOverall - 50
  1006. maxValue = maxOverall + 80
  1007. }
  1008. private func yAxisChartDataCobChart() {
  1009. let cobMapped = state.enactedAndNonEnactedDeterminations.map { Decimal($0.cob) }
  1010. guard let maxCob = cobMapped.max() else {
  1011. // default values
  1012. minValueCobChart = 0
  1013. maxValueCobChart = 20
  1014. return
  1015. }
  1016. maxValueCobChart = maxCob == 0 ? 20 : maxCob +
  1017. 20 // 2 is added to the max of iob and to keep the 1:10 ratio we add 20 here
  1018. }
  1019. private func yAxisChartDataIobChart() {
  1020. let iobMapped = state.enactedAndNonEnactedDeterminations.compactMap { $0.iob?.decimalValue }
  1021. guard let minIob = iobMapped.min(), let maxIob = iobMapped.max() else {
  1022. // default values
  1023. minValueIobChart = 0
  1024. maxValueIobChart = 5
  1025. return
  1026. }
  1027. minValueIobChart = minIob // we need to set this here because IOB can also be negative
  1028. minValueCobChart = minIob < 0 ? minIob - 2 :
  1029. 0 // if there is negative IOB the COB-X-Axis should still align with the IOB-X-Axis; 2 is only subtracted to make the charts align
  1030. maxValueIobChart = maxIob + 2
  1031. }
  1032. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  1033. plotContent
  1034. .rotationEffect(.degrees(180))
  1035. .scaleEffect(x: -1, y: 1)
  1036. }
  1037. private var mainChartXAxis: some AxisContent {
  1038. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1039. if displayXgridLines {
  1040. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1041. } else {
  1042. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1043. }
  1044. }
  1045. }
  1046. private var basalChartXAxis: some AxisContent {
  1047. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1048. if displayXgridLines {
  1049. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1050. } else {
  1051. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1052. }
  1053. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  1054. .font(.footnote).foregroundStyle(Color.primary)
  1055. }
  1056. }
  1057. private var mainChartYAxis: some AxisContent {
  1058. AxisMarks(position: .trailing) { value in
  1059. if displayYgridLines {
  1060. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1061. } else {
  1062. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1063. }
  1064. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  1065. /// fix offset between the two charts...
  1066. if units == .mmolL {
  1067. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  1068. }
  1069. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  1070. }
  1071. }
  1072. }
  1073. private var cobChartYAxis: some AxisContent {
  1074. AxisMarks(position: .trailing) { _ in
  1075. if displayYgridLines {
  1076. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1077. } else {
  1078. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1079. }
  1080. }
  1081. }
  1082. }
  1083. struct LegendItem: View {
  1084. var color: Color
  1085. var label: String
  1086. var body: some View {
  1087. Group {
  1088. Circle().fill(color).frame(width: 8, height: 8)
  1089. Text(label)
  1090. .font(.system(size: 10, weight: .bold))
  1091. .foregroundColor(color)
  1092. }
  1093. }
  1094. }
  1095. extension Int16 {
  1096. var minutes: TimeInterval {
  1097. TimeInterval(self) * 60
  1098. }
  1099. }