MainChartView.swift 47 KB

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