MainChartView.swift 47 KB

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