MainChartView.swift 48 KB

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