MainChartView.swift 49 KB

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