MainChartView.swift 47 KB

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