MainChartView.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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: didAppearTrigger) { _ in
  122. calculateBasalPoints(fullSize: fullSize)
  123. }
  124. }
  125. private func mainChart(fullSize: CGSize) -> some View {
  126. Group {
  127. VStack {
  128. ZStack {
  129. // X grid
  130. Path { path in
  131. for hour in 0 ..< hours + hours {
  132. let x = firstHourPosition(viewWidth: fullSize.width) +
  133. oneSecondStep(viewWidth: fullSize.width) *
  134. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  135. path.move(to: CGPoint(x: x, y: 0))
  136. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  137. }
  138. }
  139. .stroke(Color.secondary, lineWidth: 0.2)
  140. glucosePath(fullSize: fullSize)
  141. predictions(fullSize: fullSize)
  142. }
  143. ZStack {
  144. // X time labels
  145. ForEach(0 ..< hours + hours) { hour in
  146. Text(dateDormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  147. .font(.caption)
  148. .position(
  149. x: firstHourPosition(viewWidth: fullSize.width) +
  150. oneSecondStep(viewWidth: fullSize.width) *
  151. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  152. y: 10.0
  153. )
  154. .foregroundColor(.secondary)
  155. }
  156. }.frame(maxHeight: 20)
  157. }
  158. }
  159. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  160. }
  161. private func glucosePath(fullSize: CGSize) -> some View {
  162. Path { path in
  163. for rect in glucoseDots {
  164. path.addEllipse(in: rect)
  165. }
  166. }
  167. .fill(Color.green)
  168. .onChange(of: glucose) { _ in
  169. calculateGlucoseDots(fullSize: fullSize)
  170. }
  171. .onChange(of: didAppearTrigger) { _ in
  172. calculateGlucoseDots(fullSize: fullSize)
  173. }
  174. }
  175. private func predictions(fullSize: CGSize) -> some View {
  176. Group {
  177. Path { path in
  178. for rect in predictionDots[.iob] ?? [] {
  179. path.addEllipse(in: rect)
  180. }
  181. }.stroke(Color.blue)
  182. Path { path in
  183. for rect in predictionDots[.cob] ?? [] {
  184. path.addEllipse(in: rect)
  185. }
  186. }.stroke(Color.yellow)
  187. Path { path in
  188. for rect in predictionDots[.zt] ?? [] {
  189. path.addEllipse(in: rect)
  190. }
  191. }.stroke(Color.purple)
  192. Path { path in
  193. for rect in predictionDots[.uam] ?? [] {
  194. path.addEllipse(in: rect)
  195. }
  196. }.stroke(Color.orange)
  197. }
  198. .onChange(of: suggestion) { _ in
  199. calculatePredictionDots(fullSize: fullSize, type: .iob)
  200. calculatePredictionDots(fullSize: fullSize, type: .cob)
  201. calculatePredictionDots(fullSize: fullSize, type: .zt)
  202. calculatePredictionDots(fullSize: fullSize, type: .uam)
  203. }
  204. .onChange(of: didAppearTrigger) { _ in
  205. calculatePredictionDots(fullSize: fullSize, type: .iob)
  206. calculatePredictionDots(fullSize: fullSize, type: .cob)
  207. calculatePredictionDots(fullSize: fullSize, type: .zt)
  208. calculatePredictionDots(fullSize: fullSize, type: .uam)
  209. }
  210. }
  211. // MARK: - Calculations
  212. private func calculateGlucoseDots(fullSize: CGSize) {
  213. glucoseDots = glucose.concurrentMap { value -> CGRect in
  214. let position = glucoseToCoordinate(value, fullSize: fullSize)
  215. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  216. }
  217. }
  218. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  219. let values: [Int] = { () -> [Int] in
  220. switch type {
  221. case .iob:
  222. return suggestion?.predictions?.iob ?? []
  223. case .cob:
  224. return suggestion?.predictions?.cob ?? []
  225. case .zt:
  226. return suggestion?.predictions?.zt ?? []
  227. case .uam:
  228. return suggestion?.predictions?.uam ?? []
  229. }
  230. }()
  231. var index = 0
  232. predictionDots[type] = values.map { value -> CGRect in
  233. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  234. index += 1
  235. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  236. }
  237. }
  238. private func calculateBasalPoints(fullSize: CGSize) {
  239. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  240. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  241. var lastTimeEnd = firstTempTime
  242. let firstRegularBasalPoints = findRegularBasalPoints(timeBegin: dayAgoTime, timeEnd: firstTempTime, fullSize: fullSize)
  243. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  244. let chunk = Array(chunk)
  245. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  246. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  247. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  248. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  249. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  250. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  251. let x1 = timeToXCoordinate(timeEnd, fullSize: fullSize)
  252. let y1 = Config.basalHeight
  253. let regularPoints = findRegularBasalPoints(timeBegin: lastTimeEnd, timeEnd: timeBegin, fullSize: fullSize)
  254. lastTimeEnd = timeEnd
  255. return regularPoints + [CGPoint(x: x0, y: y0), CGPoint(x: x1, y: y1)]
  256. }.flatMap { $0 }
  257. tempBasalPath = Path { path in
  258. var yPoint: CGFloat = Config.basalHeight
  259. path.move(to: CGPoint(x: 0, y: yPoint))
  260. for point in tempBasalPoints {
  261. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  262. path.addLine(to: point)
  263. yPoint = point.y
  264. }
  265. let lastPoint = lastBasalPoint(fullSize: fullSize)
  266. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  267. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  268. }
  269. let regularBasalPoints = findRegularBasalPoints(
  270. timeBegin: dayAgoTime,
  271. timeEnd: dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval,
  272. fullSize: fullSize
  273. )
  274. regularBasalPath = Path { path in
  275. var yPoint: CGFloat = Config.basalHeight
  276. path.move(to: CGPoint(x: 0, y: yPoint))
  277. for point in regularBasalPoints {
  278. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  279. path.addLine(to: point)
  280. yPoint = point.y
  281. }
  282. }
  283. }
  284. private func findRegularBasalPoints(timeBegin: TimeInterval, timeEnd: TimeInterval, fullSize: CGSize) -> [CGPoint] {
  285. guard timeBegin < timeEnd else {
  286. return []
  287. }
  288. let beginDate = Date(timeIntervalSince1970: timeBegin)
  289. let calendar = Calendar.current
  290. let startOfDay = calendar.startOfDay(for: beginDate)
  291. let basalNormalized = basalProfile.map {
  292. (
  293. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  294. rate: $0.rate
  295. )
  296. } + basalProfile.map {
  297. (
  298. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  299. rate: $0.rate
  300. )
  301. }
  302. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  303. .compactMap { window -> CGPoint? in
  304. let window = Array(window)
  305. if window[0].time < timeBegin, window[1].time < timeBegin {
  306. return nil
  307. }
  308. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  309. if window[0].time < timeBegin, window[1].time >= timeBegin {
  310. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  311. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  312. return CGPoint(x: x, y: y)
  313. }
  314. if window[0].time >= timeBegin, window[0].time < timeEnd {
  315. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  316. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  317. return CGPoint(x: x, y: y)
  318. }
  319. return nil
  320. }
  321. return basalTruncatedPoints
  322. }
  323. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  324. let lastBasal = Array(tempBasals.suffix(2))
  325. guard lastBasal.count == 2 else {
  326. return .zero
  327. }
  328. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  329. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  330. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  331. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  332. return CGPoint(x: x, y: y)
  333. }
  334. private var lastBasalRateString: String {
  335. let lastBasal = Array(tempBasals.suffix(2))
  336. guard lastBasal.count == 2 else {
  337. return ""
  338. }
  339. let lastRate = lastBasal[0].rate ?? 0
  340. return (basalFormatter.string(from: lastRate as NSNumber) ?? "0") + " U/h"
  341. }
  342. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  343. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  344. }
  345. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  346. guard let predictions = suggestion?.predictions,
  347. let deliveredAt = suggestion?.deliverAt,
  348. let last = glucose.last
  349. else {
  350. return Config.minAdditionalWidth
  351. }
  352. let iob = predictions.iob?.count ?? 0
  353. let zt = predictions.zt?.count ?? 0
  354. let cob = predictions.cob?.count ?? 0
  355. let uam = predictions.uam?.count ?? 0
  356. let max = [iob, zt, cob, uam].max() ?? 0
  357. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  358. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  359. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  360. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  361. }
  362. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  363. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  364. }
  365. private func maxPredValue() -> Int {
  366. [
  367. suggestion?.predictions?.cob ?? [],
  368. suggestion?.predictions?.iob ?? [],
  369. suggestion?.predictions?.zt ?? [],
  370. suggestion?.predictions?.uam ?? []
  371. ]
  372. .flatMap { $0 }
  373. .max() ?? Config.maxGlucose
  374. }
  375. private func minPredValue() -> Int {
  376. [
  377. suggestion?.predictions?.cob ?? [],
  378. suggestion?.predictions?.iob ?? [],
  379. suggestion?.predictions?.zt ?? [],
  380. suggestion?.predictions?.uam ?? []
  381. ]
  382. .flatMap { $0 }
  383. .min() ?? 0
  384. }
  385. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  386. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  387. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  388. return CGPoint(x: x, y: y)
  389. }
  390. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  391. guard let deliveredAt = suggestion?.deliverAt else {
  392. return .zero
  393. }
  394. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  395. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  396. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  397. return CGPoint(x: x, y: y)
  398. }
  399. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  400. let xOffset = -(
  401. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  402. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  403. )
  404. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  405. let x = CGFloat(time + xOffset) * stepXFraction
  406. return x
  407. }
  408. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  409. let topYPaddint = Config.topYPadding + Config.basalHeight
  410. let bottomYPadding = Config.bottomYPadding
  411. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  412. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  413. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  414. let yOffset = CGFloat(minValue) * stepYFraction
  415. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  416. return y
  417. }
  418. private func glucoseYRange(fullSize: CGSize) -> (minValue: Int, minY: CGFloat, maxValue: Int, maxY: 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 maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  426. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  427. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  428. }
  429. private func firstHourDate() -> Date {
  430. let firstDate = glucose.first?.dateString ?? Date()
  431. return firstDate.dateTruncated(from: .minute)!
  432. }
  433. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  434. let firstDate = glucose.first?.dateString ?? Date()
  435. let firstHour = firstHourDate()
  436. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  437. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  438. return oneSecondWidth * CGFloat(lastDeltaTime)
  439. }
  440. }