MainChartView.swift 50 KB

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