MainChartView.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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 basalHeight: CGFloat = 80
  19. static let topYPadding: CGFloat = 20
  20. static let bottomYPadding: CGFloat = 80
  21. static let minAdditionalWidth: CGFloat = 150
  22. static let maxGlucose = 270
  23. static let minGlucose = 45
  24. static let yLinesCount = 5
  25. static let glucoseScale: CGFloat = 2 // default 2
  26. static let bolusSize: CGFloat = 8
  27. static let bolusScale: CGFloat = 2.5
  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 autotunedBasalProfile: [BasalProfileEntry]
  39. @Binding var basalProfile: [BasalProfileEntry]
  40. @Binding var tempTargets: [TempTarget]
  41. @Binding var carbs: [CarbsEntry]
  42. @Binding var timerDate: Date
  43. @Binding var units: GlucoseUnits
  44. @Binding var smooth: Bool
  45. @Binding var highGlucose: Decimal
  46. @Binding var lowGlucose: Decimal
  47. @Binding var screenHours: Int
  48. @Binding var displayXgridLines: Bool
  49. @Binding var displayYgridLines: Bool
  50. @Binding var thresholdLines: Bool
  51. @State var didAppearTrigger = false
  52. @State private var glucoseDots: [CGRect] = []
  53. @State private var unSmoothedGlucoseDots: [CGRect] = []
  54. @State private var manualGlucoseDots: [CGRect] = []
  55. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  56. @State private var bolusDots: [DotInfo] = []
  57. @State private var bolusPath = Path()
  58. @State private var tempBasalPath = Path()
  59. @State private var regularBasalPath = Path()
  60. @State private var tempTargetsPath = Path()
  61. @State private var suspensionsPath = Path()
  62. @State private var carbsDots: [DotInfo] = []
  63. @State private var carbsPath = Path()
  64. @State private var fpuDots: [DotInfo] = []
  65. @State private var fpuPath = Path()
  66. @State private var glucoseYRange: GlucoseYRange = (0, 0, 0, 0)
  67. @State private var offset: CGFloat = 0
  68. @State private var cachedMaxBasalRate: Decimal?
  69. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  70. private var dateFormatter: DateFormatter {
  71. let formatter = DateFormatter()
  72. formatter.timeStyle = .short
  73. return formatter
  74. }
  75. private var date24Formatter: DateFormatter {
  76. let formatter = DateFormatter()
  77. formatter.locale = Locale(identifier: "en_US_POSIX")
  78. formatter.setLocalizedDateFormatFromTemplate("HH")
  79. return formatter
  80. }
  81. private var glucoseFormatter: NumberFormatter {
  82. let formatter = NumberFormatter()
  83. formatter.numberStyle = .decimal
  84. formatter.maximumFractionDigits = 1
  85. return formatter
  86. }
  87. private var bolusFormatter: NumberFormatter {
  88. let formatter = NumberFormatter()
  89. formatter.numberStyle = .decimal
  90. formatter.minimumIntegerDigits = 0
  91. formatter.maximumFractionDigits = 2
  92. formatter.decimalSeparator = "."
  93. return formatter
  94. }
  95. private var carbsFormatter: NumberFormatter {
  96. let formatter = NumberFormatter()
  97. formatter.numberStyle = .decimal
  98. formatter.maximumFractionDigits = 0
  99. return formatter
  100. }
  101. private var fpuFormatter: NumberFormatter {
  102. let formatter = NumberFormatter()
  103. formatter.numberStyle = .decimal
  104. formatter.maximumFractionDigits = 1
  105. formatter.decimalSeparator = "."
  106. formatter.minimumIntegerDigits = 0
  107. return formatter
  108. }
  109. @Environment(\.horizontalSizeClass) var hSizeClass
  110. @Environment(\.verticalSizeClass) var vSizeClass
  111. // MARK: - Views
  112. var body: some View {
  113. GeometryReader { geo in
  114. ZStack(alignment: .leading) {
  115. yGridView(fullSize: geo.size)
  116. mainScrollView(fullSize: geo.size)
  117. glucoseLabelsView(fullSize: geo.size)
  118. }
  119. .onChange(of: hSizeClass) { _ in
  120. update(fullSize: geo.size)
  121. }
  122. .onChange(of: vSizeClass) { _ in
  123. update(fullSize: geo.size)
  124. }
  125. .onChange(of: screenHours) { _ in
  126. update(fullSize: geo.size)
  127. // scroll.scrollTo(Config.endID, anchor: .trailing)
  128. }
  129. .onReceive(
  130. Foundation.NotificationCenter.default
  131. .publisher(for: UIDevice.orientationDidChangeNotification)
  132. ) { _ in
  133. update(fullSize: geo.size)
  134. }
  135. }
  136. }
  137. private func mainScrollView(fullSize: CGSize) -> some View {
  138. ScrollView(.horizontal, showsIndicators: false) {
  139. ScrollViewReader { scroll in
  140. ZStack(alignment: .top) {
  141. tempTargetsView(fullSize: fullSize).drawingGroup()
  142. basalView(fullSize: fullSize).drawingGroup()
  143. mainView(fullSize: fullSize).id(Config.endID)
  144. .drawingGroup()
  145. .onChange(of: glucose) { _ in
  146. scroll.scrollTo(Config.endID, anchor: .trailing)
  147. }
  148. .onChange(of: suggestion) { _ in
  149. scroll.scrollTo(Config.endID, anchor: .trailing)
  150. }
  151. .onChange(of: tempBasals) { _ in
  152. scroll.scrollTo(Config.endID, anchor: .trailing)
  153. }
  154. .onAppear {
  155. // add trigger to the end of main queue
  156. DispatchQueue.main.async {
  157. scroll.scrollTo(Config.endID, anchor: .trailing)
  158. didAppearTrigger = true
  159. }
  160. }
  161. }
  162. }
  163. }
  164. }
  165. private func yGridView(fullSize: CGSize) -> some View {
  166. let useColour = displayYgridLines ? Color.secondary : Color.clear
  167. return ZStack {
  168. Path { path in
  169. let range = glucoseYRange
  170. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  171. for line in 0 ... Config.yLinesCount {
  172. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  173. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  174. }
  175. }.stroke(useColour, lineWidth: 0.15)
  176. // horizontal limits
  177. if thresholdLines {
  178. let range = glucoseYRange
  179. let topstep = (range.maxY - range.minY) / CGFloat(range.maxValue - range.minValue) *
  180. (CGFloat(range.maxValue) - CGFloat(highGlucose))
  181. if CGFloat(range.maxValue) > CGFloat(highGlucose) {
  182. Path { path in
  183. path.move(to: CGPoint(x: 0, y: range.minY + topstep))
  184. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + topstep))
  185. }.stroke(Color.loopYellow, lineWidth: 0.5) // .StrokeStyle(lineWidth: 0.5, dash: [5])
  186. }
  187. let yrange = glucoseYRange
  188. let bottomstep = (yrange.maxY - yrange.minY) / CGFloat(yrange.maxValue - yrange.minValue) *
  189. (CGFloat(yrange.maxValue) - CGFloat(lowGlucose))
  190. if CGFloat(yrange.minValue) < CGFloat(lowGlucose) {
  191. Path { path in
  192. path.move(to: CGPoint(x: 0, y: yrange.minY + bottomstep))
  193. path.addLine(to: CGPoint(x: fullSize.width, y: yrange.minY + bottomstep))
  194. }.stroke(Color.loopRed, lineWidth: 0.5)
  195. }
  196. }
  197. }
  198. }
  199. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  200. ForEach(0 ..< Config.yLinesCount + 1, id: \.self) { line -> AnyView in
  201. let range = glucoseYRange
  202. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  203. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  204. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  205. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  206. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  207. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  208. .font(.caption2)
  209. .asAny()
  210. }
  211. }
  212. private func basalView(fullSize: CGSize) -> some View {
  213. ZStack {
  214. tempBasalPath.fill(Color.basal.opacity(0.5))
  215. tempBasalPath.stroke(Color.insulin, lineWidth: 1)
  216. regularBasalPath.stroke(Color.insulin, style: StrokeStyle(lineWidth: 0.7, dash: [4]))
  217. suspensionsPath.stroke(Color.loopGray.opacity(0.7), style: StrokeStyle(lineWidth: 0.7)).scaleEffect(x: 1, y: -1)
  218. suspensionsPath.fill(Color.loopGray.opacity(0.2)).scaleEffect(x: 1, y: -1)
  219. }
  220. .scaleEffect(x: 1, y: -1)
  221. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  222. .frame(maxHeight: Config.basalHeight)
  223. .background(Color.secondary.opacity(0.1))
  224. .onChange(of: tempBasals) { _ in
  225. calculateBasalPoints(fullSize: fullSize)
  226. }
  227. .onChange(of: suspensions) { _ in
  228. calculateSuspensions(fullSize: fullSize)
  229. }
  230. .onChange(of: maxBasal) { _ in
  231. calculateBasalPoints(fullSize: fullSize)
  232. }
  233. .onChange(of: autotunedBasalProfile) { _ in
  234. calculateBasalPoints(fullSize: fullSize)
  235. }
  236. .onChange(of: didAppearTrigger) { _ in
  237. calculateBasalPoints(fullSize: fullSize)
  238. }
  239. }
  240. private func mainView(fullSize: CGSize) -> some View {
  241. Group {
  242. VStack {
  243. ZStack {
  244. xGridView(fullSize: fullSize)
  245. carbsView(fullSize: fullSize)
  246. fpuView(fullSize: fullSize)
  247. bolusView(fullSize: fullSize)
  248. if smooth { unSmoothedGlucoseView(fullSize: fullSize) }
  249. glucoseView(fullSize: fullSize)
  250. manualGlucoseView(fullSize: fullSize)
  251. predictionsView(fullSize: fullSize)
  252. }
  253. timeLabelsView(fullSize: fullSize)
  254. }
  255. }
  256. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  257. }
  258. @Environment(\.colorScheme) var colorScheme
  259. private func xGridView(fullSize: CGSize) -> some View {
  260. let useColour = displayXgridLines ? Color.secondary : Color.clear
  261. return ZStack {
  262. Path { path in
  263. for hour in 0 ..< hours + hours {
  264. let x = firstHourPosition(viewWidth: fullSize.width) +
  265. oneSecondStep(viewWidth: fullSize.width) *
  266. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  267. path.move(to: CGPoint(x: x, y: 0))
  268. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  269. }
  270. }
  271. .stroke(useColour, lineWidth: 0.15)
  272. Path { path in // vertical timeline
  273. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize)
  274. path.move(to: CGPoint(x: x, y: 0))
  275. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  276. }
  277. .stroke(
  278. colorScheme == .dark ? Color.white : Color.black,
  279. style: StrokeStyle(lineWidth: 0.5, dash: [5])
  280. )
  281. }
  282. }
  283. private func timeLabelsView(fullSize: CGSize) -> some View {
  284. let format = screenHours > 6 ? date24Formatter : dateFormatter
  285. return ZStack {
  286. // X time labels
  287. ForEach(0 ..< hours + hours) { hour in
  288. Text(format.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  289. .font(.caption)
  290. .position(
  291. x: firstHourPosition(viewWidth: fullSize.width) +
  292. oneSecondStep(viewWidth: fullSize.width) *
  293. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  294. y: 10.0
  295. )
  296. .foregroundColor(.secondary)
  297. }
  298. }.frame(maxHeight: 20)
  299. }
  300. private func glucoseView(fullSize: CGSize) -> some View {
  301. Path { path in
  302. for rect in glucoseDots {
  303. path.addEllipse(in: rect)
  304. }
  305. }
  306. .fill(Color.loopGreen)
  307. .onChange(of: glucose) { _ in
  308. update(fullSize: fullSize)
  309. }
  310. .onChange(of: didAppearTrigger) { _ in
  311. update(fullSize: fullSize)
  312. }
  313. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  314. update(fullSize: fullSize)
  315. }
  316. }
  317. private func unSmoothedGlucoseView(fullSize: CGSize) -> some View {
  318. Path { path in
  319. var lines: [CGPoint] = []
  320. for rect in unSmoothedGlucoseDots {
  321. lines.append(CGPoint(x: rect.midX, y: rect.midY))
  322. path.addEllipse(in: rect)
  323. }
  324. path.addLines(lines)
  325. }
  326. .stroke(Color.loopGray, lineWidth: 0.5)
  327. .onChange(of: glucose) { _ in
  328. update(fullSize: fullSize)
  329. }
  330. .onChange(of: didAppearTrigger) { _ in
  331. update(fullSize: fullSize)
  332. }
  333. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  334. update(fullSize: fullSize)
  335. }
  336. }
  337. private func manualGlucoseView(fullSize: CGSize) -> some View {
  338. ZStack {
  339. Path { path in
  340. for rect in manualGlucoseDots {
  341. path.addEllipse(in: rect)
  342. }
  343. }
  344. .fill(Color.loopRed)
  345. Path { path in
  346. for rect in manualGlucoseDots {
  347. path.addEllipse(in: rect)
  348. }
  349. }
  350. .stroke(Color.primary, lineWidth: 0.5)
  351. }
  352. .onChange(of: glucose) { _ in
  353. update(fullSize: fullSize)
  354. }
  355. .onChange(of: didAppearTrigger) { _ in
  356. update(fullSize: fullSize)
  357. }
  358. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  359. update(fullSize: fullSize)
  360. }
  361. }
  362. private func bolusView(fullSize: CGSize) -> some View {
  363. ZStack {
  364. bolusPath
  365. .fill(Color.insulin)
  366. bolusPath
  367. .stroke(Color.primary, lineWidth: 0.5)
  368. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  369. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  370. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  371. .position(position)
  372. .asAny()
  373. }
  374. }
  375. .onChange(of: boluses) { _ in
  376. calculateBolusDots(fullSize: fullSize)
  377. }
  378. .onChange(of: didAppearTrigger) { _ in
  379. calculateBolusDots(fullSize: fullSize)
  380. }
  381. }
  382. private func carbsView(fullSize: CGSize) -> some View {
  383. ZStack {
  384. carbsPath
  385. .fill(Color.loopYellow)
  386. carbsPath
  387. .stroke(Color.primary, lineWidth: 0.5)
  388. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  389. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  390. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  391. .position(position)
  392. .asAny()
  393. }
  394. }
  395. .onChange(of: carbs) { _ in
  396. calculateCarbsDots(fullSize: fullSize)
  397. }
  398. .onChange(of: didAppearTrigger) { _ in
  399. calculateCarbsDots(fullSize: fullSize)
  400. }
  401. }
  402. private func fpuView(fullSize: CGSize) -> some View {
  403. ZStack {
  404. fpuPath
  405. .fill(Color.red)
  406. fpuPath
  407. .stroke(Color.primary, lineWidth: 0.5)
  408. ForEach(fpuDots, id: \.rect.minX) { info -> AnyView in
  409. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  410. return Text(fpuFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  411. .position(position)
  412. .asAny()
  413. }
  414. }
  415. .onChange(of: carbs) { _ in
  416. calculateFPUsDots(fullSize: fullSize)
  417. }
  418. .onChange(of: didAppearTrigger) { _ in
  419. calculateFPUsDots(fullSize: fullSize)
  420. }
  421. }
  422. private func tempTargetsView(fullSize: CGSize) -> some View {
  423. ZStack {
  424. tempTargetsPath
  425. .fill(Color.tempBasal.opacity(0.5))
  426. tempTargetsPath
  427. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  428. }
  429. .onChange(of: glucose) { _ in
  430. calculateTempTargetsRects(fullSize: fullSize)
  431. }
  432. .onChange(of: tempTargets) { _ in
  433. calculateTempTargetsRects(fullSize: fullSize)
  434. }
  435. .onChange(of: didAppearTrigger) { _ in
  436. calculateTempTargetsRects(fullSize: fullSize)
  437. }
  438. }
  439. private func predictionsView(fullSize: CGSize) -> some View {
  440. Group {
  441. Path { path in
  442. for rect in predictionDots[.iob] ?? [] {
  443. path.addEllipse(in: rect)
  444. }
  445. }.fill(Color.insulin)
  446. Path { path in
  447. for rect in predictionDots[.cob] ?? [] {
  448. path.addEllipse(in: rect)
  449. }
  450. }.fill(Color.loopYellow)
  451. Path { path in
  452. for rect in predictionDots[.zt] ?? [] {
  453. path.addEllipse(in: rect)
  454. }
  455. }.fill(Color.zt)
  456. Path { path in
  457. for rect in predictionDots[.uam] ?? [] {
  458. path.addEllipse(in: rect)
  459. }
  460. }.fill(Color.uam)
  461. }
  462. .onChange(of: suggestion) { _ in
  463. update(fullSize: fullSize)
  464. }
  465. }
  466. }
  467. // MARK: - Calculations
  468. extension MainChartView {
  469. private func update(fullSize: CGSize) {
  470. calculatePredictionDots(fullSize: fullSize, type: .iob)
  471. calculatePredictionDots(fullSize: fullSize, type: .cob)
  472. calculatePredictionDots(fullSize: fullSize, type: .zt)
  473. calculatePredictionDots(fullSize: fullSize, type: .uam)
  474. calculateGlucoseDots(fullSize: fullSize)
  475. calculateUnSmoothedGlucoseDots(fullSize: fullSize)
  476. calculateManualGlucoseDots(fullSize: fullSize)
  477. calculateBolusDots(fullSize: fullSize)
  478. calculateCarbsDots(fullSize: fullSize)
  479. calculateFPUsDots(fullSize: fullSize)
  480. calculateTempTargetsRects(fullSize: fullSize)
  481. calculateBasalPoints(fullSize: fullSize)
  482. calculateSuspensions(fullSize: fullSize)
  483. }
  484. private func calculateGlucoseDots(fullSize: CGSize) {
  485. calculationQueue.async {
  486. let sgvs = glucose
  487. .filter { $0.type != "Manual"
  488. } // as fingerpricks will be drawn differently, slightly larger and red - so do not draw them here
  489. let dots = sgvs.concurrentMap { value -> CGRect in
  490. let position = glucoseToCoordinate(value, fullSize: fullSize)
  491. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  492. }
  493. let range = self.getGlucoseYRange(fullSize: fullSize)
  494. DispatchQueue.main.async {
  495. glucoseYRange = range
  496. glucoseDots = dots
  497. }
  498. }
  499. }
  500. private func calculateUnSmoothedGlucoseDots(fullSize: CGSize) {
  501. calculationQueue.async {
  502. let sgvs = glucose.filter { $0.type == "sgv" }
  503. let dots = sgvs.concurrentMap { value -> CGRect in
  504. let position = UnSmoothedGlucoseToCoordinate(value, fullSize: fullSize)
  505. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  506. }
  507. let range = self.getGlucoseYRange(fullSize: fullSize)
  508. DispatchQueue.main.async {
  509. glucoseYRange = range
  510. unSmoothedGlucoseDots = dots
  511. }
  512. }
  513. }
  514. private func calculateManualGlucoseDots(fullSize: CGSize) {
  515. calculationQueue.async {
  516. let manuals = glucose.filter { $0.type == "Manual" }
  517. let dots = manuals.concurrentMap { value -> CGRect in
  518. let position = glucoseToCoordinate(value, fullSize: fullSize)
  519. return CGRect(x: position.x - 2, y: position.y - 2, width: 6, height: 6)
  520. }
  521. let range = self.getGlucoseYRange(fullSize: fullSize)
  522. DispatchQueue.main.async {
  523. glucoseYRange = range
  524. manualGlucoseDots = dots
  525. }
  526. }
  527. }
  528. private func calculateBolusDots(fullSize: CGSize) {
  529. calculationQueue.async {
  530. let dots = boluses.map { value -> DotInfo in
  531. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  532. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  533. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  534. return DotInfo(rect: rect, value: value.amount ?? 0)
  535. }
  536. let path = Path { path in
  537. for dot in dots {
  538. path.addEllipse(in: dot.rect)
  539. }
  540. }
  541. DispatchQueue.main.async {
  542. bolusDots = dots
  543. bolusPath = path
  544. }
  545. }
  546. }
  547. private func calculateCarbsDots(fullSize: CGSize) {
  548. calculationQueue.async {
  549. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  550. let dots = realCarbs.map { value -> DotInfo in
  551. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  552. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  553. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  554. return DotInfo(rect: rect, value: value.carbs)
  555. }
  556. let path = Path { path in
  557. for dot in dots {
  558. path.addEllipse(in: dot.rect)
  559. }
  560. }
  561. DispatchQueue.main.async {
  562. carbsDots = dots
  563. carbsPath = path
  564. }
  565. }
  566. }
  567. private func calculateFPUsDots(fullSize: CGSize) {
  568. calculationQueue.async {
  569. let fpus = carbs.filter { $0.isFPU ?? false }
  570. let dots = fpus.map { value -> DotInfo in
  571. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  572. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  573. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  574. return DotInfo(rect: rect, value: value.carbs)
  575. }
  576. let path = Path { path in
  577. for dot in dots {
  578. path.addEllipse(in: dot.rect)
  579. }
  580. }
  581. DispatchQueue.main.async {
  582. fpuDots = dots
  583. fpuPath = path
  584. }
  585. }
  586. }
  587. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  588. calculationQueue.async {
  589. let values: [Int] = { () -> [Int] in
  590. switch type {
  591. case .iob:
  592. return suggestion?.predictions?.iob ?? []
  593. case .cob:
  594. return suggestion?.predictions?.cob ?? []
  595. case .zt:
  596. return suggestion?.predictions?.zt ?? []
  597. case .uam:
  598. return suggestion?.predictions?.uam ?? []
  599. }
  600. }()
  601. var index = 0
  602. let dots = values.map { value -> CGRect in
  603. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  604. index += 1
  605. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  606. }
  607. DispatchQueue.main.async {
  608. predictionDots[type] = dots
  609. }
  610. }
  611. }
  612. private func calculateBasalPoints(fullSize: CGSize) {
  613. calculationQueue.async {
  614. self.cachedMaxBasalRate = nil
  615. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  616. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  617. var lastTimeEnd = firstTempTime
  618. let firstRegularBasalPoints = findRegularBasalPoints(
  619. timeBegin: dayAgoTime,
  620. timeEnd: firstTempTime,
  621. fullSize: fullSize,
  622. autotuned: false
  623. )
  624. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  625. let chunk = Array(chunk)
  626. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  627. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  628. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  629. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  630. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  631. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  632. let regularPoints = findRegularBasalPoints(
  633. timeBegin: lastTimeEnd,
  634. timeEnd: timeBegin,
  635. fullSize: fullSize,
  636. autotuned: false
  637. )
  638. lastTimeEnd = timeEnd
  639. return regularPoints + [CGPoint(x: x0, y: y0)]
  640. }.flatMap { $0 }
  641. let tempBasalPath = Path { path in
  642. var yPoint: CGFloat = Config.basalHeight
  643. path.move(to: CGPoint(x: 0, y: yPoint))
  644. for point in tempBasalPoints {
  645. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  646. path.addLine(to: point)
  647. yPoint = point.y
  648. }
  649. let lastPoint = lastBasalPoint(fullSize: fullSize)
  650. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  651. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  652. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  653. }
  654. let adjustForOptionalExtraHours = screenHours > 12 ? screenHours - 12 : 0
  655. let endDateTime = dayAgoTime + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  656. .timeInterval + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  657. .timeInterval
  658. let autotunedBasalPoints = findRegularBasalPoints(
  659. timeBegin: dayAgoTime,
  660. timeEnd: endDateTime,
  661. fullSize: fullSize,
  662. autotuned: true
  663. )
  664. let autotunedBasalPath = Path { path in
  665. var yPoint: CGFloat = Config.basalHeight
  666. path.move(to: CGPoint(x: -50, y: yPoint))
  667. for point in autotunedBasalPoints {
  668. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  669. path.addLine(to: point)
  670. yPoint = point.y
  671. }
  672. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  673. }
  674. DispatchQueue.main.async {
  675. self.tempBasalPath = tempBasalPath
  676. self.regularBasalPath = autotunedBasalPath
  677. }
  678. }
  679. }
  680. private func calculateSuspensions(fullSize: CGSize) {
  681. calculationQueue.async {
  682. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  683. let window = Array(window)
  684. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  685. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  686. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  687. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  688. }
  689. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  690. guard event.type == .pumpResume else { return nil }
  691. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  692. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  693. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  694. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  695. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  696. return CGRect(
  697. x: x0,
  698. y: 0,
  699. width: x1 - x0,
  700. height: Config.basalHeight * 0.7
  701. )
  702. }
  703. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  704. guard event.type == .pumpSuspend else { return nil }
  705. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  706. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  707. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  708. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  709. .additionalWidth(viewWidth: fullSize.width)
  710. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  711. }
  712. rects.append(firstRec)
  713. rects.append(lastRec)
  714. let path = Path { path in
  715. path.addRects(rects.compactMap { $0 })
  716. }
  717. DispatchQueue.main.async {
  718. suspensionsPath = path
  719. }
  720. }
  721. }
  722. private func maxBasalRate() -> Decimal {
  723. if let cached = cachedMaxBasalRate {
  724. return cached
  725. }
  726. let maxRegularBasalRate = max(
  727. basalProfile.map(\.rate).max() ?? maxBasal,
  728. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  729. )
  730. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  731. if maxTempBasalRate == 0 {
  732. maxTempBasalRate = maxRegularBasalRate
  733. }
  734. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  735. return cachedMaxBasalRate ?? maxBasal
  736. }
  737. private func calculateTempTargetsRects(fullSize: CGSize) {
  738. calculationQueue.async {
  739. var rects = tempTargets.map { tempTarget -> CGRect in
  740. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  741. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  742. let x1 = timeToXCoordinate(
  743. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  744. fullSize: fullSize
  745. )
  746. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  747. return CGRect(
  748. x: x0,
  749. y: y0 - 3,
  750. width: x1 - x0,
  751. height: y1 - y0 + 6
  752. )
  753. }
  754. if rects.count > 1 {
  755. rects = rects.reduce([]) { result, rect -> [CGRect] in
  756. guard var last = result.last else { return [rect] }
  757. if last.origin.x + last.width > rect.origin.x {
  758. last.size.width = rect.origin.x - last.origin.x
  759. }
  760. var res = Array(result.dropLast())
  761. res.append(contentsOf: [last, rect])
  762. return res
  763. }
  764. }
  765. let path = Path { path in
  766. path.addRects(rects)
  767. }
  768. DispatchQueue.main.async {
  769. tempTargetsPath = path
  770. }
  771. }
  772. }
  773. private func findRegularBasalPoints(
  774. timeBegin: TimeInterval,
  775. timeEnd: TimeInterval,
  776. fullSize: CGSize,
  777. autotuned: Bool
  778. ) -> [CGPoint] {
  779. guard timeBegin < timeEnd else {
  780. return []
  781. }
  782. let beginDate = Date(timeIntervalSince1970: timeBegin)
  783. let calendar = Calendar.current
  784. let startOfDay = calendar.startOfDay(for: beginDate)
  785. let profile = autotuned ? autotunedBasalProfile : basalProfile
  786. let basalNormalized = profile.map {
  787. (
  788. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  789. rate: $0.rate
  790. )
  791. } + profile.map {
  792. (
  793. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  794. rate: $0.rate
  795. )
  796. } + profile.map {
  797. (
  798. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  799. rate: $0.rate
  800. )
  801. }
  802. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  803. .compactMap { window -> CGPoint? in
  804. let window = Array(window)
  805. if window[0].time < timeBegin, window[1].time < timeBegin {
  806. return nil
  807. }
  808. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  809. if window[0].time < timeBegin, window[1].time >= timeBegin {
  810. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  811. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  812. return CGPoint(x: x, y: y)
  813. }
  814. if window[0].time >= timeBegin, window[0].time < timeEnd {
  815. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  816. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  817. return CGPoint(x: x, y: y)
  818. }
  819. return nil
  820. }
  821. return basalTruncatedPoints
  822. }
  823. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  824. let lastBasal = Array(tempBasals.suffix(2))
  825. guard lastBasal.count == 2 else {
  826. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  827. }
  828. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  829. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  830. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  831. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  832. return CGPoint(x: x, y: y)
  833. }
  834. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  835. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  836. }
  837. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  838. guard let predictions = suggestion?.predictions,
  839. let deliveredAt = suggestion?.deliverAt,
  840. let last = glucose.last
  841. else {
  842. return Config.minAdditionalWidth
  843. }
  844. let iob = predictions.iob?.count ?? 0
  845. let zt = predictions.zt?.count ?? 0
  846. let cob = predictions.cob?.count ?? 0
  847. let uam = predictions.uam?.count ?? 0
  848. let max = [iob, zt, cob, uam].max() ?? 0
  849. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  850. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  851. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  852. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  853. }
  854. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  855. viewWidth / (CGFloat(min(max(screenHours, 2), 24)) * CGFloat(1.hours.timeInterval))
  856. }
  857. private func maxPredValue() -> Int? {
  858. [
  859. suggestion?.predictions?.cob ?? [],
  860. suggestion?.predictions?.iob ?? [],
  861. suggestion?.predictions?.zt ?? [],
  862. suggestion?.predictions?.uam ?? []
  863. ]
  864. .flatMap { $0 }
  865. .max()
  866. }
  867. private func minPredValue() -> Int? {
  868. [
  869. suggestion?.predictions?.cob ?? [],
  870. suggestion?.predictions?.iob ?? [],
  871. suggestion?.predictions?.zt ?? [],
  872. suggestion?.predictions?.uam ?? []
  873. ]
  874. .flatMap { $0 }
  875. .min()
  876. }
  877. private func maxTargetValue() -> Int? {
  878. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  879. }
  880. private func minTargetValue() -> Int? {
  881. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  882. }
  883. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  884. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  885. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  886. return CGPoint(x: x, y: y)
  887. }
  888. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  889. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  890. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  891. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  892. return CGPoint(x: x, y: y)
  893. }
  894. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  895. guard let deliveredAt = suggestion?.deliverAt else {
  896. return .zero
  897. }
  898. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  899. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  900. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  901. return CGPoint(x: x, y: y)
  902. }
  903. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  904. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  905. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  906. let x = CGFloat(time + xOffset) * stepXFraction
  907. return x
  908. }
  909. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  910. let topYPaddint = Config.topYPadding + Config.basalHeight
  911. let bottomYPadding = Config.bottomYPadding
  912. let (minValue, maxValue) = minMaxYValues()
  913. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  914. let yOffset = CGFloat(minValue) * stepYFraction
  915. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  916. return y
  917. }
  918. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  919. var nextIndex = 0
  920. for (index, value) in glucose.enumerated() {
  921. if value.dateString.timeIntervalSince1970 > time {
  922. nextIndex = index
  923. break
  924. }
  925. }
  926. let x = timeToXCoordinate(time, fullSize: fullSize)
  927. guard nextIndex > 0 else {
  928. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  929. return CGPoint(x: x, y: lastY)
  930. }
  931. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  932. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  933. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  934. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  935. let delta = nextX - prevX
  936. let fraction = (x - prevX) / delta
  937. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  938. }
  939. private func minMaxYValues() -> (min: Int, max: Int) {
  940. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  941. if let maxPredValue = maxPredValue() {
  942. maxValue = max(maxValue, maxPredValue)
  943. }
  944. if let maxTargetValue = maxTargetValue() {
  945. maxValue = max(maxValue, maxTargetValue)
  946. }
  947. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  948. if let minPredValue = minPredValue() {
  949. minValue = min(minValue, minPredValue)
  950. }
  951. if let minTargetValue = minTargetValue() {
  952. minValue = min(minValue, minTargetValue)
  953. }
  954. if minValue == maxValue {
  955. minValue = Config.minGlucose
  956. maxValue = Config.maxGlucose
  957. }
  958. // fix the grah y-axis as long as the min and max BG values are within set borders
  959. if minValue > Config.minGlucose {
  960. minValue = Config.minGlucose
  961. }
  962. if maxValue < Config.maxGlucose {
  963. maxValue = Config.maxGlucose
  964. }
  965. return (min: minValue, max: maxValue)
  966. }
  967. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  968. let topYPaddint = Config.topYPadding + Config.basalHeight
  969. let bottomYPadding = Config.bottomYPadding
  970. let (minValue, maxValue) = minMaxYValues()
  971. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  972. let yOffset = CGFloat(minValue) * stepYFraction
  973. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  974. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  975. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  976. }
  977. private func firstHourDate() -> Date {
  978. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  979. return firstDate.dateTruncated(from: .minute)!
  980. }
  981. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  982. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  983. let firstHour = firstHourDate()
  984. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  985. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  986. return oneSecondWidth * CGFloat(lastDeltaTime)
  987. }
  988. }