MainChartView.swift 23 KB

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