MainChartView.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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 = 5
  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 minGlucose = 70
  19. static let yLinesCount = 5
  20. static let bolusSize: CGFloat = 8
  21. static let bolusScale: CGFloat = 8
  22. static let carbsSize: CGFloat = 10
  23. static let carbsScale: CGFloat = 0.5
  24. }
  25. @Binding var glucose: [BloodGlucose]
  26. @Binding var suggestion: Suggestion?
  27. @Binding var tempBasals: [PumpHistoryEvent]
  28. @Binding var boluses: [PumpHistoryEvent]
  29. @Binding var hours: Int
  30. @Binding var maxBasal: Decimal
  31. @Binding var basalProfile: [BasalProfileEntry]
  32. @Binding var tempTargets: [TempTarget]
  33. @Binding var carbs: [CarbsEntry]
  34. let units: GlucoseUnits
  35. @State var didAppearTrigger = false
  36. @State private var glucoseDots: [CGRect] = []
  37. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  38. @State private var bolusDots: [CGRect] = []
  39. @State private var bolusPath = Path()
  40. @State private var tempBasalPath = Path()
  41. @State private var regularBasalPath = Path()
  42. @State private var tempTargetsPath = Path()
  43. @State private var carbsDots: [CGRect] = []
  44. @State private var carbsPath = Path()
  45. private var dateDormatter: DateFormatter {
  46. let formatter = DateFormatter()
  47. formatter.timeStyle = .short
  48. return formatter
  49. }
  50. private var glucoseFormatter: NumberFormatter {
  51. let formatter = NumberFormatter()
  52. formatter.numberStyle = .decimal
  53. formatter.maximumFractionDigits = 1
  54. return formatter
  55. }
  56. private var basalFormatter: NumberFormatter {
  57. let formatter = NumberFormatter()
  58. formatter.numberStyle = .decimal
  59. formatter.maximumFractionDigits = 2
  60. return formatter
  61. }
  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. // MARK: - Views
  77. var body: some View {
  78. GeometryReader { geo in
  79. ZStack(alignment: .leading) {
  80. // Y grid
  81. Path { path in
  82. let range = glucoseYRange(fullSize: geo.size)
  83. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  84. for line in 0 ... Config.yLinesCount {
  85. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  86. path.addLine(to: CGPoint(x: geo.size.width, y: range.minY + CGFloat(line) * step))
  87. }
  88. }.stroke(Color.secondary, lineWidth: 0.2)
  89. ScrollView(.horizontal, showsIndicators: false) {
  90. ScrollViewReader { scroll in
  91. ZStack(alignment: .top) {
  92. tempTargetsView(fullSize: geo.size)
  93. basalView(fullSize: geo.size)
  94. mainView(fullSize: geo.size).id("End")
  95. .onChange(of: glucose) { _ in
  96. scroll.scrollTo("End", anchor: .trailing)
  97. }
  98. .onChange(of: suggestion) { _ in
  99. scroll.scrollTo("End", anchor: .trailing)
  100. }
  101. .onChange(of: tempBasals) { _ in
  102. scroll.scrollTo("End", anchor: .trailing)
  103. }
  104. .onAppear {
  105. // add trigger to the end of main queue
  106. DispatchQueue.main.async {
  107. scroll.scrollTo("End", anchor: .trailing)
  108. didAppearTrigger = true
  109. }
  110. }
  111. }
  112. }
  113. }
  114. // Y glucose labels
  115. ForEach(0 ..< Config.yLinesCount + 1) { line -> AnyView in
  116. let range = glucoseYRange(fullSize: geo.size)
  117. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  118. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  119. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  120. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  121. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  122. .position(CGPoint(x: geo.size.width - 12, y: range.minY + CGFloat(line) * yStep))
  123. .font(.caption2)
  124. .asAny()
  125. }
  126. }
  127. }
  128. }
  129. private func basalView(fullSize: CGSize) -> some View {
  130. ZStack {
  131. tempBasalPath.fill(Color.blue)
  132. tempBasalPath.stroke(Color.blue, lineWidth: 1)
  133. regularBasalPath.stroke(Color.yellow, lineWidth: 1)
  134. Text(lastBasalRateString)
  135. .foregroundColor(.blue)
  136. .font(.caption2)
  137. .position(CGPoint(x: lastBasalPoint(fullSize: fullSize).x + 30, y: Config.basalHeight / 2))
  138. }
  139. .drawingGroup()
  140. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  141. .frame(maxHeight: Config.basalHeight)
  142. .background(Color.secondary.opacity(0.1))
  143. .onChange(of: tempBasals) { _ in
  144. calculateBasalPoints(fullSize: fullSize)
  145. }
  146. .onChange(of: maxBasal) { _ in
  147. calculateBasalPoints(fullSize: fullSize)
  148. }
  149. .onChange(of: basalProfile) { _ in
  150. calculateBasalPoints(fullSize: fullSize)
  151. }
  152. .onChange(of: didAppearTrigger) { _ in
  153. calculateBasalPoints(fullSize: fullSize)
  154. }
  155. }
  156. private func mainView(fullSize: CGSize) -> some View {
  157. Group {
  158. VStack {
  159. ZStack {
  160. // X grid
  161. Path { path in
  162. for hour in 0 ..< hours + hours {
  163. let x = firstHourPosition(viewWidth: fullSize.width) +
  164. oneSecondStep(viewWidth: fullSize.width) *
  165. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  166. path.move(to: CGPoint(x: x, y: 0))
  167. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  168. }
  169. }
  170. .stroke(Color.secondary, lineWidth: 0.2)
  171. carbsView(fullSize: fullSize)
  172. bolusView(fullSize: fullSize)
  173. glucoseView(fullSize: fullSize)
  174. predictionsView(fullSize: fullSize)
  175. }
  176. ZStack {
  177. // X time labels
  178. ForEach(0 ..< hours + hours) { hour in
  179. Text(dateDormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  180. .font(.caption)
  181. .position(
  182. x: firstHourPosition(viewWidth: fullSize.width) +
  183. oneSecondStep(viewWidth: fullSize.width) *
  184. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  185. y: 10.0
  186. )
  187. .foregroundColor(.secondary)
  188. }
  189. }.frame(maxHeight: 20)
  190. }
  191. }
  192. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  193. }
  194. private func glucoseView(fullSize: CGSize) -> some View {
  195. Path { path in
  196. for rect in glucoseDots {
  197. path.addEllipse(in: rect)
  198. }
  199. }
  200. .fill(Color.green)
  201. .onChange(of: glucose) { _ in
  202. calculateGlucoseDots(fullSize: fullSize)
  203. }
  204. .onChange(of: didAppearTrigger) { _ in
  205. calculateGlucoseDots(fullSize: fullSize)
  206. }
  207. }
  208. private func bolusView(fullSize: CGSize) -> some View {
  209. ZStack {
  210. bolusPath
  211. .fill(Color.blue)
  212. bolusPath
  213. .stroke(Color.primary, lineWidth: 0.5)
  214. ForEach(bolusDots.indexed(), id: \.1.minX) { index, rect -> AnyView in
  215. let position = CGPoint(x: rect.midX, y: rect.maxY + 8)
  216. return Text(bolusFormatter.string(from: (boluses[index].amount ?? 0) as NSNumber)!).font(.caption2)
  217. .position(position)
  218. .asAny()
  219. }
  220. }
  221. .onChange(of: boluses) { _ in
  222. calculateBolusDots(fullSize: fullSize)
  223. }
  224. .onChange(of: didAppearTrigger) { _ in
  225. calculateBolusDots(fullSize: fullSize)
  226. }
  227. }
  228. private func carbsView(fullSize: CGSize) -> some View {
  229. ZStack {
  230. carbsPath
  231. .fill(Color.orange)
  232. carbsPath
  233. .stroke(Color.primary, lineWidth: 0.5)
  234. ForEach(carbsDots.indexed(), id: \.1.minX) { index, rect -> AnyView in
  235. let position = CGPoint(x: rect.midX, y: rect.minY - 8)
  236. return Text(carbsFormatter.string(from: carbs[index].carbs as NSNumber)!).font(.caption2)
  237. .position(position)
  238. .asAny()
  239. }
  240. }
  241. .onChange(of: carbs) { _ in
  242. calculateCarbsDots(fullSize: fullSize)
  243. }
  244. .onChange(of: didAppearTrigger) { _ in
  245. calculateCarbsDots(fullSize: fullSize)
  246. }
  247. }
  248. private func tempTargetsView(fullSize: CGSize) -> some View {
  249. ZStack {
  250. tempTargetsPath
  251. .fill(Color.gray.opacity(0.5))
  252. }
  253. .onChange(of: glucose) { _ in
  254. calculateTempTargetsRects(fullSize: fullSize)
  255. }
  256. .onChange(of: tempTargets) { _ in
  257. calculateTempTargetsRects(fullSize: fullSize)
  258. }
  259. .onChange(of: didAppearTrigger) { _ in
  260. calculateTempTargetsRects(fullSize: fullSize)
  261. }
  262. }
  263. private func predictionsView(fullSize: CGSize) -> some View {
  264. Group {
  265. Path { path in
  266. for rect in predictionDots[.iob] ?? [] {
  267. path.addEllipse(in: rect)
  268. }
  269. }.stroke(Color.blue)
  270. Path { path in
  271. for rect in predictionDots[.cob] ?? [] {
  272. path.addEllipse(in: rect)
  273. }
  274. }.stroke(Color.yellow)
  275. Path { path in
  276. for rect in predictionDots[.zt] ?? [] {
  277. path.addEllipse(in: rect)
  278. }
  279. }.stroke(Color.purple)
  280. Path { path in
  281. for rect in predictionDots[.uam] ?? [] {
  282. path.addEllipse(in: rect)
  283. }
  284. }.stroke(Color.orange)
  285. }
  286. .onChange(of: suggestion) { _ in
  287. calculatePredictionDots(fullSize: fullSize, type: .iob)
  288. calculatePredictionDots(fullSize: fullSize, type: .cob)
  289. calculatePredictionDots(fullSize: fullSize, type: .zt)
  290. calculatePredictionDots(fullSize: fullSize, type: .uam)
  291. }
  292. .onChange(of: didAppearTrigger) { _ in
  293. calculatePredictionDots(fullSize: fullSize, type: .iob)
  294. calculatePredictionDots(fullSize: fullSize, type: .cob)
  295. calculatePredictionDots(fullSize: fullSize, type: .zt)
  296. calculatePredictionDots(fullSize: fullSize, type: .uam)
  297. }
  298. }
  299. // MARK: - Calculations
  300. private func calculateGlucoseDots(fullSize: CGSize) {
  301. glucoseDots = glucose.concurrentMap { value -> CGRect in
  302. let position = glucoseToCoordinate(value, fullSize: fullSize)
  303. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  304. }
  305. }
  306. private func calculateBolusDots(fullSize: CGSize) {
  307. bolusDots = boluses.map { value -> CGRect in
  308. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  309. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  310. return CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  311. }
  312. bolusPath = Path { path in
  313. for rect in bolusDots {
  314. path.addEllipse(in: rect)
  315. }
  316. }
  317. }
  318. private func calculateCarbsDots(fullSize: CGSize) {
  319. carbsDots = carbs.map { value -> CGRect in
  320. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  321. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  322. return CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  323. }
  324. carbsPath = Path { path in
  325. for rect in carbsDots {
  326. path.addEllipse(in: rect)
  327. }
  328. }
  329. }
  330. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  331. let values: [Int] = { () -> [Int] in
  332. switch type {
  333. case .iob:
  334. return suggestion?.predictions?.iob ?? []
  335. case .cob:
  336. return suggestion?.predictions?.cob ?? []
  337. case .zt:
  338. return suggestion?.predictions?.zt ?? []
  339. case .uam:
  340. return suggestion?.predictions?.uam ?? []
  341. }
  342. }()
  343. var index = 0
  344. predictionDots[type] = values.map { value -> CGRect in
  345. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  346. index += 1
  347. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  348. }
  349. }
  350. private func calculateBasalPoints(fullSize: CGSize) {
  351. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  352. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  353. var lastTimeEnd = firstTempTime
  354. let firstRegularBasalPoints = findRegularBasalPoints(timeBegin: dayAgoTime, timeEnd: firstTempTime, fullSize: fullSize)
  355. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  356. let chunk = Array(chunk)
  357. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  358. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  359. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  360. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  361. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  362. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  363. let x1 = timeToXCoordinate(timeEnd, fullSize: fullSize)
  364. let y1 = Config.basalHeight
  365. let regularPoints = findRegularBasalPoints(timeBegin: lastTimeEnd, timeEnd: timeBegin, fullSize: fullSize)
  366. lastTimeEnd = timeEnd
  367. return regularPoints + [CGPoint(x: x0, y: y0), CGPoint(x: x1, y: y1)]
  368. }.flatMap { $0 }
  369. tempBasalPath = Path { path in
  370. var yPoint: CGFloat = Config.basalHeight
  371. path.move(to: CGPoint(x: 0, y: yPoint))
  372. for point in tempBasalPoints {
  373. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  374. path.addLine(to: point)
  375. yPoint = point.y
  376. }
  377. let lastPoint = lastBasalPoint(fullSize: fullSize)
  378. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  379. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  380. }
  381. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  382. let regularBasalPoints = findRegularBasalPoints(
  383. timeBegin: dayAgoTime,
  384. timeEnd: endDateTime,
  385. fullSize: fullSize
  386. )
  387. regularBasalPath = Path { path in
  388. var yPoint: CGFloat = Config.basalHeight
  389. path.move(to: CGPoint(x: -50, y: yPoint))
  390. for point in regularBasalPoints {
  391. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  392. path.addLine(to: point)
  393. yPoint = point.y
  394. }
  395. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  396. }
  397. }
  398. private func findRegularBasalPoints(timeBegin: TimeInterval, timeEnd: TimeInterval, fullSize: CGSize) -> [CGPoint] {
  399. guard timeBegin < timeEnd else {
  400. return []
  401. }
  402. let beginDate = Date(timeIntervalSince1970: timeBegin)
  403. let calendar = Calendar.current
  404. let startOfDay = calendar.startOfDay(for: beginDate)
  405. let basalNormalized = basalProfile.map {
  406. (
  407. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  408. rate: $0.rate
  409. )
  410. } + basalProfile.map {
  411. (
  412. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  413. rate: $0.rate
  414. )
  415. } + basalProfile.map {
  416. (
  417. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  418. rate: $0.rate
  419. )
  420. }
  421. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  422. .compactMap { window -> CGPoint? in
  423. let window = Array(window)
  424. if window[0].time < timeBegin, window[1].time < timeBegin {
  425. return nil
  426. }
  427. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  428. if window[0].time < timeBegin, window[1].time >= timeBegin {
  429. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  430. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  431. return CGPoint(x: x, y: y)
  432. }
  433. if window[0].time >= timeBegin, window[0].time < timeEnd {
  434. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  435. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  436. return CGPoint(x: x, y: y)
  437. }
  438. return nil
  439. }
  440. return basalTruncatedPoints
  441. }
  442. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  443. let lastBasal = Array(tempBasals.suffix(2))
  444. guard lastBasal.count == 2 else {
  445. return .zero
  446. }
  447. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  448. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  449. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  450. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  451. return CGPoint(x: x, y: y)
  452. }
  453. private var lastBasalRateString: String {
  454. let lastBasal = Array(tempBasals.suffix(2))
  455. guard lastBasal.count == 2 else {
  456. return ""
  457. }
  458. let lastRate = lastBasal[0].rate ?? 0
  459. return (basalFormatter.string(from: lastRate as NSNumber) ?? "0") + " U/hr"
  460. }
  461. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  462. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  463. }
  464. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  465. guard let predictions = suggestion?.predictions,
  466. let deliveredAt = suggestion?.deliverAt,
  467. let last = glucose.last
  468. else {
  469. return Config.minAdditionalWidth
  470. }
  471. let iob = predictions.iob?.count ?? 0
  472. let zt = predictions.zt?.count ?? 0
  473. let cob = predictions.cob?.count ?? 0
  474. let uam = predictions.uam?.count ?? 0
  475. let max = [iob, zt, cob, uam].max() ?? 0
  476. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  477. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  478. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  479. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  480. }
  481. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  482. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  483. }
  484. private func maxPredValue() -> Int {
  485. [
  486. suggestion?.predictions?.cob ?? [],
  487. suggestion?.predictions?.iob ?? [],
  488. suggestion?.predictions?.zt ?? [],
  489. suggestion?.predictions?.uam ?? []
  490. ]
  491. .flatMap { $0 }
  492. .max() ?? Config.maxGlucose
  493. }
  494. private func minPredValue() -> Int {
  495. let min =
  496. [
  497. suggestion?.predictions?.cob ?? [],
  498. suggestion?.predictions?.iob ?? [],
  499. suggestion?.predictions?.zt ?? [],
  500. suggestion?.predictions?.uam ?? []
  501. ]
  502. .flatMap { $0 }
  503. .min() ?? Config.minGlucose
  504. return Swift.min(min, Config.minGlucose)
  505. }
  506. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  507. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  508. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  509. return CGPoint(x: x, y: y)
  510. }
  511. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  512. guard let deliveredAt = suggestion?.deliverAt else {
  513. return .zero
  514. }
  515. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  516. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  517. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  518. return CGPoint(x: x, y: y)
  519. }
  520. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  521. let xOffset = -(
  522. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  523. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  524. )
  525. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  526. let x = CGFloat(time + xOffset) * stepXFraction
  527. return x
  528. }
  529. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  530. let topYPaddint = Config.topYPadding + Config.basalHeight
  531. let bottomYPadding = Config.bottomYPadding
  532. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  533. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  534. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  535. let yOffset = CGFloat(minValue) * stepYFraction
  536. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  537. return y
  538. }
  539. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  540. var nextIndex = 0
  541. for (index, value) in glucose.enumerated() {
  542. if value.dateString.timeIntervalSince1970 > time {
  543. nextIndex = index
  544. break
  545. }
  546. }
  547. let x = timeToXCoordinate(time, fullSize: fullSize)
  548. guard nextIndex > 0 else {
  549. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  550. return CGPoint(x: x, y: lastY)
  551. }
  552. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  553. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  554. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  555. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  556. let delta = nextX - prevX
  557. let fraction = (x - prevX) / delta
  558. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  559. }
  560. private func glucoseYRange(fullSize: CGSize) -> (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat) {
  561. let topYPaddint = Config.topYPadding + Config.basalHeight
  562. let bottomYPadding = Config.bottomYPadding
  563. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  564. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  565. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  566. let yOffset = CGFloat(minValue) * stepYFraction
  567. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  568. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  569. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  570. }
  571. private func firstHourDate() -> Date {
  572. let firstDate = glucose.first?.dateString ?? Date()
  573. return firstDate.dateTruncated(from: .minute)!
  574. }
  575. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  576. let firstDate = glucose.first?.dateString ?? Date()
  577. let firstHour = firstHourDate()
  578. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  579. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  580. return oneSecondWidth * CGFloat(lastDeltaTime)
  581. }
  582. private func calculateTempTargetsRects(fullSize: CGSize) {
  583. var rects = tempTargets.map { tempTarget -> CGRect in
  584. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  585. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop), fullSize: fullSize)
  586. let x1 = timeToXCoordinate(
  587. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  588. fullSize: fullSize
  589. )
  590. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom), fullSize: fullSize)
  591. return CGRect(
  592. x: x0,
  593. y: y0 - 3,
  594. width: x1 - x0,
  595. height: y1 - y0 + 6
  596. )
  597. }
  598. if rects.count > 1 {
  599. rects = rects.reduce([]) { result, rect -> [CGRect] in
  600. guard var last = result.last else { return [rect] }
  601. if last.origin.x + last.width > rect.origin.x {
  602. last.size.width = rect.origin.x - last.origin.x
  603. }
  604. var res = Array(result.dropLast())
  605. res.append(contentsOf: [last, rect])
  606. return res
  607. }
  608. }
  609. tempTargetsPath = Path { path in
  610. path.addRects(rects)
  611. }
  612. }
  613. }