MainChartView.swift 26 KB

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