MainChartView.swift 29 KB

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