MainChartView.swift 52 KB

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