MainChartView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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. @Binding var units: GlucoseUnits
  34. @Binding var announcement: [Announcement]
  35. @Binding var hours: Int
  36. @Binding var maxBasal: Decimal
  37. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  38. @Binding var basalProfile: [BasalProfileEntry]
  39. @Binding var tempTargets: [TempTarget]
  40. @Binding var smooth: Bool
  41. @Binding var highGlucose: Decimal
  42. @Binding var lowGlucose: Decimal
  43. @Binding var screenHours: Int16
  44. @Binding var displayXgridLines: Bool
  45. @Binding var displayYgridLines: Bool
  46. @Binding var thresholdLines: Bool
  47. @Binding var isTempTargetActive: Bool
  48. @StateObject var state: Home.StateModel
  49. @State var didAppearTrigger = false
  50. @State private var basalProfiles: [BasalProfile] = []
  51. @State private var chartTempTargets: [ChartTempTarget] = []
  52. @State private var count: Decimal = 1
  53. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  54. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  55. @State private var minValue: Decimal = 45
  56. @State private var maxValue: Decimal = 270
  57. @State private var selection: Date? = nil
  58. private let now = Date.now
  59. private let context = CoreDataStack.shared.persistentContainer.viewContext
  60. @Environment(\.colorScheme) var colorScheme
  61. @Environment(\.calendar) var calendar
  62. private var bolusFormatter: NumberFormatter {
  63. let formatter = NumberFormatter()
  64. formatter.numberStyle = .decimal
  65. formatter.minimumIntegerDigits = 0
  66. formatter.maximumFractionDigits = 2
  67. formatter.decimalSeparator = "."
  68. return formatter
  69. }
  70. private var carbsFormatter: NumberFormatter {
  71. let formatter = NumberFormatter()
  72. formatter.numberStyle = .decimal
  73. formatter.maximumFractionDigits = 0
  74. return formatter
  75. }
  76. private var conversionFactor: Decimal {
  77. units == .mmolL ? 0.0555 : 1
  78. }
  79. private var upperLimit: Decimal {
  80. units == .mgdL ? 400 : 22.2
  81. }
  82. private var defaultBolusPosition: Int {
  83. units == .mgdL ? 120 : 7
  84. }
  85. private var bolusOffset: Decimal {
  86. units == .mgdL ? 30 : 1.66
  87. }
  88. private var selectedGlucose: GlucoseStored? {
  89. if let selection = selection {
  90. let lowerBound = selection.addingTimeInterval(-120)
  91. let upperBound = selection.addingTimeInterval(120)
  92. return state.glucoseFromPersistence.first { $0.date ?? now >= lowerBound && $0.date ?? now <= upperBound }
  93. } else {
  94. return nil
  95. }
  96. }
  97. var body: some View {
  98. VStack {
  99. ZStack {
  100. VStack {
  101. staticYAxisChart
  102. dummyBasalChart
  103. }
  104. ScrollViewReader { scroller in
  105. ScrollView(.horizontal, showsIndicators: false) {
  106. VStack(spacing: 0) {
  107. mainChart
  108. basalChart
  109. }.onChange(of: screenHours) { _ in
  110. updateStartEndMarkers()
  111. yAxisChartData()
  112. scroller.scrollTo("MainChart", anchor: .trailing)
  113. }
  114. .onChange(of: state.glucoseFromPersistence.last?.glucose) { _ in
  115. updateStartEndMarkers()
  116. yAxisChartData()
  117. scroller.scrollTo("MainChart", anchor: .trailing)
  118. }
  119. .onChange(of: state.determinationsFromPersistence.last?.deliverAt) { _ in
  120. updateStartEndMarkers()
  121. scroller.scrollTo("MainChart", anchor: .trailing)
  122. }
  123. .onChange(of: state.tempBasals) { _ in
  124. updateStartEndMarkers()
  125. scroller.scrollTo("MainChart", anchor: .trailing)
  126. }
  127. .onChange(of: units) { _ in
  128. yAxisChartData()
  129. }
  130. .onAppear {
  131. updateStartEndMarkers()
  132. scroller.scrollTo("MainChart", anchor: .trailing)
  133. }
  134. }
  135. }
  136. }
  137. }
  138. }
  139. }
  140. // MARK: - Components
  141. struct Backport<Content: View> {
  142. let content: Content
  143. }
  144. extension View {
  145. var backport: Backport<Self> { Backport(content: self) }
  146. }
  147. extension Backport {
  148. @ViewBuilder func chartXSelection(value: Binding<Date?>) -> some View {
  149. if #available(iOS 17, *) {
  150. content.chartXSelection(value: value)
  151. } else {
  152. content
  153. }
  154. }
  155. }
  156. extension MainChartView {
  157. /// 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
  158. private var staticYAxisChart: some View {
  159. Chart {
  160. /// high and low threshold lines
  161. if thresholdLines {
  162. RuleMark(y: .value("High", highGlucose * conversionFactor)).foregroundStyle(Color.loopYellow)
  163. .lineStyle(.init(lineWidth: 1, dash: [5]))
  164. RuleMark(y: .value("Low", lowGlucose * conversionFactor)).foregroundStyle(Color.loopRed)
  165. .lineStyle(.init(lineWidth: 1, dash: [5]))
  166. }
  167. }
  168. .id("DummyMainChart")
  169. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  170. .frame(width: screenSize.width - 10)
  171. .chartYAxis { mainChartYAxis }
  172. .chartXAxis(.hidden)
  173. .chartYScale(domain: minValue ... maxValue)
  174. .chartLegend(.hidden)
  175. }
  176. private var dummyBasalChart: some View {
  177. Chart {}
  178. .id("DummyBasalChart")
  179. .frame(height: UIScreen.main.bounds.height * 0.08)
  180. .frame(width: screenSize.width - 10)
  181. .chartYAxis(.hidden)
  182. .chartXAxis(.hidden)
  183. .chartYScale(domain: minValue ... maxValue)
  184. .chartLegend(.hidden)
  185. }
  186. private var mainChart: some View {
  187. VStack {
  188. Chart {
  189. drawStartRuleMark()
  190. drawEndRuleMark()
  191. drawCurrentTimeMarker()
  192. drawCarbs()
  193. drawFpus()
  194. drawBoluses()
  195. drawTempTargets()
  196. drawActiveOverrides()
  197. drawOverrideRunStored()
  198. drawForecasts()
  199. drawGlucose()
  200. drawManualGlucose()
  201. /// show glucose value when hovering over it
  202. if let selectedGlucose {
  203. RuleMark(x: .value("Selection", selectedGlucose.date ?? now, unit: .minute))
  204. .foregroundStyle(Color.tabBar)
  205. .offset(yStart: 70)
  206. .lineStyle(.init(lineWidth: 2, dash: [5]))
  207. .annotation(position: .top) {
  208. selectionPopover
  209. }
  210. }
  211. }
  212. .id("MainChart")
  213. .onChange(of: state.insulinFromPersistence) { _ in
  214. state.roundedTotalBolus = state.calculateTINS()
  215. }
  216. .onChange(of: tempTargets) { _ in
  217. calculateTTs()
  218. }
  219. .onChange(of: didAppearTrigger) { _ in
  220. calculateTTs()
  221. }
  222. .frame(minHeight: UIScreen.main.bounds.height * 0.2)
  223. .frame(width: fullWidth(viewWidth: screenSize.width))
  224. .chartXScale(domain: startMarker ... endMarker)
  225. .chartXAxis { mainChartXAxis }
  226. .chartYAxis(.hidden)
  227. .backport.chartXSelection(value: $selection)
  228. .chartYScale(domain: minValue ... maxValue)
  229. .chartForegroundStyleScale([
  230. "zt": Color.zt,
  231. "uam": Color.uam,
  232. "cob": .orange,
  233. "iob": .blue
  234. ])
  235. .chartLegend(.hidden)
  236. }
  237. }
  238. @ViewBuilder var selectionPopover: some View {
  239. if let sgv = selectedGlucose?.glucose {
  240. let glucoseToShow = Decimal(sgv) * conversionFactor
  241. VStack {
  242. Text(selectedGlucose?.date?.formatted(.dateTime.hour().minute(.twoDigits)) ?? "")
  243. HStack {
  244. Text(glucoseToShow.formatted(.number.precision(units == .mmolL ? .fractionLength(1) : .fractionLength(0))))
  245. .fontWeight(.bold)
  246. .foregroundStyle(
  247. Decimal(sgv) < lowGlucose ? Color
  248. .red : (Decimal(sgv) > highGlucose ? Color.orange : Color.primary)
  249. )
  250. Text(units.rawValue).foregroundColor(.secondary)
  251. }
  252. }
  253. .padding(6)
  254. .background {
  255. RoundedRectangle(cornerRadius: 4)
  256. .fill(Color.gray.opacity(0.1))
  257. .shadow(color: .blue, radius: 2)
  258. }
  259. }
  260. }
  261. private var basalChart: some View {
  262. VStack {
  263. Chart {
  264. drawStartRuleMark()
  265. drawEndRuleMark()
  266. drawCurrentTimeMarker()
  267. drawTempBasals()
  268. drawBasalProfile()
  269. drawSuspensions()
  270. }.onChange(of: state.tempBasals) { _ in
  271. calculateBasals()
  272. }
  273. .onChange(of: maxBasal) { _ in
  274. calculateBasals()
  275. }
  276. .onChange(of: autotunedBasalProfile) { _ in
  277. calculateBasals()
  278. }
  279. .onChange(of: didAppearTrigger) { _ in
  280. calculateBasals()
  281. }.onChange(of: basalProfile) { _ in
  282. calculateBasals()
  283. }
  284. .frame(height: UIScreen.main.bounds.height * 0.08)
  285. .frame(width: fullWidth(viewWidth: screenSize.width))
  286. .chartXScale(domain: startMarker ... endMarker)
  287. .chartXAxis { basalChartXAxis }
  288. .chartYAxis(.hidden)
  289. }
  290. }
  291. }
  292. // MARK: - Calculations
  293. extension MainChartView {
  294. private func drawBoluses() -> some ChartContent {
  295. ForEach(state.insulinFromPersistence) { insulin in
  296. let amount = insulin.bolus?.amount ?? 0 as NSDecimalNumber
  297. let bolusDate = insulin.timestamp ?? Date()
  298. if amount != 0, let glucose = timeToNearestGlucose(time: bolusDate.timeIntervalSince1970)?.glucose {
  299. let yPosition = (Decimal(glucose) * conversionFactor) + bolusOffset
  300. let size = (Config.bolusSize + CGFloat(truncating: amount) * Config.bolusScale) * 1.8
  301. PointMark(
  302. x: .value("Time", bolusDate, unit: .second),
  303. y: .value("Value", yPosition)
  304. )
  305. .symbol {
  306. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size)).foregroundStyle(Color.insulin)
  307. }
  308. .annotation(position: .top) {
  309. Text(bolusFormatter.string(from: amount) ?? "")
  310. .font(.caption2)
  311. .foregroundStyle(Color.insulin)
  312. }
  313. }
  314. }
  315. }
  316. private func drawCarbs() -> some ChartContent {
  317. /// carbs
  318. ForEach(state.carbsFromPersistence) { carb in
  319. let carbAmount = carb.carbs
  320. let yPosition = units == .mgdL ? 60 : 3.33
  321. PointMark(
  322. x: .value("Time", carb.date ?? Date(), unit: .second),
  323. y: .value("Value", yPosition)
  324. )
  325. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  326. .foregroundStyle(Color.orange)
  327. .annotation(position: .bottom) {
  328. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  329. .foregroundStyle(Color.orange)
  330. }
  331. }
  332. }
  333. private func drawFpus() -> some ChartContent {
  334. /// fpus
  335. ForEach(state.fpusFromPersistence, id: \.id) { fpu in
  336. let fpuAmount = fpu.carbs
  337. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  338. let yPosition = units == .mgdL ? 60 : 3.33
  339. PointMark(
  340. x: .value("Time", fpu.date ?? Date(), unit: .second),
  341. y: .value("Value", yPosition)
  342. )
  343. .symbolSize(size)
  344. .foregroundStyle(Color.brown)
  345. }
  346. }
  347. private func drawGlucose() -> some ChartContent {
  348. /// glucose point mark
  349. /// filtering for high and low bounds in settings
  350. ForEach(state.glucoseFromPersistence) { item in
  351. if smooth {
  352. if item.glucose > Int(highGlucose) {
  353. PointMark(
  354. x: .value("Time", item.date ?? Date(), unit: .second),
  355. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  356. ).foregroundStyle(Color.orange.gradient).symbolSize(25).interpolationMethod(.cardinal)
  357. } else if item.glucose < Int(lowGlucose) {
  358. PointMark(
  359. x: .value("Time", item.date ?? Date(), unit: .second),
  360. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  361. ).foregroundStyle(Color.red.gradient).symbolSize(25).interpolationMethod(.cardinal)
  362. } else {
  363. PointMark(
  364. x: .value("Time", item.date ?? Date(), unit: .second),
  365. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  366. ).foregroundStyle(Color.green.gradient).symbolSize(25).interpolationMethod(.cardinal)
  367. }
  368. } else {
  369. if item.glucose > Int(highGlucose) {
  370. PointMark(
  371. x: .value("Time", item.date ?? Date(), unit: .second),
  372. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  373. ).foregroundStyle(Color.orange.gradient).symbolSize(25)
  374. } else if item.glucose < Int(lowGlucose) {
  375. PointMark(
  376. x: .value("Time", item.date ?? Date(), unit: .second),
  377. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  378. ).foregroundStyle(Color.red.gradient).symbolSize(25)
  379. } else {
  380. PointMark(
  381. x: .value("Time", item.date ?? Date(), unit: .second),
  382. y: .value("Value", Decimal(item.glucose) * conversionFactor)
  383. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  384. }
  385. }
  386. }
  387. }
  388. private func timeForIndex(_ index: Int32) -> Date {
  389. let currentTime = Date()
  390. let timeInterval = TimeInterval(index * 300)
  391. return currentTime.addingTimeInterval(timeInterval)
  392. }
  393. private func drawForecasts() -> some ChartContent {
  394. ForEach(state.preprocessedData, id: \.id) { tuple in
  395. let forecastValue = tuple.forecastValue
  396. let forecast = tuple.forecast
  397. LineMark(
  398. x: .value("Time", timeForIndex(forecastValue.index)),
  399. y: .value("Value", Int(forecastValue.value))
  400. )
  401. .foregroundStyle(by: .value("Predictions", forecast.type ?? ""))
  402. }
  403. }
  404. private func drawCurrentTimeMarker() -> some ChartContent {
  405. RuleMark(
  406. x: .value(
  407. "",
  408. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  409. unit: .second
  410. )
  411. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  412. }
  413. private func drawStartRuleMark() -> some ChartContent {
  414. RuleMark(
  415. x: .value(
  416. "",
  417. startMarker,
  418. unit: .second
  419. )
  420. ).foregroundStyle(Color.clear)
  421. }
  422. private func drawEndRuleMark() -> some ChartContent {
  423. RuleMark(
  424. x: .value(
  425. "",
  426. endMarker,
  427. unit: .second
  428. )
  429. ).foregroundStyle(Color.clear)
  430. }
  431. private func drawTempTargets() -> some ChartContent {
  432. /// temp targets
  433. ForEach(chartTempTargets, id: \.self) { target in
  434. let targetLimited = min(max(target.amount, 0), upperLimit)
  435. RuleMark(
  436. xStart: .value("Start", target.start),
  437. xEnd: .value("End", target.end),
  438. y: .value("Value", targetLimited)
  439. )
  440. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  441. }
  442. }
  443. private func drawActiveOverrides() -> some ChartContent {
  444. ForEach(state.overrides) { override in
  445. let start: Date = override.date ?? .distantPast
  446. let duration = state.calculateDuration(override: override)
  447. let end: Date = start.addingTimeInterval(duration)
  448. let target = state.calculateTarget(override: override)
  449. RuleMark(
  450. xStart: .value("Start", start, unit: .second),
  451. xEnd: .value("End", end, unit: .second),
  452. y: .value("Value", target)
  453. )
  454. .foregroundStyle(Color.purple.opacity(0.6))
  455. .lineStyle(.init(lineWidth: 8))
  456. // .annotation(position: .overlay, spacing: 0) {
  457. // if let name = override.name {
  458. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  459. // }
  460. // }
  461. }
  462. }
  463. private func drawOverrideRunStored() -> some ChartContent {
  464. ForEach(state.overrideRunStored) { overrideRunStored in
  465. let start: Date = overrideRunStored.startDate ?? .distantPast
  466. let end: Date = overrideRunStored.endDate ?? Date()
  467. let target = overrideRunStored.target?.decimalValue ?? 100
  468. RuleMark(
  469. xStart: .value("Start", start, unit: .second),
  470. xEnd: .value("End", end, unit: .second),
  471. y: .value("Value", target)
  472. )
  473. .foregroundStyle(Color.purple.opacity(0.4))
  474. .lineStyle(.init(lineWidth: 8))
  475. // .annotation(position: .bottom, spacing: 0) {
  476. // if let name = overrideRunStored.override?.name {
  477. // Text("\(name)").foregroundStyle(.secondary).font(.footnote)
  478. // }
  479. // }
  480. }
  481. }
  482. private func drawManualGlucose() -> some ChartContent {
  483. /// manual glucose mark
  484. ForEach(state.manualGlucoseFromPersistence) { item in
  485. let manualGlucose = item.glucose
  486. PointMark(
  487. x: .value("Time", item.date ?? Date(), unit: .second),
  488. y: .value("Value", Decimal(manualGlucose) * conversionFactor)
  489. )
  490. .symbol {
  491. Image(systemName: "drop.fill").font(.system(size: 10)).symbolRenderingMode(.monochrome)
  492. .foregroundStyle(.red)
  493. }
  494. }
  495. }
  496. private func drawSuspensions() -> some ChartContent {
  497. let suspensions = state.suspensions
  498. return ForEach(suspensions) { suspension in
  499. let now = Date()
  500. if let type = suspension.type, type == EventType.pumpSuspend.rawValue, let suspensionStart = suspension.timestamp {
  501. let suspensionEnd = min(
  502. (
  503. suspensions
  504. .first(where: {
  505. $0.timestamp ?? now > suspensionStart && $0.type == EventType.pumpResume.rawValue })?
  506. .timestamp
  507. ) ?? now,
  508. now
  509. )
  510. let basalProfileDuringSuspension = basalProfiles.first(where: { $0.startDate <= suspensionStart })
  511. let suspensionMarkHeight = basalProfileDuringSuspension?.amount ?? 1
  512. RectangleMark(
  513. xStart: .value("start", suspensionStart),
  514. xEnd: .value("end", suspensionEnd),
  515. yStart: .value("suspend-start", 0),
  516. yEnd: .value("suspend-end", suspensionMarkHeight)
  517. )
  518. .foregroundStyle(Color.loopGray.opacity(colorScheme == .dark ? 0.3 : 0.8))
  519. }
  520. }
  521. }
  522. private func prepareTempBasals() -> [(start: Date, end: Date, rate: Double)] {
  523. let now = Date()
  524. let tempBasals = state.tempBasals
  525. return tempBasals.compactMap { temp -> (start: Date, end: Date, rate: Double)? in
  526. let duration = temp.tempBasal?.duration ?? 0
  527. let timestamp = temp.timestamp ?? Date()
  528. let end = min(timestamp + duration.minutes, now)
  529. let isInsulinSuspended = state.suspensions.contains { $0.timestamp ?? now >= timestamp && $0.timestamp ?? now <= end }
  530. let rate = Double(truncating: temp.tempBasal?.rate ?? Decimal.zero as NSDecimalNumber) * (isInsulinSuspended ? 0 : 1)
  531. // Check if there's a subsequent temp basal to determine the end time
  532. guard let nextTemp = state.tempBasals.first(where: { $0.timestamp ?? .distantPast > timestamp }) else {
  533. return (timestamp, end, rate)
  534. }
  535. return (timestamp, nextTemp.timestamp ?? Date(), rate) // end defaults to current time
  536. }
  537. }
  538. private func drawTempBasals() -> some ChartContent {
  539. ForEach(prepareTempBasals(), id: \.rate) { basal in
  540. RectangleMark(
  541. xStart: .value("start", basal.start),
  542. xEnd: .value("end", basal.end),
  543. yStart: .value("rate-start", 0),
  544. yEnd: .value("rate-end", basal.rate)
  545. ).foregroundStyle(Color.insulin.opacity(0.2))
  546. LineMark(x: .value("Start Date", basal.start), y: .value("Amount", basal.rate))
  547. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  548. LineMark(x: .value("End Date", basal.end), y: .value("Amount", basal.rate))
  549. .lineStyle(.init(lineWidth: 1)).foregroundStyle(Color.insulin)
  550. }
  551. }
  552. private func drawBasalProfile() -> some ChartContent {
  553. /// dashed profile line
  554. ForEach(basalProfiles, id: \.self) { profile in
  555. LineMark(
  556. x: .value("Start Date", profile.startDate),
  557. y: .value("Amount", profile.amount),
  558. series: .value("profile", "profile")
  559. ).lineStyle(.init(lineWidth: 2, dash: [2, 4])).foregroundStyle(Color.insulin)
  560. LineMark(
  561. x: .value("End Date", profile.endDate ?? endMarker),
  562. y: .value("Amount", profile.amount),
  563. series: .value("profile", "profile")
  564. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 4])).foregroundStyle(Color.insulin)
  565. }
  566. }
  567. /// calculates the glucose value thats the nearest to parameter 'time'
  568. private func timeToNearestGlucose(time: TimeInterval) -> GlucoseStored? {
  569. guard !state.glucoseFromPersistence.isEmpty else {
  570. return nil
  571. }
  572. // sort by date
  573. let sortedGlucose = state.glucoseFromPersistence
  574. .sorted { $0.date?.timeIntervalSince1970 ?? 0 < $1.date?.timeIntervalSince1970 ?? 0 }
  575. var low = 0
  576. var high = sortedGlucose.count - 1
  577. var closestGlucose: GlucoseStored?
  578. // binary search to find next glucose
  579. while low <= high {
  580. let mid = low + (high - low) / 2
  581. let midTime = sortedGlucose[mid].date?.timeIntervalSince1970 ?? 0
  582. if midTime == time {
  583. return sortedGlucose[mid]
  584. } else if midTime < time {
  585. low = mid + 1
  586. } else {
  587. high = mid - 1
  588. }
  589. // update if necessary
  590. if closestGlucose == nil || abs(midTime - time) < abs(closestGlucose!.date?.timeIntervalSince1970 ?? 0 - time) {
  591. closestGlucose = sortedGlucose[mid]
  592. }
  593. }
  594. return closestGlucose
  595. }
  596. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  597. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  598. }
  599. /// calculations for temp target bar mark
  600. private func calculateTTs() {
  601. var groupedPackages: [[TempTarget]] = []
  602. var currentPackage: [TempTarget] = []
  603. var calculatedTTs: [ChartTempTarget] = []
  604. for target in tempTargets {
  605. if target.duration > 0 {
  606. if !currentPackage.isEmpty {
  607. groupedPackages.append(currentPackage)
  608. currentPackage = []
  609. }
  610. currentPackage.append(target)
  611. } else {
  612. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  613. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  614. target.createdAt <= lastNonZeroTempTarget.createdAt
  615. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  616. {
  617. currentPackage.append(target)
  618. }
  619. }
  620. }
  621. }
  622. // appends last package, if exists
  623. if !currentPackage.isEmpty {
  624. groupedPackages.append(currentPackage)
  625. }
  626. for package in groupedPackages {
  627. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  628. continue
  629. }
  630. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  631. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  632. if let earliestCancelTarget = earliestCancelTarget {
  633. end = min(earliestCancelTarget.createdAt, end)
  634. }
  635. let now = Date()
  636. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  637. if firstNonZeroTarget.targetTop != nil {
  638. calculatedTTs
  639. .append(ChartTempTarget(
  640. amount: (firstNonZeroTarget.targetTop ?? 0) * conversionFactor,
  641. start: firstNonZeroTarget.createdAt,
  642. end: end
  643. ))
  644. }
  645. }
  646. chartTempTargets = calculatedTTs
  647. }
  648. private func findRegularBasalPoints(
  649. timeBegin: TimeInterval,
  650. timeEnd: TimeInterval,
  651. autotuned: Bool
  652. ) -> [BasalProfile] {
  653. guard timeBegin < timeEnd else {
  654. return []
  655. }
  656. let beginDate = Date(timeIntervalSince1970: timeBegin)
  657. let calendar = Calendar.current
  658. let startOfDay = calendar.startOfDay(for: beginDate)
  659. let profile = autotuned ? autotunedBasalProfile : basalProfile
  660. let basalNormalized = profile.map {
  661. (
  662. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  663. rate: $0.rate
  664. )
  665. } + profile.map {
  666. (
  667. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  668. .timeIntervalSince1970,
  669. rate: $0.rate
  670. )
  671. } + profile.map {
  672. (
  673. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  674. .timeIntervalSince1970,
  675. rate: $0.rate
  676. )
  677. }
  678. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  679. .compactMap { window -> BasalProfile? in
  680. let window = Array(window)
  681. if window[0].time < timeBegin, window[1].time < timeBegin {
  682. return nil
  683. }
  684. if window[0].time < timeBegin, window[1].time >= timeBegin {
  685. let startDate = Date(timeIntervalSince1970: timeBegin)
  686. let rate = window[0].rate
  687. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  688. }
  689. if window[0].time >= timeBegin, window[0].time < timeEnd {
  690. let startDate = Date(timeIntervalSince1970: window[0].time)
  691. let rate = window[0].rate
  692. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  693. }
  694. return nil
  695. }
  696. return basalTruncatedPoints
  697. }
  698. /// update start and end marker to fix scroll update problem with x axis
  699. private func updateStartEndMarkers() {
  700. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  701. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  702. }
  703. private func calculateBasals() {
  704. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  705. let regularPoints = findRegularBasalPoints(
  706. timeBegin: dayAgoTime,
  707. timeEnd: endMarker.timeIntervalSince1970,
  708. autotuned: false
  709. )
  710. let autotunedBasalPoints = findRegularBasalPoints(
  711. timeBegin: dayAgoTime,
  712. timeEnd: endMarker.timeIntervalSince1970,
  713. autotuned: true
  714. )
  715. var totalBasal = regularPoints + autotunedBasalPoints
  716. totalBasal.sort {
  717. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  718. }
  719. var basals: [BasalProfile] = []
  720. totalBasal.indices.forEach { index in
  721. basals.append(BasalProfile(
  722. amount: totalBasal[index].amount,
  723. isOverwritten: totalBasal[index].isOverwritten,
  724. startDate: totalBasal[index].startDate,
  725. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  726. ))
  727. }
  728. basalProfiles = basals
  729. }
  730. // MARK: - Chart formatting
  731. private func yAxisChartData() {
  732. let glucoseMapped = state.glucoseFromPersistence.map(\.glucose)
  733. guard let minGlucose = glucoseMapped.min(), let maxGlucose = glucoseMapped.max() else {
  734. // default values
  735. minValue = 45 * conversionFactor - 20 * conversionFactor
  736. maxValue = 270 * conversionFactor + 50 * conversionFactor
  737. return
  738. }
  739. minValue = Decimal(minGlucose) * conversionFactor - 20 * conversionFactor
  740. maxValue = Decimal(maxGlucose) * conversionFactor + 50 * conversionFactor
  741. debug(.default, "min \(minValue)")
  742. debug(.default, "max \(maxValue)")
  743. }
  744. private func basalChartPlotStyle(_ plotContent: ChartPlotContent) -> some View {
  745. plotContent
  746. .rotationEffect(.degrees(180))
  747. .scaleEffect(x: -1, y: 1)
  748. .chartXAxis(.hidden)
  749. }
  750. private var mainChartXAxis: some AxisContent {
  751. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  752. if displayXgridLines {
  753. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  754. } else {
  755. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  756. }
  757. }
  758. }
  759. private var basalChartXAxis: some AxisContent {
  760. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  761. if displayXgridLines {
  762. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  763. } else {
  764. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  765. }
  766. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  767. .font(.footnote)
  768. }
  769. }
  770. private var mainChartYAxis: some AxisContent {
  771. AxisMarks(position: .trailing) { value in
  772. if displayXgridLines {
  773. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  774. } else {
  775. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  776. }
  777. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  778. /// fix offset between the two charts...
  779. if units == .mmolL {
  780. AxisTick(length: 7, stroke: .init(lineWidth: 7)).foregroundStyle(Color.clear)
  781. }
  782. AxisValueLabel().font(.footnote)
  783. }
  784. }
  785. }
  786. }
  787. struct LegendItem: View {
  788. var color: Color
  789. var label: String
  790. var body: some View {
  791. Group {
  792. Circle().fill(color).frame(width: 8, height: 8)
  793. Text(label)
  794. .font(.system(size: 10, weight: .bold))
  795. .foregroundColor(color)
  796. }
  797. }
  798. }
  799. extension Int16 {
  800. var minutes: TimeInterval {
  801. TimeInterval(self) * 60
  802. }
  803. }