MainChartView.swift 32 KB

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