MainChartView.swift 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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. HStack {
  359. Image(systemName: "clock")
  360. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  361. .font(.body).bold()
  362. }.font(.body).padding(.bottom, 5)
  363. HStack {
  364. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  365. .bold()
  366. + Text(" \(units.rawValue)")
  367. }.foregroundStyle(
  368. Decimal(sgv) < lowGlucose ? Color
  369. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  370. ).font(.body)
  371. if let selectedIOBValue, let iob = selectedIOBValue.iob {
  372. HStack {
  373. Image(systemName: "syringe.fill").frame(width: 15)
  374. Text(bolusFormatter.string(from: iob) ?? "")
  375. .bold()
  376. + Text(NSLocalizedString(" U", comment: "Insulin unit"))
  377. }.foregroundStyle(Color.insulin).font(.body)
  378. }
  379. if let selectedCOBValue {
  380. HStack {
  381. Image(systemName: "fork.knife").frame(width: 15)
  382. Text(carbsFormatter.string(from: selectedCOBValue.cob as NSNumber) ?? "")
  383. .bold()
  384. + Text(NSLocalizedString(" g", comment: "gram of carbs"))
  385. }.foregroundStyle(Color.orange).font(.body)
  386. }
  387. }
  388. .padding()
  389. .background {
  390. RoundedRectangle(cornerRadius: 4)
  391. .fill(Color.chart.opacity(0.85))
  392. .shadow(color: Color.secondary, radius: 2)
  393. .overlay(
  394. RoundedRectangle(cornerRadius: 4)
  395. .stroke(Color.secondary, lineWidth: 2)
  396. )
  397. }
  398. }
  399. }
  400. private var basalChart: some View {
  401. VStack {
  402. Chart {
  403. drawStartRuleMark()
  404. drawEndRuleMark()
  405. drawCurrentTimeMarker()
  406. drawTempBasals(dummy: false)
  407. drawBasalProfile()
  408. drawSuspensions()
  409. }.onChange(of: state.tempBasals) { _ in
  410. calculateBasals()
  411. }
  412. .onChange(of: maxBasal) { _ in
  413. calculateBasals()
  414. }
  415. .onChange(of: autotunedBasalProfile) { _ in
  416. calculateBasals()
  417. }
  418. .onChange(of: didAppearTrigger) { _ in
  419. calculateBasals()
  420. }.onChange(of: basalProfile) { _ in
  421. calculateBasals()
  422. }
  423. .frame(minHeight: geo.size.height * 0.05)
  424. .frame(width: fullWidth(viewWidth: screenSize.width))
  425. .chartXScale(domain: startMarker ... endMarker)
  426. .chartXAxis { basalChartXAxis }
  427. .chartXAxis(.hidden)
  428. .chartYAxis(.hidden)
  429. .chartPlotStyle { basalChartPlotStyle($0) }
  430. }
  431. }
  432. private var iobChart: some View {
  433. VStack {
  434. Chart {
  435. drawIOB()
  436. if #available(iOS 17, *) {
  437. if let selectedIOBValue {
  438. PointMark(
  439. x: .value("Time", selectedIOBValue.deliverAt ?? now, unit: .minute),
  440. y: .value("Value", Int(truncating: selectedIOBValue.iob ?? 0))
  441. )
  442. .symbolSize(CGSize(width: 15, height: 15))
  443. .foregroundStyle(Color.darkerBlue.opacity(0.8))
  444. PointMark(
  445. x: .value("Time", selectedIOBValue.deliverAt ?? now, unit: .minute),
  446. y: .value("Value", Int(truncating: selectedIOBValue.iob ?? 0))
  447. )
  448. .symbolSize(CGSize(width: 6, height: 6))
  449. .foregroundStyle(Color.primary)
  450. }
  451. }
  452. }
  453. .frame(minHeight: geo.size.height * 0.12)
  454. .frame(width: fullWidth(viewWidth: screenSize.width))
  455. .chartXScale(domain: startMarker ... endMarker)
  456. .backport.chartXSelection(value: $selection)
  457. .chartXAxis { basalChartXAxis }
  458. .chartYAxis { cobChartYAxis }
  459. .chartYScale(domain: minValueIobChart ... maxValueIobChart)
  460. .chartYAxis(.hidden)
  461. }
  462. }
  463. private var cobChart: some View {
  464. Chart {
  465. drawCurrentTimeMarker()
  466. drawCOB(dummy: false)
  467. if #available(iOS 17, *) {
  468. if let selectedCOBValue {
  469. PointMark(
  470. x: .value("Time", selectedCOBValue.deliverAt ?? now, unit: .minute),
  471. y: .value("Value", selectedCOBValue.cob)
  472. )
  473. .symbolSize(CGSize(width: 15, height: 15))
  474. .foregroundStyle(Color.orange.opacity(0.8))
  475. PointMark(
  476. x: .value("Time", selectedCOBValue.deliverAt ?? now, unit: .minute),
  477. y: .value("Value", selectedCOBValue.cob)
  478. )
  479. .symbolSize(CGSize(width: 6, height: 6))
  480. .foregroundStyle(Color.primary)
  481. }
  482. }
  483. }
  484. .frame(minHeight: geo.size.height * 0.12)
  485. .frame(width: fullWidth(viewWidth: screenSize.width))
  486. .chartXScale(domain: startMarker ... endMarker)
  487. .backport.chartXSelection(value: $selection)
  488. .chartXAxis { basalChartXAxis }
  489. .chartYAxis { cobChartYAxis }
  490. .chartYScale(domain: minValueCobChart ... maxValueCobChart)
  491. }
  492. }
  493. // MARK: - Calculations
  494. extension MainChartView {
  495. private func drawBoluses() -> some ChartContent {
  496. ForEach(state.insulinFromPersistence) { insulin in
  497. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  498. let bolusDate = insulin.timestamp ?? Date()
  499. if amount != 0, let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)?.glucose {
  500. let yPosition = (Decimal(glucose) * conversionFactor) + bolusOffset
  501. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  502. PointMark(
  503. x: .value("Time", bolusDate, unit: .second),
  504. y: .value("Value", yPosition)
  505. )
  506. .symbol {
  507. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  508. }
  509. .annotation(position: .top) {
  510. Text(bolusFormatter.string(from: amount) ?? "")
  511. .font(.caption2)
  512. .foregroundStyle(Color.insulin)
  513. }
  514. }
  515. }
  516. }
  517. private func drawCarbs() -> some ChartContent {
  518. /// carbs
  519. ForEach(state.carbsFromPersistence) { carb in
  520. let carbAmount = carb.carbs
  521. let carbDate = carb.date ?? Date()
  522. if let glucose = timeToNearestGlucose(time: carbDate.timeIntervalSince1970)?.glucose {
  523. let yPosition = (Decimal(glucose) * conversionFactor) - bolusOffset
  524. let size = (Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale)
  525. let limitedSize = size > 30 ? 30 : size
  526. PointMark(
  527. x: .value("Time", carbDate, unit: .second),
  528. y: .value("Value", yPosition)
  529. )
  530. .symbol {
  531. Image(systemName: "arrowtriangle.down.fill").font(.system(size: limitedSize)).foregroundStyle(Color.orange)
  532. .rotationEffect(.degrees(180))
  533. }
  534. .annotation(position: .bottom) {
  535. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  536. .foregroundStyle(Color.orange)
  537. }
  538. }
  539. }
  540. }
  541. private func drawFpus() -> some ChartContent {
  542. /// fpus
  543. ForEach(state.fpusFromPersistence, id: \.id) { fpu in
  544. let fpuAmount = fpu.carbs
  545. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  546. let yPosition = minValue
  547. PointMark(
  548. x: .value("Time", fpu.date ?? Date(), unit: .second),
  549. y: .value("Value", yPosition)
  550. )
  551. .symbolSize(size)
  552. .foregroundStyle(Color.brown)
  553. }
  554. }
  555. private func drawGlucose(dummy _: Bool) -> some ChartContent {
  556. /// glucose point mark
  557. /// filtering for high and low bounds in settings
  558. ForEach(state.glucoseFromPersistence) { item in
  559. if smooth {
  560. if item.glucose > Int(highGlucose) {
  561. PointMark(
  562. x: .value("Time", item.date ?? Date(), unit: .second),
  563. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  564. ).foregroundStyle(Color.orange.gradient).symbolSize(20).interpolationMethod(.cardinal)
  565. } else if item.glucose < Int(lowGlucose) {
  566. PointMark(
  567. x: .value("Time", item.date ?? Date(), unit: .second),
  568. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  569. ).foregroundStyle(Color.red.gradient).symbolSize(20).interpolationMethod(.cardinal)
  570. } else {
  571. PointMark(
  572. x: .value("Time", item.date ?? Date(), unit: .second),
  573. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  574. ).foregroundStyle(Color.green.gradient).symbolSize(20).interpolationMethod(.cardinal)
  575. }
  576. } else {
  577. if item.glucose > Int(highGlucose) {
  578. PointMark(
  579. x: .value("Time", item.date ?? Date(), unit: .second),
  580. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  581. ).foregroundStyle(Color.orange.gradient).symbolSize(20)
  582. } else if item.glucose < Int(lowGlucose) {
  583. PointMark(
  584. x: .value("Time", item.date ?? Date(), unit: .second),
  585. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  586. ).foregroundStyle(Color.red.gradient).symbolSize(20)
  587. } else {
  588. PointMark(
  589. x: .value("Time", item.date ?? Date(), unit: .second),
  590. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  591. ).foregroundStyle(Color.green.gradient).symbolSize(20)
  592. }
  593. }
  594. }
  595. }
  596. private func timeForIndex(_ index: Int32) -> Date {
  597. let currentTime = Date()
  598. let timeInterval = TimeInterval(index * 300)
  599. return currentTime.addingTimeInterval(timeInterval)
  600. }
  601. private func drawForecastsCone() -> some ChartContent {
  602. // Draw AreaMark for the forecast bounds
  603. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  604. if index < state.minForecast.count, index < state.maxForecast.count {
  605. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index]) : Decimal(state.minForecast[index]).asMmolL
  606. let yMaxValue = units == .mgdL ? Decimal(state.maxForecast[index]) : Decimal(state.maxForecast[index]).asMmolL
  607. let xValue = timeForIndex(Int32(index))
  608. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  609. AreaMark(
  610. x: .value("Time", xValue),
  611. // maxValue is already parsed to user units, no need to parse
  612. yStart: .value("Min Value", yMinValue <= maxValue ? yMinValue : maxValue),
  613. yEnd: .value("Max Value", yMaxValue <= maxValue ? yMaxValue : maxValue)
  614. )
  615. .foregroundStyle(Color.blue.opacity(0.5))
  616. .interpolationMethod(.catmullRom)
  617. }
  618. }
  619. }
  620. }
  621. private func drawForecastsLines() -> some ChartContent {
  622. ForEach(state.preprocessedData, id: \.id) { tuple in
  623. let forecastValue = tuple.forecastValue
  624. let forecast = tuple.forecast
  625. let valueAsDecimal = Decimal(forecastValue.value)
  626. let displayValue = units == .mmolL ? valueAsDecimal.asMmolL : valueAsDecimal
  627. let xValue = timeForIndex(forecastValue.index)
  628. if xValue <= Date(timeIntervalSinceNow: TimeInterval(hours: 2.5)) {
  629. LineMark(
  630. x: .value("Time", xValue),
  631. y: .value("Value", displayValue)
  632. )
  633. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  634. }
  635. }
  636. }
  637. private func drawCurrentTimeMarker() -> some ChartContent {
  638. RuleMark(
  639. x: .value(
  640. "",
  641. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  642. unit: .second
  643. )
  644. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  645. }
  646. private func drawStartRuleMark() -> some ChartContent {
  647. RuleMark(
  648. x: .value(
  649. "",
  650. startMarker,
  651. unit: .second
  652. )
  653. ).foregroundStyle(Color.clear)
  654. }
  655. private func drawEndRuleMark() -> some ChartContent {
  656. RuleMark(
  657. x: .value(
  658. "",
  659. endMarker,
  660. unit: .second
  661. )
  662. ).foregroundStyle(Color.clear)
  663. }
  664. private func drawTempTargets() -> some ChartContent {
  665. /// temp targets
  666. ForEach(chartTempTargets, id: \.self) { target in
  667. let targetLimited = min(max(target.amount, 0), upperLimit)
  668. RuleMark(
  669. xStart: .value("Start", target.start),
  670. xEnd: .value("End", target.end),
  671. y: .value("Value", targetLimited)
  672. )
  673. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  674. }
  675. }
  676. private func drawActiveOverrides() -> some ChartContent {
  677. ForEach(state.overrides) { override in
  678. let start: Date = override.date ?? .distantPast
  679. let duration = state.calculateDuration(override: override)
  680. let end: Date = start.addingTimeInterval(duration)
  681. let target = state.calculateTarget(override: override)
  682. RuleMark(
  683. xStart: .value("Start", start, unit: .second),
  684. xEnd: .value("End", end, unit: .second),
  685. y: .value("Value", target)
  686. )
  687. .foregroundStyle(Color.purple.opacity(0.6))
  688. .lineStyle(.init(lineWidth: 8))
  689. // .annotation(position: .overlay, spacing: 0) {
  690. // if let name = override.name {
  691. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  692. // }
  693. // }
  694. }
  695. }
  696. private func drawOverrideRunStored() -> some ChartContent {
  697. ForEach(state.overrideRunStored) { overrideRunStored in
  698. let start: Date = overrideRunStored.startDate ?? .distantPast
  699. let end: Date = overrideRunStored.endDate ?? Date()
  700. let target = overrideRunStored.target?.decimalValue ?? 100
  701. RuleMark(
  702. xStart: .value("Start", start, unit: .second),
  703. xEnd: .value("End", end, unit: .second),
  704. y: .value("Value", target)
  705. )
  706. .foregroundStyle(Color.purple.opacity(0.4))
  707. .lineStyle(.init(lineWidth: 8))
  708. // .annotation(position: .bottom, spacing: 0) {
  709. // if let name = overrideRunStored.override?.name {
  710. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  711. // }
  712. // }
  713. }
  714. }
  715. private func drawManualGlucose() -> some ChartContent {
  716. /// manual glucose mark
  717. ForEach(state.manualGlucoseFromPersistence) { item in
  718. let manualGlucose = item.glucose
  719. PointMark(
  720. x: .value("Time", item.date ?? Date(), unit: .second),
  721. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  722. )
  723. .symbol {
  724. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  725. .foregroundStyle(.red)
  726. }
  727. }
  728. }
  729. private func drawSuspensions() -> some ChartContent {
  730. let suspensions = state.suspensions
  731. return ForEach(suspensions) { suspension in
  732. let now = Date()
  733. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  734. let suspensionEnd = min(
  735. (
  736. suspensions
  737. .first(where: {
  738. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  739. .timestamp
  740. ) ?? now,
  741. now
  742. )
  743. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  744. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  745. RectangleMark(
  746. xStart: .value("start", suspensionStart),
  747. xEnd: .value("end", suspensionEnd),
  748. yStart: .value("suspend-start", 0),
  749. yEnd: .value("suspend-end", suspensionMarkHeight)
  750. )
  751. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  752. }
  753. }
  754. }
  755. private func drawIOB() -> some ChartContent {
  756. ForEach(state.enactedAndNonEnactedDeterminations) { iob in
  757. let rawAmount = iob.iob?.doubleValue ?? 0
  758. let amount: Double = rawAmount > 0 ? rawAmount : rawAmount * 2 // weigh negative iob with factor 2
  759. let date: Date = iob.deliverAt ?? Date()
  760. LineMark(x: .value("Time", date), y: .value("Amount", amount))
  761. .foregroundStyle(Color.darkerBlue)
  762. AreaMark(x: .value("Time", date), y: .value("Amount", amount))
  763. .foregroundStyle(
  764. LinearGradient(
  765. gradient: Gradient(
  766. colors: [
  767. Color.darkerBlue.opacity(0.8),
  768. Color.darkerBlue.opacity(0.01)
  769. ]
  770. ),
  771. startPoint: .top,
  772. endPoint: .bottom
  773. )
  774. )
  775. }
  776. }
  777. private func drawCOB(dummy: Bool) -> some ChartContent {
  778. ForEach(state.enactedAndNonEnactedDeterminations) { cob in
  779. let amount = Int(cob.cob)
  780. let date: Date = cob.deliverAt ?? Date()
  781. if dummy {
  782. LineMark(x: .value("Time", date), y: .value("Value", amount))
  783. .foregroundStyle(Color.clear)
  784. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  785. Color.clear
  786. )
  787. } else {
  788. LineMark(x: .value("Time", date), y: .value("Value", amount))
  789. .foregroundStyle(Color.orange.gradient)
  790. AreaMark(x: .value("Time", date), y: .value("Value", amount)).foregroundStyle(
  791. LinearGradient(
  792. gradient: Gradient(
  793. colors: [
  794. Color.orange.opacity(0.8),
  795. Color.orange.opacity(0.01)
  796. ]
  797. ),
  798. startPoint: .top,
  799. endPoint: .bottom
  800. )
  801. )
  802. }
  803. }
  804. }
  805. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  806. let now = Date()
  807. let tempBasals = state.tempBasals
  808. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  809. let duration = temp.tempBasal?.duration ?? 0
  810. let timestamp = temp.timestamp ?? Date()
  811. let end = min(timestamp + duration.minutes, now)
  812. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  813. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  814. // Check if there's a subsequent temp basal to determine the end time
  815. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  816. return (timestamp, end, rate)
  817. }
  818. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  819. }
  820. }
  821. private func drawTempBasals(dummy: Bool) -> some ChartContent {
  822. ForEach(prepareTempBasals(), id: \.rate) { basal in
  823. if dummy {
  824. RectangleMark(
  825. xStart: .value("start", basal.start),
  826. xEnd: .value("end", basal.end),
  827. yStart: .value("rate-start", 0),
  828. yEnd: .value("rate-end", basal.rate)
  829. ).foregroundStyle(Color.clear)
  830. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  831. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  832. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  833. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.clear)
  834. } else {
  835. RectangleMark(
  836. xStart: .value("start", basal.start),
  837. xEnd: .value("end", basal.end),
  838. yStart: .value("rate-start", 0),
  839. yEnd: .value("rate-end", basal.rate)
  840. ).foregroundStyle(
  841. LinearGradient(
  842. gradient: Gradient(
  843. colors: [
  844. Color.insulin.opacity(0.6),
  845. Color.insulin.opacity(0.1)
  846. ]
  847. ),
  848. startPoint: .top,
  849. endPoint: .bottom
  850. )
  851. )
  852. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  853. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  854. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  855. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  856. }
  857. }
  858. }
  859. private func drawBasalProfile() -> some ChartContent {
  860. /// dashed profile line
  861. ForEach(basalProfiles, id: \.self) { profile in
  862. LineMark(
  863. x: .value("Start Date", profile.startDate),
  864. y: .value("Amount", profile.amount),
  865. series: .value("profile", "profile")
  866. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  867. LineMark(
  868. x: .value("End Date", profile.endDate ?? endMarker),
  869. y: .value("Amount", profile.amount),
  870. series: .value("profile", "profile")
  871. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  872. }
  873. }
  874. /// calculates the glucose value thats the nearest to parameter 'time'
  875. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  876. guard !state.glucoseFromPersistence.isEmpty else {
  877. return nil
  878. }
  879. // sort by date
  880. let sortedGlucose = state.glucoseFromPersistence
  881. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  882. var low = 0
  883. var high = sortedGlucose.count - 1
  884. var closestGlucose: GlucoseStored?
  885. // binary search to find next glucose
  886. while low <= high {
  887. let mid = low + (high - low) / 2
  888. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  889. if midTime == time {
  890. return sortedGlucose[mid]
  891. } else if midTime < time {
  892. low = mid + 1
  893. } else {
  894. high = mid - 1
  895. }
  896. // update if necessary
  897. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  898. closestGlucose = sortedGlucose[mid]
  899. }
  900. }
  901. return closestGlucose
  902. }
  903. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  904. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  905. }
  906. /// calculations for temp target bar mark
  907. private func calculateTTs() {
  908. var groupedPackages: [[TempTarget]] = []
  909. var currentPackage: [TempTarget] = []
  910. var calculatedTTs: [ChartTempTarget] = []
  911. for target in tempTargets {
  912. if target.duration > 0 {
  913. if !currentPackage.isEmpty {
  914. groupedPackages.append(currentPackage)
  915. currentPackage = []
  916. }
  917. currentPackage.append(target)
  918. } else {
  919. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  920. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  921. target.createdAt <= lastNonZeroTempTarget.createdAt
  922. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  923. {
  924. currentPackage.append(target)
  925. }
  926. }
  927. }
  928. }
  929. // appends last package, if exists
  930. if !currentPackage.isEmpty {
  931. groupedPackages.append(currentPackage)
  932. }
  933. for package in groupedPackages {
  934. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  935. continue
  936. }
  937. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  938. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  939. if let earliestCancelTarget = earliestCancelTarget {
  940. end = min(earliestCancelTarget.createdAt, end)
  941. }
  942. let now = Date()
  943. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  944. if firstNonZeroTarget.targetTop != nil {
  945. calculatedTTs
  946. .append(ChartTempTarget(
  947. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  948. start: firstNonZeroTarget.createdAt,
  949. end: end
  950. ))
  951. }
  952. }
  953. chartTempTargets = calculatedTTs
  954. }
  955. private func findRegularBasalPoints(
  956. timeBegin: TimeInterval,
  957. timeEnd: TimeInterval,
  958. autotuned: Bool
  959. ) -> [BasalProfile] {
  960. guard timeBegin < timeEnd else {
  961. return []
  962. }
  963. let beginDate = Date(timeIntervalSince1970: timeBegin)
  964. let calendar = Calendar.current
  965. let startOfDay = calendar.startOfDay(for: beginDate)
  966. let profile = autotuned ? autotunedBasalProfile : basalProfile
  967. let basalNormalized = profile.map {
  968. (
  969. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  970. rate: $0.rate
  971. )
  972. } + profile.map {
  973. (
  974. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  975. .timeIntervalSince1970,
  976. rate: $0.rate
  977. )
  978. } + profile.map {
  979. (
  980. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  981. .timeIntervalSince1970,
  982. rate: $0.rate
  983. )
  984. }
  985. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  986. .compactMap { window -> BasalProfile? in
  987. let window = Array(window)
  988. if window[0].time < timeBegin, window[1].time < timeBegin {
  989. return nil
  990. }
  991. if window[0].time < timeBegin, window[1].time >= timeBegin {
  992. let startDate = Date(timeIntervalSince1970: timeBegin)
  993. let rate = window[0].rate
  994. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  995. }
  996. if window[0].time >= timeBegin, window[0].time < timeEnd {
  997. let startDate = Date(timeIntervalSince1970: window[0].time)
  998. let rate = window[0].rate
  999. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  1000. }
  1001. return nil
  1002. }
  1003. return basalTruncatedPoints
  1004. }
  1005. /// update start and end marker to fix scroll update problem with x axis
  1006. private func updateStartEndMarkers() {
  1007. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  1008. // endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  1009. }
  1010. private func calculateBasals() {
  1011. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  1012. let regularPoints = findRegularBasalPoints(
  1013. timeBegin: dayAgoTime,
  1014. timeEnd: endMarker.timeIntervalSince1970,
  1015. autotuned: false
  1016. )
  1017. let autotunedBasalPoints = findRegularBasalPoints(
  1018. timeBegin: dayAgoTime,
  1019. timeEnd: endMarker.timeIntervalSince1970,
  1020. autotuned: true
  1021. )
  1022. var totalBasal = regularPoints + autotunedBasalPoints
  1023. totalBasal.sort {
  1024. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  1025. }
  1026. var basals: [BasalProfile] = []
  1027. totalBasal.indices.forEach { index in
  1028. basals.append(BasalProfile(
  1029. amount: totalBasal[index].amount,
  1030. isOverwritten: totalBasal[index].isOverwritten,
  1031. startDate: totalBasal[index].startDate,
  1032. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  1033. ))
  1034. }
  1035. basalProfiles = basals
  1036. }
  1037. // MARK: - Chart formatting
  1038. private func yAxisChartData() {
  1039. let glucoseMapped = state.glucoseFromPersistence.map { Decimal($0.glucose) }
  1040. let forecastValues = state.preprocessedData.map { Decimal($0.forecastValue.value) }
  1041. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max(),
  1042. let minForecast = forecastValues.min(), let maxForecast = forecastValues.max()
  1043. else {
  1044. // default values
  1045. minValue = 45 * conversionFactor - 20 * conversionFactor
  1046. maxValue = 270 * conversionFactor + 50 * conversionFactor
  1047. return
  1048. }
  1049. // Ensure maxForecast is not more than 100 over maxGlucose
  1050. let adjustedMaxForecast = min(maxForecast, maxGlucose + 100)
  1051. let minOverall = min(minGlucose, minForecast)
  1052. let maxOverall = max(maxGlucose, adjustedMaxForecast)
  1053. minValue = minOverall * conversionFactor - 50 * conversionFactor
  1054. maxValue = maxOverall * conversionFactor + 80 * conversionFactor
  1055. }
  1056. private func yAxisChartDataCobChart() {
  1057. let cobMapped = state.enactedAndNonEnactedDeterminations.map { Decimal($0.cob) }
  1058. guard let maxCob = cobMapped.max() else {
  1059. // default values
  1060. minValueCobChart = 0
  1061. maxValueCobChart = 20
  1062. return
  1063. }
  1064. maxValueCobChart = maxCob == 0 ? 20 : maxCob +
  1065. 20 // 2 is added to the max of iob and to keep the 1:10 ratio we add 20 here
  1066. }
  1067. private func yAxisChartDataIobChart() {
  1068. let iobMapped = state.enactedAndNonEnactedDeterminations.compactMap { $0.iob?.decimalValue }
  1069. guard let minIob = iobMapped.min(), let maxIob = iobMapped.max() else {
  1070. // default values
  1071. minValueIobChart = 0
  1072. maxValueIobChart = 5
  1073. return
  1074. }
  1075. minValueIobChart = minIob // we need to set this here because IOB can also be negative
  1076. minValueCobChart = minIob < 0 ? minIob - 2 :
  1077. 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
  1078. maxValueIobChart = maxIob + 2
  1079. }
  1080. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  1081. plotContent
  1082. .rotationEffect(.degrees(180))
  1083. .scaleEffect(x: -1, y: 1)
  1084. }
  1085. private var mainChartXAxis: some AxisContent {
  1086. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1087. if displayXgridLines {
  1088. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1089. } else {
  1090. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1091. }
  1092. }
  1093. }
  1094. private var basalChartXAxis: some AxisContent {
  1095. AxisMarks(values: .stride(by: .hour, count: screenHours > 6 ? (screenHours > 12 ? 4 : 2) : 1)) { _ in
  1096. if displayXgridLines {
  1097. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1098. } else {
  1099. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1100. }
  1101. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  1102. .font(.footnote).foregroundStyle(Color.primary)
  1103. }
  1104. }
  1105. private var mainChartYAxis: some AxisContent {
  1106. AxisMarks(position: .trailing) { value in
  1107. if displayXgridLines {
  1108. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1109. } else {
  1110. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1111. }
  1112. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  1113. /// fix offset between the two charts...
  1114. if units == .mmolL {
  1115. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  1116. }
  1117. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  1118. }
  1119. }
  1120. }
  1121. private var cobChartYAxis: some AxisContent {
  1122. AxisMarks(position: .trailing) { _ in
  1123. if displayXgridLines {
  1124. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  1125. } else {
  1126. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  1127. }
  1128. }
  1129. }
  1130. }
  1131. struct LegendItem: View {
  1132. var color: Color
  1133. var label: String
  1134. var body: some View {
  1135. Group {
  1136. Circle().fill(color).frame(width: 8, height: 8)
  1137. Text(label)
  1138. .font(.system(size: 10, weight: .bold))
  1139. .foregroundColor(color)
  1140. }
  1141. }
  1142. }
  1143. extension Int16 {
  1144. var minutes: TimeInterval {
  1145. TimeInterval(self) * 60
  1146. }
  1147. }