MainChartView.swift 44 KB

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