MainChartView.swift 48 KB

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