MainChartView.swift 50 KB

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