MainChartView.swift 48 KB

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