MainChartView.swift 30 KB

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