MainChartView.swift 50 KB

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