MainChartView.swift 29 KB

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