MainChartView.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import Algorithms
  2. import SwiftDate
  3. import SwiftUI
  4. private enum PredictionType: Hashable {
  5. case iob
  6. case cob
  7. case zt
  8. case uam
  9. }
  10. struct MainChartView: View {
  11. private enum Config {
  12. static let screenHours = 6
  13. static let basalHeight: CGFloat = 60
  14. static let topYPadding: CGFloat = 20
  15. static let bottomYPadding: CGFloat = 50
  16. static let minAdditionalWidth: CGFloat = 150
  17. static let maxGlucose = 450
  18. static let yLinesCount = 5
  19. }
  20. @Binding var glucose: [BloodGlucose]
  21. @Binding var suggestion: Suggestion?
  22. @Binding var tempBasals: [PumpHistoryEvent]
  23. @Binding var hours: Int
  24. @Binding var maxBasal: Decimal
  25. @Binding var basalProfile: [BasalProfileEntry]
  26. let units: GlucoseUnits
  27. @State var didAppearTrigger = false
  28. @State private var glucoseDots: [CGRect] = []
  29. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  30. @State private var tempBasalPath = Path()
  31. @State private var regularBasalPath = Path()
  32. private var dateDormatter: DateFormatter {
  33. let formatter = DateFormatter()
  34. formatter.timeStyle = .short
  35. return formatter
  36. }
  37. private var glucoseFormatter: NumberFormatter {
  38. let formatter = NumberFormatter()
  39. formatter.numberStyle = .decimal
  40. formatter.maximumFractionDigits = 1
  41. return formatter
  42. }
  43. private var basalFormatter: NumberFormatter {
  44. let formatter = NumberFormatter()
  45. formatter.numberStyle = .decimal
  46. formatter.maximumFractionDigits = 2
  47. return formatter
  48. }
  49. // MARK: - Views
  50. var body: some View {
  51. GeometryReader { geo in
  52. ZStack(alignment: .leading) {
  53. // Y grid
  54. Path { path in
  55. let range = glucoseYRange(fullSize: geo.size)
  56. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  57. for line in 0 ... Config.yLinesCount {
  58. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  59. path.addLine(to: CGPoint(x: geo.size.width, y: range.minY + CGFloat(line) * step))
  60. }
  61. }.stroke(Color.secondary, lineWidth: 0.2)
  62. ScrollView(.horizontal, showsIndicators: false) {
  63. ScrollViewReader { scroll in
  64. ZStack(alignment: .top) {
  65. basalChart(fullSize: geo.size)
  66. mainChart(fullSize: geo.size).id("End")
  67. .onChange(of: glucose) { _ in
  68. scroll.scrollTo("End", anchor: .trailing)
  69. }
  70. .onChange(of: suggestion) { _ in
  71. scroll.scrollTo("End", anchor: .trailing)
  72. }
  73. .onChange(of: tempBasals) { _ in
  74. scroll.scrollTo("End", anchor: .trailing)
  75. }
  76. .onAppear {
  77. // add trigger to the end of main queue
  78. DispatchQueue.main.async {
  79. scroll.scrollTo("End", anchor: .trailing)
  80. didAppearTrigger = true
  81. }
  82. }
  83. }
  84. }
  85. }
  86. // Y glucose labels
  87. ForEach(0 ..< Config.yLinesCount + 1) { line -> AnyView in
  88. let range = glucoseYRange(fullSize: geo.size)
  89. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  90. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  91. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  92. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  93. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  94. .position(CGPoint(x: geo.size.width - 12, y: range.minY + CGFloat(line) * yStep))
  95. .font(.caption2)
  96. .asAny()
  97. }
  98. }
  99. }
  100. }
  101. private func basalChart(fullSize: CGSize) -> some View {
  102. ZStack {
  103. tempBasalPath.fill(Color.blue)
  104. tempBasalPath.stroke(Color.blue, lineWidth: 1)
  105. regularBasalPath.stroke(Color.yellow, lineWidth: 1)
  106. Text(lastBasalRateString)
  107. .foregroundColor(.blue)
  108. .font(.caption2)
  109. .position(CGPoint(x: lastBasalPoint(fullSize: fullSize).x + 30, y: Config.basalHeight / 2))
  110. }
  111. .drawingGroup()
  112. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  113. .frame(maxHeight: Config.basalHeight)
  114. .background(Color.secondary.opacity(0.1))
  115. .onChange(of: tempBasals) { _ in
  116. calculateBasalPoints(fullSize: fullSize)
  117. }
  118. .onChange(of: maxBasal) { _ in
  119. calculateBasalPoints(fullSize: fullSize)
  120. }
  121. .onChange(of: basalProfile) { _ in
  122. calculateBasalPoints(fullSize: fullSize)
  123. }
  124. .onChange(of: didAppearTrigger) { _ in
  125. calculateBasalPoints(fullSize: fullSize)
  126. }
  127. }
  128. private func mainChart(fullSize: CGSize) -> some View {
  129. Group {
  130. VStack {
  131. ZStack {
  132. // X grid
  133. Path { path in
  134. for hour in 0 ..< hours + hours {
  135. let x = firstHourPosition(viewWidth: fullSize.width) +
  136. oneSecondStep(viewWidth: fullSize.width) *
  137. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  138. path.move(to: CGPoint(x: x, y: 0))
  139. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  140. }
  141. }
  142. .stroke(Color.secondary, lineWidth: 0.2)
  143. glucosePath(fullSize: fullSize)
  144. predictions(fullSize: fullSize)
  145. }
  146. ZStack {
  147. // X time labels
  148. ForEach(0 ..< hours + hours) { hour in
  149. Text(dateDormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  150. .font(.caption)
  151. .position(
  152. x: firstHourPosition(viewWidth: fullSize.width) +
  153. oneSecondStep(viewWidth: fullSize.width) *
  154. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  155. y: 10.0
  156. )
  157. .foregroundColor(.secondary)
  158. }
  159. }.frame(maxHeight: 20)
  160. }
  161. }
  162. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  163. }
  164. private func glucosePath(fullSize: CGSize) -> some View {
  165. Path { path in
  166. for rect in glucoseDots {
  167. path.addEllipse(in: rect)
  168. }
  169. }
  170. .fill(Color.green)
  171. .onChange(of: glucose) { _ in
  172. calculateGlucoseDots(fullSize: fullSize)
  173. }
  174. .onChange(of: didAppearTrigger) { _ in
  175. calculateGlucoseDots(fullSize: fullSize)
  176. }
  177. }
  178. private func predictions(fullSize: CGSize) -> some View {
  179. Group {
  180. Path { path in
  181. for rect in predictionDots[.iob] ?? [] {
  182. path.addEllipse(in: rect)
  183. }
  184. }.stroke(Color.blue)
  185. Path { path in
  186. for rect in predictionDots[.cob] ?? [] {
  187. path.addEllipse(in: rect)
  188. }
  189. }.stroke(Color.yellow)
  190. Path { path in
  191. for rect in predictionDots[.zt] ?? [] {
  192. path.addEllipse(in: rect)
  193. }
  194. }.stroke(Color.purple)
  195. Path { path in
  196. for rect in predictionDots[.uam] ?? [] {
  197. path.addEllipse(in: rect)
  198. }
  199. }.stroke(Color.orange)
  200. }
  201. .onChange(of: suggestion) { _ in
  202. calculatePredictionDots(fullSize: fullSize, type: .iob)
  203. calculatePredictionDots(fullSize: fullSize, type: .cob)
  204. calculatePredictionDots(fullSize: fullSize, type: .zt)
  205. calculatePredictionDots(fullSize: fullSize, type: .uam)
  206. }
  207. .onChange(of: didAppearTrigger) { _ in
  208. calculatePredictionDots(fullSize: fullSize, type: .iob)
  209. calculatePredictionDots(fullSize: fullSize, type: .cob)
  210. calculatePredictionDots(fullSize: fullSize, type: .zt)
  211. calculatePredictionDots(fullSize: fullSize, type: .uam)
  212. }
  213. }
  214. // MARK: - Calculations
  215. private func calculateGlucoseDots(fullSize: CGSize) {
  216. glucoseDots = glucose.concurrentMap { value -> CGRect in
  217. let position = glucoseToCoordinate(value, fullSize: fullSize)
  218. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  219. }
  220. }
  221. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  222. let values: [Int] = { () -> [Int] in
  223. switch type {
  224. case .iob:
  225. return suggestion?.predictions?.iob ?? []
  226. case .cob:
  227. return suggestion?.predictions?.cob ?? []
  228. case .zt:
  229. return suggestion?.predictions?.zt ?? []
  230. case .uam:
  231. return suggestion?.predictions?.uam ?? []
  232. }
  233. }()
  234. var index = 0
  235. predictionDots[type] = values.map { value -> CGRect in
  236. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  237. index += 1
  238. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  239. }
  240. }
  241. private func calculateBasalPoints(fullSize: CGSize) {
  242. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  243. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  244. var lastTimeEnd = firstTempTime
  245. let firstRegularBasalPoints = findRegularBasalPoints(timeBegin: dayAgoTime, timeEnd: firstTempTime, fullSize: fullSize)
  246. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  247. let chunk = Array(chunk)
  248. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  249. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  250. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  251. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  252. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  253. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  254. let x1 = timeToXCoordinate(timeEnd, fullSize: fullSize)
  255. let y1 = Config.basalHeight
  256. let regularPoints = findRegularBasalPoints(timeBegin: lastTimeEnd, timeEnd: timeBegin, fullSize: fullSize)
  257. lastTimeEnd = timeEnd
  258. return regularPoints + [CGPoint(x: x0, y: y0), CGPoint(x: x1, y: y1)]
  259. }.flatMap { $0 }
  260. tempBasalPath = Path { path in
  261. var yPoint: CGFloat = Config.basalHeight
  262. path.move(to: CGPoint(x: 0, y: yPoint))
  263. for point in tempBasalPoints {
  264. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  265. path.addLine(to: point)
  266. yPoint = point.y
  267. }
  268. let lastPoint = lastBasalPoint(fullSize: fullSize)
  269. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  270. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  271. }
  272. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  273. let regularBasalPoints = findRegularBasalPoints(
  274. timeBegin: dayAgoTime,
  275. timeEnd: endDateTime,
  276. fullSize: fullSize
  277. )
  278. regularBasalPath = Path { path in
  279. var yPoint: CGFloat = Config.basalHeight
  280. path.move(to: CGPoint(x: -50, y: yPoint))
  281. for point in regularBasalPoints {
  282. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  283. path.addLine(to: point)
  284. yPoint = point.y
  285. }
  286. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  287. }
  288. }
  289. private func findRegularBasalPoints(timeBegin: TimeInterval, timeEnd: TimeInterval, fullSize: CGSize) -> [CGPoint] {
  290. guard timeBegin < timeEnd else {
  291. return []
  292. }
  293. let beginDate = Date(timeIntervalSince1970: timeBegin)
  294. let calendar = Calendar.current
  295. let startOfDay = calendar.startOfDay(for: beginDate)
  296. let basalNormalized = basalProfile.map {
  297. (
  298. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  299. rate: $0.rate
  300. )
  301. } + basalProfile.map {
  302. (
  303. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  304. rate: $0.rate
  305. )
  306. } + basalProfile.map {
  307. (
  308. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  309. rate: $0.rate
  310. )
  311. }
  312. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  313. .compactMap { window -> CGPoint? in
  314. let window = Array(window)
  315. if window[0].time < timeBegin, window[1].time < timeBegin {
  316. return nil
  317. }
  318. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  319. if window[0].time < timeBegin, window[1].time >= timeBegin {
  320. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  321. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  322. return CGPoint(x: x, y: y)
  323. }
  324. if window[0].time >= timeBegin, window[0].time < timeEnd {
  325. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  326. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  327. return CGPoint(x: x, y: y)
  328. }
  329. return nil
  330. }
  331. return basalTruncatedPoints
  332. }
  333. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  334. let lastBasal = Array(tempBasals.suffix(2))
  335. guard lastBasal.count == 2 else {
  336. return .zero
  337. }
  338. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  339. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  340. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  341. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  342. return CGPoint(x: x, y: y)
  343. }
  344. private var lastBasalRateString: String {
  345. let lastBasal = Array(tempBasals.suffix(2))
  346. guard lastBasal.count == 2 else {
  347. return ""
  348. }
  349. let lastRate = lastBasal[0].rate ?? 0
  350. return (basalFormatter.string(from: lastRate as NSNumber) ?? "0") + " U/h"
  351. }
  352. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  353. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  354. }
  355. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  356. guard let predictions = suggestion?.predictions,
  357. let deliveredAt = suggestion?.deliverAt,
  358. let last = glucose.last
  359. else {
  360. return Config.minAdditionalWidth
  361. }
  362. let iob = predictions.iob?.count ?? 0
  363. let zt = predictions.zt?.count ?? 0
  364. let cob = predictions.cob?.count ?? 0
  365. let uam = predictions.uam?.count ?? 0
  366. let max = [iob, zt, cob, uam].max() ?? 0
  367. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  368. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  369. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  370. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  371. }
  372. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  373. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  374. }
  375. private func maxPredValue() -> Int {
  376. [
  377. suggestion?.predictions?.cob ?? [],
  378. suggestion?.predictions?.iob ?? [],
  379. suggestion?.predictions?.zt ?? [],
  380. suggestion?.predictions?.uam ?? []
  381. ]
  382. .flatMap { $0 }
  383. .max() ?? Config.maxGlucose
  384. }
  385. private func minPredValue() -> Int {
  386. [
  387. suggestion?.predictions?.cob ?? [],
  388. suggestion?.predictions?.iob ?? [],
  389. suggestion?.predictions?.zt ?? [],
  390. suggestion?.predictions?.uam ?? []
  391. ]
  392. .flatMap { $0 }
  393. .min() ?? 0
  394. }
  395. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  396. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  397. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  398. return CGPoint(x: x, y: y)
  399. }
  400. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  401. guard let deliveredAt = suggestion?.deliverAt else {
  402. return .zero
  403. }
  404. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  405. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  406. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  407. return CGPoint(x: x, y: y)
  408. }
  409. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  410. let xOffset = -(
  411. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  412. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  413. )
  414. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  415. let x = CGFloat(time + xOffset) * stepXFraction
  416. return x
  417. }
  418. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  419. let topYPaddint = Config.topYPadding + Config.basalHeight
  420. let bottomYPadding = Config.bottomYPadding
  421. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  422. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  423. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  424. let yOffset = CGFloat(minValue) * stepYFraction
  425. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  426. return y
  427. }
  428. private func glucoseYRange(fullSize: CGSize) -> (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat) {
  429. let topYPaddint = Config.topYPadding + Config.basalHeight
  430. let bottomYPadding = Config.bottomYPadding
  431. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  432. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  433. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  434. let yOffset = CGFloat(minValue) * stepYFraction
  435. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  436. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  437. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  438. }
  439. private func firstHourDate() -> Date {
  440. let firstDate = glucose.first?.dateString ?? Date()
  441. return firstDate.dateTruncated(from: .minute)!
  442. }
  443. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  444. let firstDate = glucose.first?.dateString ?? Date()
  445. let firstHour = firstHourDate()
  446. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  447. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  448. return oneSecondWidth * CGFloat(lastDeltaTime)
  449. }
  450. }