MainChartView.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. calculateBolusDots(fullSize: fullSize)
  298. calculateBolusDots(fullSize: fullSize)
  299. }
  300. .onChange(of: didAppearTrigger) { _ in
  301. calculatePredictionDots(fullSize: fullSize, type: .iob)
  302. calculatePredictionDots(fullSize: fullSize, type: .cob)
  303. calculatePredictionDots(fullSize: fullSize, type: .zt)
  304. calculatePredictionDots(fullSize: fullSize, type: .uam)
  305. calculateGlucoseDots(fullSize: fullSize)
  306. calculateBolusDots(fullSize: fullSize)
  307. calculateBolusDots(fullSize: fullSize)
  308. }
  309. }
  310. // MARK: - Calculations
  311. private func calculateGlucoseDots(fullSize: CGSize) {
  312. calculationQueue.async {
  313. let dots = glucose.concurrentMap { value -> CGRect in
  314. let position = glucoseToCoordinate(value, fullSize: fullSize)
  315. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  316. }
  317. DispatchQueue.main.async {
  318. glucoseDots = dots
  319. }
  320. }
  321. }
  322. private func calculateBolusDots(fullSize: CGSize) {
  323. calculationQueue.async {
  324. let dots = boluses.map { value -> DotInfo in
  325. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  326. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  327. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  328. return DotInfo(rect: rect, value: value.amount ?? 0)
  329. }
  330. let path = Path { path in
  331. for dot in dots {
  332. path.addEllipse(in: dot.rect)
  333. }
  334. }
  335. DispatchQueue.main.async {
  336. bolusDots = dots
  337. bolusPath = path
  338. }
  339. }
  340. }
  341. private func calculateCarbsDots(fullSize: CGSize) {
  342. calculationQueue.async {
  343. let dots = carbs.map { value -> DotInfo in
  344. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  345. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  346. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  347. return DotInfo(rect: rect, value: value.carbs)
  348. }
  349. let path = Path { path in
  350. for dot in dots {
  351. path.addEllipse(in: dot.rect)
  352. }
  353. }
  354. DispatchQueue.main.async {
  355. carbsDots = dots
  356. carbsPath = path
  357. }
  358. }
  359. }
  360. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  361. calculationQueue.async {
  362. let values: [Int] = { () -> [Int] in
  363. switch type {
  364. case .iob:
  365. return suggestion?.predictions?.iob ?? []
  366. case .cob:
  367. return suggestion?.predictions?.cob ?? []
  368. case .zt:
  369. return suggestion?.predictions?.zt ?? []
  370. case .uam:
  371. return suggestion?.predictions?.uam ?? []
  372. }
  373. }()
  374. var index = 0
  375. let dots = values.map { value -> CGRect in
  376. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  377. index += 1
  378. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  379. }
  380. DispatchQueue.main.async {
  381. predictionDots[type] = dots
  382. }
  383. }
  384. }
  385. private func calculateBasalPoints(fullSize: CGSize) {
  386. calculationQueue.async {
  387. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  388. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  389. var lastTimeEnd = firstTempTime
  390. let firstRegularBasalPoints = findRegularBasalPoints(
  391. timeBegin: dayAgoTime,
  392. timeEnd: firstTempTime,
  393. fullSize: fullSize
  394. )
  395. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  396. let chunk = Array(chunk)
  397. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  398. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  399. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  400. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  401. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  402. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  403. let x1 = timeToXCoordinate(timeEnd, fullSize: fullSize)
  404. let y1 = Config.basalHeight
  405. let regularPoints = findRegularBasalPoints(timeBegin: lastTimeEnd, timeEnd: timeBegin, fullSize: fullSize)
  406. lastTimeEnd = timeEnd
  407. return regularPoints + [CGPoint(x: x0, y: y0), CGPoint(x: x1, y: y1)]
  408. }.flatMap { $0 }
  409. let tempBasalPath = Path { path in
  410. var yPoint: CGFloat = Config.basalHeight
  411. path.move(to: CGPoint(x: 0, y: yPoint))
  412. for point in tempBasalPoints {
  413. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  414. path.addLine(to: point)
  415. yPoint = point.y
  416. }
  417. let lastPoint = lastBasalPoint(fullSize: fullSize)
  418. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  419. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  420. }
  421. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  422. let regularBasalPoints = findRegularBasalPoints(
  423. timeBegin: dayAgoTime,
  424. timeEnd: endDateTime,
  425. fullSize: fullSize
  426. )
  427. let regularBasalPath = Path { path in
  428. var yPoint: CGFloat = Config.basalHeight
  429. path.move(to: CGPoint(x: -50, y: yPoint))
  430. for point in regularBasalPoints {
  431. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  432. path.addLine(to: point)
  433. yPoint = point.y
  434. }
  435. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  436. }
  437. DispatchQueue.main.async {
  438. self.tempBasalPath = tempBasalPath
  439. self.regularBasalPath = regularBasalPath
  440. }
  441. }
  442. }
  443. private func findRegularBasalPoints(timeBegin: TimeInterval, timeEnd: TimeInterval, fullSize: CGSize) -> [CGPoint] {
  444. guard timeBegin < timeEnd else {
  445. return []
  446. }
  447. let beginDate = Date(timeIntervalSince1970: timeBegin)
  448. let calendar = Calendar.current
  449. let startOfDay = calendar.startOfDay(for: beginDate)
  450. let basalNormalized = basalProfile.map {
  451. (
  452. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  453. rate: $0.rate
  454. )
  455. } + basalProfile.map {
  456. (
  457. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  458. rate: $0.rate
  459. )
  460. } + basalProfile.map {
  461. (
  462. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  463. rate: $0.rate
  464. )
  465. }
  466. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  467. .compactMap { window -> CGPoint? in
  468. let window = Array(window)
  469. if window[0].time < timeBegin, window[1].time < timeBegin {
  470. return nil
  471. }
  472. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  473. if window[0].time < timeBegin, window[1].time >= timeBegin {
  474. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  475. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  476. return CGPoint(x: x, y: y)
  477. }
  478. if window[0].time >= timeBegin, window[0].time < timeEnd {
  479. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  480. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  481. return CGPoint(x: x, y: y)
  482. }
  483. return nil
  484. }
  485. return basalTruncatedPoints
  486. }
  487. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  488. let lastBasal = Array(tempBasals.suffix(2))
  489. guard lastBasal.count == 2 else {
  490. return .zero
  491. }
  492. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  493. let rateCost = Config.basalHeight / CGFloat(maxBasal)
  494. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  495. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  496. return CGPoint(x: x, y: y)
  497. }
  498. private var lastBasalRateString: String {
  499. let lastBasal = Array(tempBasals.suffix(2))
  500. guard lastBasal.count == 2 else {
  501. return ""
  502. }
  503. let lastRate = lastBasal[0].rate ?? 0
  504. return (basalFormatter.string(from: lastRate as NSNumber) ?? "0") + " U/hr"
  505. }
  506. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  507. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  508. }
  509. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  510. guard let predictions = suggestion?.predictions,
  511. let deliveredAt = suggestion?.deliverAt,
  512. let last = glucose.last
  513. else {
  514. return Config.minAdditionalWidth
  515. }
  516. let iob = predictions.iob?.count ?? 0
  517. let zt = predictions.zt?.count ?? 0
  518. let cob = predictions.cob?.count ?? 0
  519. let uam = predictions.uam?.count ?? 0
  520. let max = [iob, zt, cob, uam].max() ?? 0
  521. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  522. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  523. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  524. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  525. }
  526. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  527. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  528. }
  529. private func maxPredValue() -> Int {
  530. [
  531. suggestion?.predictions?.cob ?? [],
  532. suggestion?.predictions?.iob ?? [],
  533. suggestion?.predictions?.zt ?? [],
  534. suggestion?.predictions?.uam ?? []
  535. ]
  536. .flatMap { $0 }
  537. .max() ?? Config.maxGlucose
  538. }
  539. private func minPredValue() -> Int {
  540. let min =
  541. [
  542. suggestion?.predictions?.cob ?? [],
  543. suggestion?.predictions?.iob ?? [],
  544. suggestion?.predictions?.zt ?? [],
  545. suggestion?.predictions?.uam ?? []
  546. ]
  547. .flatMap { $0 }
  548. .min() ?? Config.minGlucose
  549. return Swift.min(min, Config.minGlucose)
  550. }
  551. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  552. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  553. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  554. return CGPoint(x: x, y: y)
  555. }
  556. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  557. guard let deliveredAt = suggestion?.deliverAt else {
  558. return .zero
  559. }
  560. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  561. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  562. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  563. return CGPoint(x: x, y: y)
  564. }
  565. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  566. let xOffset = -(
  567. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  568. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  569. )
  570. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  571. let x = CGFloat(time + xOffset) * stepXFraction
  572. return x
  573. }
  574. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  575. let topYPaddint = Config.topYPadding + Config.basalHeight
  576. let bottomYPadding = Config.bottomYPadding
  577. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  578. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  579. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  580. let yOffset = CGFloat(minValue) * stepYFraction
  581. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  582. return y
  583. }
  584. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  585. var nextIndex = 0
  586. for (index, value) in glucose.enumerated() {
  587. if value.dateString.timeIntervalSince1970 > time {
  588. nextIndex = index
  589. break
  590. }
  591. }
  592. let x = timeToXCoordinate(time, fullSize: fullSize)
  593. guard nextIndex > 0 else {
  594. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  595. return CGPoint(x: x, y: lastY)
  596. }
  597. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  598. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  599. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  600. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  601. let delta = nextX - prevX
  602. let fraction = (x - prevX) / delta
  603. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  604. }
  605. private func glucoseYRange(fullSize: CGSize) -> (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat) {
  606. let topYPaddint = Config.topYPadding + Config.basalHeight
  607. let bottomYPadding = Config.bottomYPadding
  608. let maxValue = max(glucose.compactMap(\.glucose).max() ?? Config.maxGlucose, maxPredValue())
  609. let minValue = min(glucose.compactMap(\.glucose).min() ?? 0, minPredValue())
  610. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  611. let yOffset = CGFloat(minValue) * stepYFraction
  612. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  613. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  614. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  615. }
  616. private func firstHourDate() -> Date {
  617. let firstDate = glucose.first?.dateString ?? Date()
  618. return firstDate.dateTruncated(from: .minute)!
  619. }
  620. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  621. let firstDate = glucose.first?.dateString ?? Date()
  622. let firstHour = firstHourDate()
  623. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  624. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  625. return oneSecondWidth * CGFloat(lastDeltaTime)
  626. }
  627. private func calculateTempTargetsRects(fullSize: CGSize) {
  628. var rects = tempTargets.map { tempTarget -> CGRect in
  629. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  630. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop), fullSize: fullSize)
  631. let x1 = timeToXCoordinate(
  632. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  633. fullSize: fullSize
  634. )
  635. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom), fullSize: fullSize)
  636. return CGRect(
  637. x: x0,
  638. y: y0 - 3,
  639. width: x1 - x0,
  640. height: y1 - y0 + 6
  641. )
  642. }
  643. if rects.count > 1 {
  644. rects = rects.reduce([]) { result, rect -> [CGRect] in
  645. guard var last = result.last else { return [rect] }
  646. if last.origin.x + last.width > rect.origin.x {
  647. last.size.width = rect.origin.x - last.origin.x
  648. }
  649. var res = Array(result.dropLast())
  650. res.append(contentsOf: [last, rect])
  651. return res
  652. }
  653. }
  654. tempTargetsPath = Path { path in
  655. path.addRects(rects)
  656. }
  657. }
  658. }