MainChartView.swift 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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.filter { $0.type == "sgv" }
  487. let dots = sgvs.concurrentMap { value -> CGRect in
  488. let position = glucoseToCoordinate(value, fullSize: fullSize)
  489. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  490. }
  491. let range = self.getGlucoseYRange(fullSize: fullSize)
  492. DispatchQueue.main.async {
  493. glucoseYRange = range
  494. glucoseDots = dots
  495. }
  496. }
  497. }
  498. private func calculateUnSmoothedGlucoseDots(fullSize: CGSize) {
  499. calculationQueue.async {
  500. let sgvs = glucose.filter { $0.type == "sgv" }
  501. let dots = sgvs.concurrentMap { value -> CGRect in
  502. let position = UnSmoothedGlucoseToCoordinate(value, fullSize: fullSize)
  503. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  504. }
  505. let range = self.getGlucoseYRange(fullSize: fullSize)
  506. DispatchQueue.main.async {
  507. glucoseYRange = range
  508. unSmoothedGlucoseDots = dots
  509. }
  510. }
  511. }
  512. private func calculateManualGlucoseDots(fullSize: CGSize) {
  513. calculationQueue.async {
  514. let manuals = glucose.filter { $0.type == "Manual" }
  515. let dots = manuals.concurrentMap { value -> CGRect in
  516. let position = glucoseToCoordinate(value, fullSize: fullSize)
  517. return CGRect(x: position.x - 2, y: position.y - 2, width: 6, height: 6)
  518. }
  519. let range = self.getGlucoseYRange(fullSize: fullSize)
  520. DispatchQueue.main.async {
  521. glucoseYRange = range
  522. manualGlucoseDots = dots
  523. }
  524. }
  525. }
  526. private func calculateBolusDots(fullSize: CGSize) {
  527. calculationQueue.async {
  528. let dots = boluses.map { value -> DotInfo in
  529. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  530. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  531. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  532. return DotInfo(rect: rect, value: value.amount ?? 0)
  533. }
  534. let path = Path { path in
  535. for dot in dots {
  536. path.addEllipse(in: dot.rect)
  537. }
  538. }
  539. DispatchQueue.main.async {
  540. bolusDots = dots
  541. bolusPath = path
  542. }
  543. }
  544. }
  545. private func calculateCarbsDots(fullSize: CGSize) {
  546. calculationQueue.async {
  547. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  548. let dots = realCarbs.map { value -> DotInfo in
  549. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  550. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  551. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  552. return DotInfo(rect: rect, value: value.carbs)
  553. }
  554. let path = Path { path in
  555. for dot in dots {
  556. path.addEllipse(in: dot.rect)
  557. }
  558. }
  559. DispatchQueue.main.async {
  560. carbsDots = dots
  561. carbsPath = path
  562. }
  563. }
  564. }
  565. private func calculateFPUsDots(fullSize: CGSize) {
  566. calculationQueue.async {
  567. let fpus = carbs.filter { $0.isFPU ?? false }
  568. let dots = fpus.map { value -> DotInfo in
  569. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  570. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  571. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  572. return DotInfo(rect: rect, value: value.carbs)
  573. }
  574. let path = Path { path in
  575. for dot in dots {
  576. path.addEllipse(in: dot.rect)
  577. }
  578. }
  579. DispatchQueue.main.async {
  580. fpuDots = dots
  581. fpuPath = path
  582. }
  583. }
  584. }
  585. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  586. calculationQueue.async {
  587. let values: [Int] = { () -> [Int] in
  588. switch type {
  589. case .iob:
  590. return suggestion?.predictions?.iob ?? []
  591. case .cob:
  592. return suggestion?.predictions?.cob ?? []
  593. case .zt:
  594. return suggestion?.predictions?.zt ?? []
  595. case .uam:
  596. return suggestion?.predictions?.uam ?? []
  597. }
  598. }()
  599. var index = 0
  600. let dots = values.map { value -> CGRect in
  601. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  602. index += 1
  603. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  604. }
  605. DispatchQueue.main.async {
  606. predictionDots[type] = dots
  607. }
  608. }
  609. }
  610. private func calculateBasalPoints(fullSize: CGSize) {
  611. calculationQueue.async {
  612. self.cachedMaxBasalRate = nil
  613. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  614. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  615. var lastTimeEnd = firstTempTime
  616. let firstRegularBasalPoints = findRegularBasalPoints(
  617. timeBegin: dayAgoTime,
  618. timeEnd: firstTempTime,
  619. fullSize: fullSize,
  620. autotuned: false
  621. )
  622. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  623. let chunk = Array(chunk)
  624. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  625. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  626. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  627. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  628. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  629. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  630. let regularPoints = findRegularBasalPoints(
  631. timeBegin: lastTimeEnd,
  632. timeEnd: timeBegin,
  633. fullSize: fullSize,
  634. autotuned: false
  635. )
  636. lastTimeEnd = timeEnd
  637. return regularPoints + [CGPoint(x: x0, y: y0)]
  638. }.flatMap { $0 }
  639. let tempBasalPath = Path { path in
  640. var yPoint: CGFloat = Config.basalHeight
  641. path.move(to: CGPoint(x: 0, y: yPoint))
  642. for point in tempBasalPoints {
  643. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  644. path.addLine(to: point)
  645. yPoint = point.y
  646. }
  647. let lastPoint = lastBasalPoint(fullSize: fullSize)
  648. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  649. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  650. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  651. }
  652. let adjustForOptionalExtraHours = screenHours > 12 ? screenHours - 12 : 0
  653. let endDateTime = dayAgoTime + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  654. .timeInterval + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  655. .timeInterval
  656. let autotunedBasalPoints = findRegularBasalPoints(
  657. timeBegin: dayAgoTime,
  658. timeEnd: endDateTime,
  659. fullSize: fullSize,
  660. autotuned: true
  661. )
  662. let autotunedBasalPath = Path { path in
  663. var yPoint: CGFloat = Config.basalHeight
  664. path.move(to: CGPoint(x: -50, y: yPoint))
  665. for point in autotunedBasalPoints {
  666. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  667. path.addLine(to: point)
  668. yPoint = point.y
  669. }
  670. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  671. }
  672. DispatchQueue.main.async {
  673. self.tempBasalPath = tempBasalPath
  674. self.regularBasalPath = autotunedBasalPath
  675. }
  676. }
  677. }
  678. private func calculateSuspensions(fullSize: CGSize) {
  679. calculationQueue.async {
  680. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  681. let window = Array(window)
  682. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  683. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  684. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  685. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  686. }
  687. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  688. guard event.type == .pumpResume else { return nil }
  689. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  690. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  691. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  692. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  693. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  694. return CGRect(
  695. x: x0,
  696. y: 0,
  697. width: x1 - x0,
  698. height: Config.basalHeight * 0.7
  699. )
  700. }
  701. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  702. guard event.type == .pumpSuspend else { return nil }
  703. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  704. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  705. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  706. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  707. .additionalWidth(viewWidth: fullSize.width)
  708. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  709. }
  710. rects.append(firstRec)
  711. rects.append(lastRec)
  712. let path = Path { path in
  713. path.addRects(rects.compactMap { $0 })
  714. }
  715. DispatchQueue.main.async {
  716. suspensionsPath = path
  717. }
  718. }
  719. }
  720. private func maxBasalRate() -> Decimal {
  721. if let cached = cachedMaxBasalRate {
  722. return cached
  723. }
  724. let maxRegularBasalRate = max(
  725. basalProfile.map(\.rate).max() ?? maxBasal,
  726. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  727. )
  728. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  729. if maxTempBasalRate == 0 {
  730. maxTempBasalRate = maxRegularBasalRate
  731. }
  732. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  733. return cachedMaxBasalRate ?? maxBasal
  734. }
  735. private func calculateTempTargetsRects(fullSize: CGSize) {
  736. calculationQueue.async {
  737. var rects = tempTargets.map { tempTarget -> CGRect in
  738. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  739. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  740. let x1 = timeToXCoordinate(
  741. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  742. fullSize: fullSize
  743. )
  744. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  745. return CGRect(
  746. x: x0,
  747. y: y0 - 3,
  748. width: x1 - x0,
  749. height: y1 - y0 + 6
  750. )
  751. }
  752. if rects.count > 1 {
  753. rects = rects.reduce([]) { result, rect -> [CGRect] in
  754. guard var last = result.last else { return [rect] }
  755. if last.origin.x + last.width > rect.origin.x {
  756. last.size.width = rect.origin.x - last.origin.x
  757. }
  758. var res = Array(result.dropLast())
  759. res.append(contentsOf: [last, rect])
  760. return res
  761. }
  762. }
  763. let path = Path { path in
  764. path.addRects(rects)
  765. }
  766. DispatchQueue.main.async {
  767. tempTargetsPath = path
  768. }
  769. }
  770. }
  771. private func findRegularBasalPoints(
  772. timeBegin: TimeInterval,
  773. timeEnd: TimeInterval,
  774. fullSize: CGSize,
  775. autotuned: Bool
  776. ) -> [CGPoint] {
  777. guard timeBegin < timeEnd else {
  778. return []
  779. }
  780. let beginDate = Date(timeIntervalSince1970: timeBegin)
  781. let calendar = Calendar.current
  782. let startOfDay = calendar.startOfDay(for: beginDate)
  783. let profile = autotuned ? autotunedBasalProfile : basalProfile
  784. let basalNormalized = profile.map {
  785. (
  786. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  787. rate: $0.rate
  788. )
  789. } + profile.map {
  790. (
  791. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  792. rate: $0.rate
  793. )
  794. } + profile.map {
  795. (
  796. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  797. rate: $0.rate
  798. )
  799. }
  800. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  801. .compactMap { window -> CGPoint? in
  802. let window = Array(window)
  803. if window[0].time < timeBegin, window[1].time < timeBegin {
  804. return nil
  805. }
  806. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  807. if window[0].time < timeBegin, window[1].time >= timeBegin {
  808. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  809. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  810. return CGPoint(x: x, y: y)
  811. }
  812. if window[0].time >= timeBegin, window[0].time < timeEnd {
  813. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  814. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  815. return CGPoint(x: x, y: y)
  816. }
  817. return nil
  818. }
  819. return basalTruncatedPoints
  820. }
  821. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  822. let lastBasal = Array(tempBasals.suffix(2))
  823. guard lastBasal.count == 2 else {
  824. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  825. }
  826. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  827. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  828. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  829. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  830. return CGPoint(x: x, y: y)
  831. }
  832. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  833. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  834. }
  835. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  836. guard let predictions = suggestion?.predictions,
  837. let deliveredAt = suggestion?.deliverAt,
  838. let last = glucose.last
  839. else {
  840. return Config.minAdditionalWidth
  841. }
  842. let iob = predictions.iob?.count ?? 0
  843. let zt = predictions.zt?.count ?? 0
  844. let cob = predictions.cob?.count ?? 0
  845. let uam = predictions.uam?.count ?? 0
  846. let max = [iob, zt, cob, uam].max() ?? 0
  847. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  848. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  849. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  850. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  851. }
  852. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  853. viewWidth / (CGFloat(min(max(screenHours, 2), 24)) * CGFloat(1.hours.timeInterval))
  854. }
  855. private func maxPredValue() -> Int? {
  856. [
  857. suggestion?.predictions?.cob ?? [],
  858. suggestion?.predictions?.iob ?? [],
  859. suggestion?.predictions?.zt ?? [],
  860. suggestion?.predictions?.uam ?? []
  861. ]
  862. .flatMap { $0 }
  863. .max()
  864. }
  865. private func minPredValue() -> Int? {
  866. [
  867. suggestion?.predictions?.cob ?? [],
  868. suggestion?.predictions?.iob ?? [],
  869. suggestion?.predictions?.zt ?? [],
  870. suggestion?.predictions?.uam ?? []
  871. ]
  872. .flatMap { $0 }
  873. .min()
  874. }
  875. private func maxTargetValue() -> Int? {
  876. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  877. }
  878. private func minTargetValue() -> Int? {
  879. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  880. }
  881. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  882. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  883. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  884. return CGPoint(x: x, y: y)
  885. }
  886. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  887. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  888. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  889. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  890. return CGPoint(x: x, y: y)
  891. }
  892. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  893. guard let deliveredAt = suggestion?.deliverAt else {
  894. return .zero
  895. }
  896. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  897. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  898. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  899. return CGPoint(x: x, y: y)
  900. }
  901. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  902. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  903. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  904. let x = CGFloat(time + xOffset) * stepXFraction
  905. return x
  906. }
  907. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  908. let topYPaddint = Config.topYPadding + Config.basalHeight
  909. let bottomYPadding = Config.bottomYPadding
  910. let (minValue, maxValue) = minMaxYValues()
  911. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  912. let yOffset = CGFloat(minValue) * stepYFraction
  913. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  914. return y
  915. }
  916. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  917. var nextIndex = 0
  918. for (index, value) in glucose.enumerated() {
  919. if value.dateString.timeIntervalSince1970 > time {
  920. nextIndex = index
  921. break
  922. }
  923. }
  924. let x = timeToXCoordinate(time, fullSize: fullSize)
  925. guard nextIndex > 0 else {
  926. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  927. return CGPoint(x: x, y: lastY)
  928. }
  929. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  930. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  931. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  932. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  933. let delta = nextX - prevX
  934. let fraction = (x - prevX) / delta
  935. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  936. }
  937. private func minMaxYValues() -> (min: Int, max: Int) {
  938. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  939. if let maxPredValue = maxPredValue() {
  940. maxValue = max(maxValue, maxPredValue)
  941. }
  942. if let maxTargetValue = maxTargetValue() {
  943. maxValue = max(maxValue, maxTargetValue)
  944. }
  945. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  946. if let minPredValue = minPredValue() {
  947. minValue = min(minValue, minPredValue)
  948. }
  949. if let minTargetValue = minTargetValue() {
  950. minValue = min(minValue, minTargetValue)
  951. }
  952. if minValue == maxValue {
  953. minValue = Config.minGlucose
  954. maxValue = Config.maxGlucose
  955. }
  956. // fix the grah y-axis as long as the min and max BG values are within set borders
  957. if minValue > Config.minGlucose {
  958. minValue = Config.minGlucose
  959. }
  960. if maxValue < Config.maxGlucose {
  961. maxValue = Config.maxGlucose
  962. }
  963. return (min: minValue, max: maxValue)
  964. }
  965. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  966. let topYPaddint = Config.topYPadding + Config.basalHeight
  967. let bottomYPadding = Config.bottomYPadding
  968. let (minValue, maxValue) = minMaxYValues()
  969. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  970. let yOffset = CGFloat(minValue) * stepYFraction
  971. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  972. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  973. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  974. }
  975. private func firstHourDate() -> Date {
  976. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  977. return firstDate.dateTruncated(from: .minute)!
  978. }
  979. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  980. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  981. let firstHour = firstHourDate()
  982. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  983. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  984. return oneSecondWidth * CGFloat(lastDeltaTime)
  985. }
  986. }