MainChartView.swift 48 KB

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