MainChartView.swift 29 KB

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