MainChartView.swift 49 KB

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