MainChartView.swift 17 KB

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