MainChartView.swift 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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. // sort by date
  842. let sortedGlucose = state.glucoseFromPersistence
  843. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  844. var low = 0
  845. var high = sortedGlucose.count - 1
  846. var closestGlucose: GlucoseStored?
  847. // binary search to find next glucose
  848. while low <= high {
  849. let mid = low + (high - low) / 2
  850. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  851. if midTime == time {
  852. return sortedGlucose[mid]
  853. } else if midTime < time {
  854. low = mid + 1
  855. } else {
  856. high = mid - 1
  857. }
  858. // update if necessary
  859. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  860. closestGlucose = sortedGlucose[mid]
  861. }
  862. }
  863. return closestGlucose
  864. }
  865. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  866. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  867. }
  868. /// calculations for temp target bar mark
  869. private func calculateTTs() {
  870. var groupedPackages: [[TempTarget]] = []
  871. var currentPackage: [TempTarget] = []
  872. var calculatedTTs: [ChartTempTarget] = []
  873. for target in tempTargets {
  874. if target.duration > 0 {
  875. if !currentPackage.isEmpty {
  876. groupedPackages.append(currentPackage)
  877. currentPackage = []
  878. }
  879. currentPackage.append(target)
  880. } else {
  881. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  882. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  883. target.createdAt <= lastNonZeroTempTarget.createdAt
  884. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  885. {
  886. currentPackage.append(target)
  887. }
  888. }
  889. }
  890. }
  891. // appends last package, if exists
  892. if !currentPackage.isEmpty {
  893. groupedPackages.append(currentPackage)
  894. }
  895. for package in groupedPackages {
  896. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  897. continue
  898. }
  899. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  900. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  901. if let earliestCancelTarget = earliestCancelTarget {
  902. end = min(earliestCancelTarget.createdAt, end)
  903. }
  904. let now = Date()
  905. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  906. if firstNonZeroTarget.targetTop != nil {
  907. let targetTop = firstNonZeroTarget.targetTop ?? 0
  908. calculatedTTs
  909. .append(ChartTempTarget(
  910. amount: units == .mgdL ? targetTop : targetTop.asMmolL,
  911. start: firstNonZeroTarget.createdAt,
  912. end: end
  913. ))
  914. }
  915. }
  916. chartTempTargets = calculatedTTs
  917. }
  918. private func findRegularBasalPoints(
  919. timeBegin: TimeInterval,
  920. timeEnd: TimeInterval,
  921. autotuned: Bool
  922. ) async -> [BasalProfile] {
  923. guard timeBegin < timeEnd else { return [] }
  924. let beginDate = Date(timeIntervalSince1970: timeBegin)
  925. let startOfDay = Calendar.current.startOfDay(for: beginDate)
  926. let profile = autotuned ? autotunedBasalProfile : basalProfile
  927. var basalPoints: [BasalProfile] = []
  928. // Iterate over the next three days, multiplying the time intervals
  929. for dayOffset in 0 ..< 3 {
  930. let dayTimeOffset = TimeInterval(dayOffset * 24 * 60 * 60) // One Day in seconds
  931. for entry in profile {
  932. let basalTime = startOfDay.addingTimeInterval(entry.minutes.minutes.timeInterval + dayTimeOffset)
  933. let basalTimeInterval = basalTime.timeIntervalSince1970
  934. // Only append points within the timeBegin and timeEnd range
  935. if basalTimeInterval >= timeBegin, basalTimeInterval < timeEnd {
  936. basalPoints.append(BasalProfile(
  937. amount: Double(entry.rate),
  938. isOverwritten: false,
  939. startDate: basalTime
  940. ))
  941. }
  942. }
  943. }
  944. return basalPoints
  945. }
  946. /// update start and end marker to fix scroll update problem with x axis
  947. private func updateStartEndMarkers() {
  948. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  949. let threeHourSinceNow = Date(timeIntervalSinceNow: TimeInterval(hours: 3))
  950. // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  951. let dynamicFutureDateForCone = Date(timeIntervalSinceNow: TimeInterval(
  952. Int(1.5) * 5 * state
  953. .minCount * 60
  954. ))
  955. endMarker = state
  956. .forecastDisplayType == .lines ? threeHourSinceNow : dynamicFutureDateForCone <= threeHourSinceNow ?
  957. dynamicFutureDateForCone.addingTimeInterval(TimeInterval(minutes: 30)) : threeHourSinceNow
  958. }
  959. private func calculateBasals() {
  960. Task {
  961. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  962. // Get Regular and Autotuned Basal parallel
  963. async let getRegularBasalPoints = findRegularBasalPoints(
  964. timeBegin: dayAgoTime,
  965. timeEnd: endMarker.timeIntervalSince1970,
  966. autotuned: false
  967. )
  968. async let getAutotunedBasalPoints = findRegularBasalPoints(
  969. timeBegin: dayAgoTime,
  970. timeEnd: endMarker.timeIntervalSince1970,
  971. autotuned: true
  972. )
  973. let (regularPoints, autotunedBasalPoints) = await (getRegularBasalPoints, getAutotunedBasalPoints)
  974. var totalBasal = regularPoints + autotunedBasalPoints
  975. totalBasal.sort {
  976. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  977. }
  978. var basals: [BasalProfile] = []
  979. totalBasal.indices.forEach { index in
  980. basals.append(BasalProfile(
  981. amount: totalBasal[index].amount,
  982. isOverwritten: totalBasal[index].isOverwritten,
  983. startDate: totalBasal[index].startDate,
  984. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  985. ))
  986. }
  987. await MainActor.run {
  988. basalProfiles = basals
  989. }
  990. }
  991. }
  992. // MARK: - Chart formatting
  993. private func yAxisChartData() {
  994. let glucoseMapped = state.glucoseFromPersistence.map { Decimal($0.glucose) }
  995. let forecastValues = state.preprocessedData.map { Decimal($0.forecastValue.value) }
  996. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max(),
  997. let minForecast = forecastValues.min(), let maxForecast = forecastValues.max()
  998. else {
  999. // default values
  1000. minValue = 45 - 20
  1001. maxValue = 270 + 50
  1002. return
  1003. }
  1004. // Ensure maxForecast is not more than 100 over maxGlucose
  1005. let adjustedMaxForecast = min(maxForecast, maxGlucose + 100)
  1006. let minOverall = min(minGlucose, minForecast)
  1007. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  1008. minValue = minOverall - 50
  1009. maxValue = maxOverall + 80
  1010. }
  1011. private func yAxisChartDataCobChart() {
  1012. let cobMapped = state.enactedAndNonEnactedDeterminations.map { Decimal($0.cob) }
  1013. guard let maxCob = cobMapped.max() else {
  1014. // default values
  1015. minValueCobChart = 0
  1016. maxValueCobChart = 20
  1017. return
  1018. }
  1019. maxValueCobChart = maxCob == 0 ? 20 : maxCob +
  1020. 20 // 2 is added to the max of iob and to keep the 1:10 ratio we add 20 here
  1021. }
  1022. private func yAxisChartDataIobChart() {
  1023. let iobMapped = state.enactedAndNonEnactedDeterminations.compactMap { $0.iob?.decimalValue }
  1024. guard let minIob = iobMapped.min(), let maxIob = iobMapped.max() else {
  1025. // default values
  1026. minValueIobChart = 0
  1027. maxValueIobChart = 5
  1028. return
  1029. }
  1030. minValueIobChart = minIob // we need to set this here because IOB can also be negative
  1031. minValueCobChart = minIob < 0 ? minIob - 2 :
  1032. 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
  1033. maxValueIobChart = maxIob + 2
  1034. }
  1035. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  1036. plotContent
  1037. .rotationEffect(.degrees(180))
  1038. .scaleEffect(x: -1, y: 1)
  1039. }
  1040. private var mainChartXAxis: some AxisContent {
  1041. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1042. if displayXgridLines {
  1043. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1044. } else {
  1045. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1046. }
  1047. }
  1048. }
  1049. private var basalChartXAxis: some AxisContent {
  1050. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1051. if displayXgridLines {
  1052. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1053. } else {
  1054. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1055. }
  1056. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  1057. .font(.footnote).foregroundStyle(Color.primary)
  1058. }
  1059. }
  1060. private var mainChartYAxis: some AxisContent {
  1061. AxisMarks(position: .trailing) { value in
  1062. if displayYgridLines {
  1063. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1064. } else {
  1065. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1066. }
  1067. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  1068. /// fix offset between the two charts...
  1069. if units == .mmolL {
  1070. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  1071. }
  1072. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  1073. }
  1074. }
  1075. }
  1076. private var cobChartYAxis: some AxisContent {
  1077. AxisMarks(position: .trailing) { _ in
  1078. if displayYgridLines {
  1079. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1080. } else {
  1081. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1082. }
  1083. }
  1084. }
  1085. }
  1086. struct LegendItem: View {
  1087. var color: Color
  1088. var label: String
  1089. var body: some View {
  1090. Group {
  1091. Circle().fill(color).frame(width: 8, height: 8)
  1092. Text(label)
  1093. .font(.system(size: 10, weight: .bold))
  1094. .foregroundColor(color)
  1095. }
  1096. }
  1097. }
  1098. extension Int16 {
  1099. var minutes: TimeInterval {
  1100. TimeInterval(self) * 60
  1101. }
  1102. }