virtualizedViewManager.tsx 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  1. import {useLayoutEffect, useRef, useState} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import {mat3, vec2} from 'gl-matrix';
  4. import type {Client} from 'sentry/api';
  5. import type {Organization} from 'sentry/types';
  6. import {getDuration} from 'sentry/utils/formatters';
  7. import clamp from 'sentry/utils/number/clamp';
  8. import {requestAnimationTimeout} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  9. import {lightTheme as theme} from 'sentry/utils/theme';
  10. import {
  11. isAutogroupedNode,
  12. isMissingInstrumentationNode,
  13. isParentAutogroupedNode,
  14. isSiblingAutogroupedNode,
  15. isSpanNode,
  16. isTraceErrorNode,
  17. isTraceNode,
  18. isTransactionNode,
  19. } from 'sentry/views/performance/newTraceDetails/guards';
  20. import {
  21. type TraceTree,
  22. TraceTreeNode,
  23. } from 'sentry/views/performance/newTraceDetails/traceTree';
  24. const DIVIDER_WIDTH = 6;
  25. function easeOutSine(x: number): number {
  26. return Math.sin((x * Math.PI) / 2);
  27. }
  28. type ViewColumn = {
  29. column_nodes: TraceTreeNode<TraceTree.NodeValue>[];
  30. column_refs: (HTMLElement | undefined)[];
  31. translate: [number, number];
  32. width: number;
  33. };
  34. class View {
  35. public x: number;
  36. public y: number;
  37. public width: number;
  38. public height: number;
  39. constructor(x: number, y: number, width: number, height: number) {
  40. this.x = x;
  41. this.y = y;
  42. this.width = width;
  43. this.height = height;
  44. }
  45. static From(view: View): View {
  46. return new View(view.x, view.y, view.width, view.height);
  47. }
  48. static Empty(): View {
  49. return new View(0, 0, 1000, 1);
  50. }
  51. serialize() {
  52. return [this.x, this.y, this.width, this.height];
  53. }
  54. between(to: View): mat3 {
  55. return mat3.fromValues(
  56. to.width / this.width,
  57. 0,
  58. 0,
  59. to.height / this.height,
  60. 0,
  61. 0,
  62. to.x - this.x * (to.width / this.width),
  63. to.y - this.y * (to.height / this.height),
  64. 1
  65. );
  66. }
  67. transform(mat: mat3): [number, number, number, number] {
  68. const x = this.x * mat[0] + this.y * mat[3] + mat[6];
  69. const y = this.x * mat[1] + this.y * mat[4] + mat[7];
  70. const width = this.width * mat[0] + this.height * mat[3];
  71. const height = this.width * mat[1] + this.height * mat[4];
  72. return [x, y, width, height];
  73. }
  74. get center() {
  75. return this.x + this.width / 2;
  76. }
  77. get left() {
  78. return this.x;
  79. }
  80. get right() {
  81. return this.x + this.width;
  82. }
  83. get top() {
  84. return this.y;
  85. }
  86. get bottom() {
  87. return this.y + this.height;
  88. }
  89. }
  90. export function computeTimelineIntervals(
  91. view: View,
  92. targetInterval: number,
  93. results: (number | undefined)[]
  94. ): void {
  95. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  96. let interval = minInterval;
  97. if (targetInterval / interval > 5) {
  98. interval *= 5;
  99. } else if (targetInterval / interval > 2) {
  100. interval *= 2;
  101. }
  102. let x = Math.ceil(view.x / interval) * interval;
  103. let idx = -1;
  104. if (x > 0) {
  105. x -= interval;
  106. }
  107. while (x <= view.right) {
  108. results[++idx] = x;
  109. x += interval;
  110. }
  111. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  112. results[++idx] = undefined;
  113. }
  114. }
  115. type ArgumentTypes<F> = F extends (...args: infer A) => any ? A : never;
  116. type EventStore = {
  117. [K in keyof VirtualizedViewManagerEvents]: Set<VirtualizedViewManagerEvents[K]>;
  118. };
  119. interface VirtualizedViewManagerEvents {
  120. ['divider resize end']: (list_width: number) => void;
  121. }
  122. /**
  123. * Tracks the state of the virtualized view and manages the resizing of the columns.
  124. * Children components should call the appropriate register*Ref methods to register their
  125. * HTML elements.
  126. */
  127. export class VirtualizedViewManager {
  128. // Represents the space of the entire trace, for example
  129. // a trace starting at 0 and ending at 1000 would have a space of [0, 1000]
  130. to_origin: number = 0;
  131. trace_space: View = View.Empty();
  132. // The view defines what the user is currently looking at, it is a subset
  133. // of the trace space. For example, if the user is currently looking at the
  134. // trace from 500 to 1000, the view would be represented by [x, width] = [500, 500]
  135. trace_view: View = View.Empty();
  136. // Represents the pixel space of the entire trace - this is the container
  137. // that we render to. For example, if the container is 1000px wide, the
  138. // pixel space would be [0, 1000]
  139. trace_physical_space: View = View.Empty();
  140. container_physical_space: View = View.Empty();
  141. events: EventStore = {
  142. ['divider resize end']: new Set<VirtualizedViewManagerEvents['divider resize end']>(),
  143. };
  144. row_measurer: DOMWidthMeasurer<TraceTreeNode<TraceTree.NodeValue>> =
  145. new DOMWidthMeasurer();
  146. indicator_label_measurer: DOMWidthMeasurer<TraceTree['indicators'][0]> =
  147. new DOMWidthMeasurer();
  148. text_measurer: TextMeasurer = new TextMeasurer();
  149. resize_observer: ResizeObserver | null = null;
  150. list: VirtualizedList | null = null;
  151. isScrolling: boolean = false;
  152. start_virtualized_index: number = 0;
  153. // HTML refs that we need to keep track of such
  154. // that rendering can be done programmatically
  155. divider: HTMLElement | null = null;
  156. container: HTMLElement | null = null;
  157. indicator_container: HTMLElement | null = null;
  158. intervals: (number | undefined)[] = [];
  159. // We want to render an indicator every 100px, but because we dont track resizing
  160. // of the container, we need to precompute the number of intervals we need to render.
  161. // We'll oversize the count by 3x, assuming no user will ever resize the window to 3x the
  162. // original size.
  163. interval_bars = new Array(Math.ceil(window.innerWidth / 100) * 3).fill(0);
  164. indicators: ({indicator: TraceTree['indicators'][0]; ref: HTMLElement} | undefined)[] =
  165. [];
  166. timeline_indicators: (HTMLElement | undefined)[] = [];
  167. span_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  168. invisible_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  169. span_arrows: (
  170. | {
  171. position: 0 | 1;
  172. ref: HTMLElement;
  173. space: [number, number];
  174. visible: boolean;
  175. }
  176. | undefined
  177. )[] = [];
  178. span_text: ({ref: HTMLElement; space: [number, number]; text: string} | undefined)[] =
  179. [];
  180. // Holds the span to px matrix so we dont keep recalculating it
  181. span_to_px: mat3 = mat3.create();
  182. row_depth_padding: number = 22;
  183. // Column configuration
  184. columns: {
  185. list: ViewColumn;
  186. span_list: ViewColumn;
  187. };
  188. constructor(columns: {
  189. list: Pick<ViewColumn, 'width'>;
  190. span_list: Pick<ViewColumn, 'width'>;
  191. }) {
  192. this.columns = {
  193. list: {...columns.list, column_nodes: [], column_refs: [], translate: [0, 0]},
  194. span_list: {
  195. ...columns.span_list,
  196. column_nodes: [],
  197. column_refs: [],
  198. translate: [0, 0],
  199. },
  200. };
  201. this.onDividerMouseDown = this.onDividerMouseDown.bind(this);
  202. this.onDividerMouseUp = this.onDividerMouseUp.bind(this);
  203. this.onDividerMouseMove = this.onDividerMouseMove.bind(this);
  204. this.onSyncedScrollbarScroll = this.onSyncedScrollbarScroll.bind(this);
  205. this.onWheelZoom = this.onWheelZoom.bind(this);
  206. this.onWheelEnd = this.onWheelEnd.bind(this);
  207. this.onWheelStart = this.onWheelStart.bind(this);
  208. }
  209. on<K extends keyof VirtualizedViewManagerEvents>(
  210. eventName: K,
  211. cb: VirtualizedViewManagerEvents[K]
  212. ): void {
  213. const set = this.events[eventName] as unknown as Set<VirtualizedViewManagerEvents[K]>;
  214. if (set.has(cb)) {
  215. return;
  216. }
  217. set.add(cb);
  218. }
  219. off<K extends keyof VirtualizedViewManagerEvents>(
  220. eventName: K,
  221. cb: VirtualizedViewManagerEvents[K]
  222. ): void {
  223. const set = this.events[eventName] as unknown as Set<VirtualizedViewManagerEvents[K]>;
  224. if (set.has(cb)) {
  225. set.delete(cb);
  226. }
  227. }
  228. dispatch<K extends keyof VirtualizedViewManagerEvents>(
  229. event: K,
  230. ...args: ArgumentTypes<VirtualizedViewManagerEvents[K]>
  231. ): void {
  232. for (const handler of this.events[event]) {
  233. // @ts-expect-error
  234. handler(...args);
  235. }
  236. }
  237. initializeTraceSpace(space: [x: number, y: number, width: number, height: number]) {
  238. this.to_origin = space[0];
  239. this.trace_space = new View(0, 0, space[2], space[3]);
  240. this.trace_view = new View(0, 0, space[2], space[3]);
  241. this.recomputeTimelineIntervals();
  242. this.recomputeSpanToPxMatrix();
  243. }
  244. initializePhysicalSpace(width: number, height: number) {
  245. this.container_physical_space = new View(0, 0, width, height);
  246. this.trace_physical_space = new View(
  247. 0,
  248. 0,
  249. width * this.columns.span_list.width,
  250. height
  251. );
  252. this.recomputeTimelineIntervals();
  253. this.recomputeSpanToPxMatrix();
  254. }
  255. onContainerRef(container: HTMLElement | null) {
  256. if (container) {
  257. this.initialize(container);
  258. } else {
  259. this.teardown();
  260. }
  261. }
  262. dividerScale: 1 | undefined = undefined;
  263. dividerStartVec: [number, number] | null = null;
  264. previousDividerClientVec: [number, number] | null = null;
  265. onDividerMouseDown(event: MouseEvent) {
  266. if (!this.container) {
  267. return;
  268. }
  269. this.dividerScale = this.trace_view.width === this.trace_space.width ? 1 : undefined;
  270. this.dividerStartVec = [event.clientX, event.clientY];
  271. this.previousDividerClientVec = [event.clientX, event.clientY];
  272. this.container.style.userSelect = 'none';
  273. document.addEventListener('mouseup', this.onDividerMouseUp, {passive: true});
  274. document.addEventListener('mousemove', this.onDividerMouseMove, {
  275. passive: true,
  276. });
  277. }
  278. onDividerMouseUp(event: MouseEvent) {
  279. if (!this.container || !this.dividerStartVec) {
  280. return;
  281. }
  282. this.dividerScale = undefined;
  283. const distance = event.clientX - this.dividerStartVec[0];
  284. const distancePercentage = distance / this.container_physical_space.width;
  285. this.columns.list.width = this.columns.list.width + distancePercentage;
  286. this.columns.span_list.width = this.columns.span_list.width - distancePercentage;
  287. this.container.style.userSelect = 'auto';
  288. this.dividerStartVec = null;
  289. this.previousDividerClientVec = null;
  290. this.enqueueOnScrollEndOutOfBoundsCheck();
  291. document.removeEventListener('mouseup', this.onDividerMouseUp);
  292. document.removeEventListener('mousemove', this.onDividerMouseMove);
  293. this.dispatch('divider resize end', this.columns.list.width);
  294. }
  295. onDividerMouseMove(event: MouseEvent) {
  296. if (!this.dividerStartVec || !this.divider || !this.previousDividerClientVec) {
  297. return;
  298. }
  299. const distance = event.clientX - this.dividerStartVec[0];
  300. const distancePercentage = distance / this.container_physical_space.width;
  301. this.trace_physical_space.width =
  302. (this.columns.span_list.width - distancePercentage) *
  303. this.container_physical_space.width;
  304. const physical_distance = this.previousDividerClientVec[0] - event.clientX;
  305. const config_distance_pct = physical_distance / this.trace_physical_space.width;
  306. const config_distance = this.trace_view.width * config_distance_pct;
  307. if (this.dividerScale) {
  308. // just recompute the draw matrix and let the view scale itself
  309. this.recomputeSpanToPxMatrix();
  310. } else {
  311. this.setTraceView({
  312. x: this.trace_view.x - config_distance,
  313. width: this.trace_view.width + config_distance,
  314. });
  315. }
  316. this.recomputeTimelineIntervals();
  317. this.draw({
  318. list: this.columns.list.width + distancePercentage,
  319. span_list: this.columns.span_list.width - distancePercentage,
  320. });
  321. this.previousDividerClientVec = [event.clientX, event.clientY];
  322. }
  323. registerList(list: VirtualizedList | null) {
  324. this.list = list;
  325. }
  326. registerIndicatorContainerRef(ref: HTMLElement | null) {
  327. if (ref) {
  328. ref.style.width = this.columns.span_list.width * 100 + '%';
  329. }
  330. this.indicator_container = ref;
  331. }
  332. registerDividerRef(ref: HTMLElement | null) {
  333. if (!ref) {
  334. if (this.divider) {
  335. this.divider.removeEventListener('mousedown', this.onDividerMouseDown);
  336. }
  337. this.divider = null;
  338. return;
  339. }
  340. this.divider = ref;
  341. this.divider.style.width = `${DIVIDER_WIDTH}px`;
  342. ref.addEventListener('mousedown', this.onDividerMouseDown, {passive: true});
  343. }
  344. registerSpanBarRef(ref: HTMLElement | null, space: [number, number], index: number) {
  345. this.span_bars[index] = ref ? {ref, space} : undefined;
  346. }
  347. registerInvisibleBarRef(
  348. ref: HTMLElement | null,
  349. space: [number, number],
  350. index: number
  351. ) {
  352. this.invisible_bars[index] = ref ? {ref, space} : undefined;
  353. }
  354. registerArrowRef(ref: HTMLElement | null, space: [number, number], index: number) {
  355. this.span_arrows[index] = ref ? {ref, space, visible: false, position: 0} : undefined;
  356. }
  357. registerSpanBarTextRef(
  358. ref: HTMLElement | null,
  359. text: string,
  360. space: [number, number],
  361. index: number
  362. ) {
  363. this.span_text[index] = ref ? {ref, text, space} : undefined;
  364. }
  365. registerColumnRef(
  366. column: string,
  367. ref: HTMLElement | null,
  368. index: number,
  369. node: TraceTreeNode<any>
  370. ) {
  371. if (column === 'list') {
  372. const element = this.columns[column].column_refs[index];
  373. if (ref === undefined && element) {
  374. element.removeEventListener('wheel', this.onSyncedScrollbarScroll);
  375. } else if (ref) {
  376. const scrollableElement = ref.children[0] as HTMLElement | undefined;
  377. if (scrollableElement) {
  378. scrollableElement.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  379. this.row_measurer.enqueueMeasure(node, scrollableElement as HTMLElement);
  380. ref.addEventListener('wheel', this.onSyncedScrollbarScroll, {passive: false});
  381. }
  382. }
  383. }
  384. if (column === 'span_list') {
  385. const element = this.columns[column].column_refs[index];
  386. if (ref === undefined && element) {
  387. element.removeEventListener('wheel', this.onWheelZoom);
  388. } else if (ref) {
  389. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  390. }
  391. }
  392. this.columns[column].column_refs[index] = ref ?? undefined;
  393. this.columns[column].column_nodes[index] = node ?? undefined;
  394. }
  395. registerIndicatorRef(
  396. ref: HTMLElement | null,
  397. index: number,
  398. indicator: TraceTree['indicators'][0]
  399. ) {
  400. if (!ref) {
  401. const element = this.indicators[index]?.ref;
  402. if (element) {
  403. element.removeEventListener('wheel', this.onWheelZoom);
  404. }
  405. this.indicators[index] = undefined;
  406. } else {
  407. this.indicators[index] = {ref, indicator};
  408. }
  409. if (ref) {
  410. const label = ref.children[0] as HTMLElement | undefined;
  411. if (label) {
  412. this.indicator_label_measurer.enqueueMeasure(indicator, label);
  413. }
  414. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  415. ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(
  416. indicator.start
  417. )}px)`;
  418. }
  419. }
  420. registerTimelineIndicatorRef(ref: HTMLElement | null, index: number) {
  421. if (ref) {
  422. this.timeline_indicators[index] = ref;
  423. } else {
  424. this.timeline_indicators[index] = undefined;
  425. }
  426. }
  427. getConfigSpaceCursor(cursor: {x: number; y: number}): [number, number] {
  428. const left_percentage = cursor.x / this.trace_physical_space.width;
  429. const left_view = left_percentage * this.trace_view.width;
  430. return [this.trace_view.x + left_view, 0];
  431. }
  432. onWheelZoom(event: WheelEvent) {
  433. if (event.metaKey) {
  434. event.preventDefault();
  435. if (!this.onWheelEndRaf) {
  436. this.onWheelStart();
  437. }
  438. this.enqueueOnWheelEndRaf();
  439. const scale = 1 - event.deltaY * 0.01 * -1;
  440. const configSpaceCursor = this.getConfigSpaceCursor({
  441. x: event.offsetX,
  442. y: event.offsetY,
  443. });
  444. const center = vec2.fromValues(configSpaceCursor[0], 0);
  445. const centerScaleMatrix = mat3.create();
  446. mat3.fromTranslation(centerScaleMatrix, center);
  447. mat3.scale(centerScaleMatrix, centerScaleMatrix, vec2.fromValues(scale, 1));
  448. mat3.translate(
  449. centerScaleMatrix,
  450. centerScaleMatrix,
  451. vec2.fromValues(-center[0], 0)
  452. );
  453. const newView = this.trace_view.transform(centerScaleMatrix);
  454. this.setTraceView({
  455. x: newView[0],
  456. width: newView[2],
  457. });
  458. this.draw();
  459. } else {
  460. if (!this.onWheelEndRaf) {
  461. this.onWheelStart();
  462. }
  463. this.enqueueOnWheelEndRaf();
  464. const scrollingHorizontally = Math.abs(event.deltaX) >= Math.abs(event.deltaY);
  465. if (event.deltaX !== 0 && event.deltaX !== -0 && scrollingHorizontally) {
  466. event.preventDefault();
  467. }
  468. if (scrollingHorizontally) {
  469. const physical_delta_pct = event.deltaX / this.trace_physical_space.width;
  470. const view_delta = physical_delta_pct * this.trace_view.width;
  471. this.setTraceView({
  472. x: this.trace_view.x + view_delta,
  473. });
  474. this.draw();
  475. }
  476. }
  477. }
  478. onBringRowIntoView(space: [number, number]) {
  479. if (this.zoomIntoSpaceRaf !== null) {
  480. window.cancelAnimationFrame(this.zoomIntoSpaceRaf);
  481. this.zoomIntoSpaceRaf = null;
  482. }
  483. if (space[0] - this.to_origin > this.trace_view.x) {
  484. this.onZoomIntoSpace([
  485. space[0] + space[1] / 2 - this.trace_view.width / 2,
  486. this.trace_view.width,
  487. ]);
  488. } else if (space[0] - this.to_origin < this.trace_view.x) {
  489. this.onZoomIntoSpace([
  490. space[0] + space[1] / 2 - this.trace_view.width / 2,
  491. this.trace_view.width,
  492. ]);
  493. }
  494. }
  495. animateViewTo(node_space: [number, number]) {
  496. const start = node_space[0];
  497. const width = node_space[1] > 0 ? node_space[1] : this.trace_view.width;
  498. const margin = 0.2 * width;
  499. this.setTraceView({x: start - margin - this.to_origin, width: width + margin * 2});
  500. this.draw();
  501. }
  502. zoomIntoSpaceRaf: number | null = null;
  503. onZoomIntoSpace(space: [number, number]) {
  504. if (space[1] <= 0) {
  505. // @TODO implement scrolling to 0 width spaces
  506. return;
  507. }
  508. const distance_x = space[0] - this.to_origin - this.trace_view.x;
  509. const distance_width = this.trace_view.width - space[1];
  510. const start_x = this.trace_view.x;
  511. const start_width = this.trace_view.width;
  512. const start = performance.now();
  513. const rafCallback = (now: number) => {
  514. const elapsed = now - start;
  515. const progress = elapsed / 300;
  516. const eased = easeOutSine(progress);
  517. const x = start_x + distance_x * eased;
  518. const width = start_width - distance_width * eased;
  519. this.setTraceView({x, width});
  520. this.draw();
  521. if (progress < 1) {
  522. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  523. } else {
  524. this.zoomIntoSpaceRaf = null;
  525. this.setTraceView({x: space[0] - this.to_origin, width: space[1]});
  526. this.draw();
  527. }
  528. };
  529. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  530. }
  531. resetZoom() {
  532. this.onZoomIntoSpace([this.to_origin, this.trace_space.width]);
  533. }
  534. onWheelEndRaf: number | null = null;
  535. enqueueOnWheelEndRaf() {
  536. if (this.onWheelEndRaf !== null) {
  537. window.cancelAnimationFrame(this.onWheelEndRaf);
  538. }
  539. const start = performance.now();
  540. const rafCallback = (now: number) => {
  541. const elapsed = now - start;
  542. if (elapsed > 200) {
  543. this.onWheelEnd();
  544. } else {
  545. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  546. }
  547. };
  548. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  549. }
  550. onWheelStart() {
  551. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  552. const span_list = this.columns.span_list.column_refs[i];
  553. if (span_list?.children?.[0]) {
  554. (span_list.children[0] as HTMLElement).style.pointerEvents = 'none';
  555. }
  556. const span_text = this.span_text[i];
  557. if (span_text) {
  558. span_text.ref.style.pointerEvents = 'none';
  559. }
  560. }
  561. for (let i = 0; i < this.indicators.length; i++) {
  562. const indicator = this.indicators[i];
  563. if (indicator?.ref) {
  564. indicator.ref.style.pointerEvents = 'none';
  565. }
  566. }
  567. }
  568. onWheelEnd() {
  569. this.onWheelEndRaf = null;
  570. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  571. const span_list = this.columns.span_list.column_refs[i];
  572. if (span_list?.children?.[0]) {
  573. (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto';
  574. }
  575. const span_text = this.span_text[i];
  576. if (span_text) {
  577. span_text.ref.style.pointerEvents = 'auto';
  578. }
  579. }
  580. for (let i = 0; i < this.indicators.length; i++) {
  581. const indicator = this.indicators[i];
  582. if (indicator?.ref) {
  583. indicator.ref.style.pointerEvents = 'auto';
  584. }
  585. }
  586. }
  587. setTraceView(view: {width?: number; x?: number}) {
  588. // In cases where a trace might have a single error, there is no concept of a timeline
  589. if (this.trace_view.width === 0) {
  590. return;
  591. }
  592. const x = view.x ?? this.trace_view.x;
  593. const width = view.width ?? this.trace_view.width;
  594. this.trace_view.x = clamp(x, 0, this.trace_space.width - width);
  595. this.trace_view.width = clamp(width, 1, this.trace_space.width - this.trace_view.x);
  596. this.recomputeTimelineIntervals();
  597. this.recomputeSpanToPxMatrix();
  598. }
  599. scrollSyncRaf: number | null = null;
  600. onSyncedScrollbarScroll(event: WheelEvent) {
  601. if (this.isScrolling) {
  602. return;
  603. }
  604. const scrollingHorizontally = Math.abs(event.deltaX) >= Math.abs(event.deltaY);
  605. if (event.deltaX !== 0 && event.deltaX !== -0 && scrollingHorizontally) {
  606. event.preventDefault();
  607. } else {
  608. return;
  609. }
  610. if (this.bringRowIntoViewAnimation !== null) {
  611. window.cancelAnimationFrame(this.bringRowIntoViewAnimation);
  612. this.bringRowIntoViewAnimation = null;
  613. }
  614. this.enqueueOnScrollEndOutOfBoundsCheck();
  615. const newTransform = this.clampRowTransform(
  616. this.columns.list.translate[0] - event.deltaX
  617. );
  618. if (newTransform === this.columns.list.translate[0]) {
  619. return;
  620. }
  621. this.columns.list.translate[0] = newTransform;
  622. if (this.scrollSyncRaf) {
  623. window.cancelAnimationFrame(this.scrollSyncRaf);
  624. }
  625. this.scrollSyncRaf = window.requestAnimationFrame(() => {
  626. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  627. const list = this.columns.list.column_refs[i];
  628. if (list?.children?.[0]) {
  629. (list.children[0] as HTMLElement).style.transform =
  630. `translateX(${this.columns.list.translate[0]}px)`;
  631. }
  632. }
  633. });
  634. }
  635. clampRowTransform(transform: number): number {
  636. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  637. const max = this.row_measurer.max - columnWidth + 16;
  638. if (this.row_measurer.max < columnWidth) {
  639. return 0;
  640. }
  641. // Sometimes the wheel event glitches or jumps to a very high value
  642. if (transform > 0) {
  643. return 0;
  644. }
  645. if (transform < -max) {
  646. return -max;
  647. }
  648. return transform;
  649. }
  650. scrollEndSyncRaf: number | null = null;
  651. enqueueOnScrollEndOutOfBoundsCheck() {
  652. if (this.scrollEndSyncRaf !== null) {
  653. window.cancelAnimationFrame(this.scrollEndSyncRaf);
  654. }
  655. const start = performance.now();
  656. const rafCallback = (now: number) => {
  657. const elapsed = now - start;
  658. if (elapsed > 300) {
  659. this.onScrollEndOutOfBoundsCheck();
  660. } else {
  661. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  662. }
  663. };
  664. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  665. }
  666. onScrollEndOutOfBoundsCheck() {
  667. this.scrollEndSyncRaf = null;
  668. const translation = this.columns.list.translate[0];
  669. let min = Number.POSITIVE_INFINITY;
  670. let max = Number.NEGATIVE_INFINITY;
  671. let innerMostNode: TraceTreeNode<any> | undefined;
  672. for (let i = 5; i < this.columns.span_list.column_refs.length - 5; i++) {
  673. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  674. if (width === undefined) {
  675. // this is unlikely to happen, but we should trigger a sync measure event if it does
  676. continue;
  677. }
  678. min = Math.min(min, width);
  679. max = Math.max(max, width);
  680. innerMostNode =
  681. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  682. ? this.columns.list.column_nodes[i]
  683. : innerMostNode;
  684. }
  685. if (innerMostNode) {
  686. if (translation + max < 0) {
  687. this.scrollRowIntoViewHorizontally(innerMostNode);
  688. } else if (
  689. translation + innerMostNode.depth * this.row_depth_padding >
  690. this.columns.list.width * this.container_physical_space.width
  691. ) {
  692. this.scrollRowIntoViewHorizontally(innerMostNode);
  693. }
  694. }
  695. }
  696. isOutsideOfViewOnKeyDown(node: TraceTreeNode<any>, offset_px: number): boolean {
  697. const width = this.row_measurer.cache.get(node);
  698. if (width === undefined) {
  699. // this is unlikely to happen, but we should trigger a sync measure event if it does
  700. return false;
  701. }
  702. const translation = this.columns.list.translate[0];
  703. return (
  704. translation + node.depth * this.row_depth_padding < 0 ||
  705. translation + node.depth * this.row_depth_padding + offset_px >
  706. this.columns.list.width * this.container_physical_space.width
  707. );
  708. }
  709. scrollRowIntoViewHorizontally(
  710. node: TraceTreeNode<any>,
  711. duration: number = 600,
  712. offset_px: number = 0,
  713. position: 'exact' | 'measured' = 'measured'
  714. ) {
  715. const depth_px = -node.depth * this.row_depth_padding + offset_px;
  716. const newTransform =
  717. position === 'exact' ? depth_px : this.clampRowTransform(depth_px);
  718. this.animateScrollColumnTo(newTransform, duration);
  719. }
  720. bringRowIntoViewAnimation: number | null = null;
  721. animateScrollColumnTo(x: number, duration: number) {
  722. const start = performance.now();
  723. const startPosition = this.columns.list.translate[0];
  724. const distance = x - startPosition;
  725. const animate = (now: number) => {
  726. const elapsed = now - start;
  727. const progress = duration > 0 ? elapsed / duration : 1;
  728. const eased = easeOutSine(progress);
  729. const pos = startPosition + distance * eased;
  730. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  731. const list = this.columns.list.column_refs[i];
  732. if (list?.children?.[0]) {
  733. (list.children[0] as HTMLElement).style.transform = `translateX(${pos}px)`;
  734. }
  735. }
  736. if (progress < 1) {
  737. this.columns.list.translate[0] = pos;
  738. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  739. } else {
  740. this.columns.list.translate[0] = x;
  741. }
  742. };
  743. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  744. }
  745. initialize(container: HTMLElement) {
  746. if (this.container !== container && this.resize_observer !== null) {
  747. this.teardown();
  748. }
  749. this.container = container;
  750. this.resize_observer = new ResizeObserver(entries => {
  751. const entry = entries[0];
  752. if (!entry) {
  753. throw new Error('ResizeObserver entry is undefined');
  754. }
  755. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  756. this.draw();
  757. });
  758. this.resize_observer.observe(container);
  759. }
  760. recomputeSpanToPxMatrix() {
  761. const traceViewToSpace = this.trace_space.between(this.trace_view);
  762. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  763. this.span_to_px = mat3.multiply(
  764. this.span_to_px,
  765. traceViewToSpace,
  766. tracePhysicalToView
  767. );
  768. }
  769. computeRelativeLeftPositionFromOrigin(
  770. timestamp: number,
  771. entire_space: [number, number]
  772. ) {
  773. return (timestamp - entire_space[0]) / entire_space[1];
  774. }
  775. recomputeTimelineIntervals() {
  776. if (this.trace_view.width === 0) {
  777. this.intervals[0] = 0;
  778. this.intervals[1] = 0;
  779. for (let i = 2; i < this.intervals.length; i++) {
  780. this.intervals[i] = undefined;
  781. }
  782. return;
  783. }
  784. const tracePhysicalToView = this.trace_physical_space.between(this.trace_view);
  785. const time_at_100 =
  786. tracePhysicalToView[0] * (100 * window.devicePixelRatio) +
  787. tracePhysicalToView[6] -
  788. this.trace_view.x;
  789. computeTimelineIntervals(this.trace_view, time_at_100, this.intervals);
  790. }
  791. readonly span_matrix: [number, number, number, number, number, number] = [
  792. 1, 0, 0, 1, 0, 0,
  793. ];
  794. computeSpanCSSMatrixTransform(
  795. space: [number, number]
  796. ): [number, number, number, number, number, number] {
  797. const scale = space[1] / this.trace_view.width;
  798. this.span_matrix[0] = Math.max(
  799. scale,
  800. (1 * this.span_to_px[0]) / this.trace_view.width
  801. );
  802. this.span_matrix[3] = 1;
  803. this.span_matrix[4] =
  804. (space[0] - this.to_origin) / this.span_to_px[0] -
  805. this.trace_view.x / this.span_to_px[0];
  806. return this.span_matrix;
  807. }
  808. scrollToEventID(
  809. eventId: string,
  810. tree: TraceTree,
  811. rerender: () => void,
  812. {api, organization}: {api: Client; organization: Organization}
  813. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  814. const node = findInTreeByEventId(tree.root, eventId);
  815. if (!node) {
  816. return Promise.resolve(null);
  817. }
  818. return this.scrollToPath(tree, node.path, rerender, {api, organization}).then(
  819. async result => {
  820. // When users are coming off an eventID link, we want to fetch the children
  821. // of the node that the eventID points to. This is because the eventID link
  822. // only points to the transaction, but we want to fetch the children of the
  823. // transaction to show the user the list of spans in that transaction
  824. if (result?.node?.canFetch) {
  825. await tree.zoomIn(result.node, true, {api, organization}).catch(_e => {
  826. Sentry.captureMessage('Failed to fetch children of eventId on mount');
  827. });
  828. return result;
  829. }
  830. return null;
  831. }
  832. );
  833. }
  834. scrollToPath(
  835. tree: TraceTree,
  836. scrollQueue: TraceTree.NodePath[],
  837. rerender: () => void,
  838. {api, organization}: {api: Client; organization: Organization}
  839. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  840. const segments = [...scrollQueue];
  841. const list = this.list;
  842. if (!list) {
  843. return Promise.resolve(null);
  844. }
  845. if (segments.length === 1 && segments[0] === 'trace:root') {
  846. rerender();
  847. this.scrollToRow(0);
  848. return Promise.resolve({index: 0, node: tree.root.children[0]});
  849. }
  850. // Keep parent reference as we traverse the tree so that we can only
  851. // perform searching in the current level and not the entire tree
  852. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  853. const scrollToRow = async (): Promise<{
  854. index: number;
  855. node: TraceTreeNode<TraceTree.NodeValue>;
  856. } | null | null> => {
  857. const path = segments.pop();
  858. let current = findInTreeFromSegment(parent, path!);
  859. if (!current) {
  860. // Some parts of the codebase link to span:span_id, txn:event_id, where span_id is
  861. // actally stored on the txn:event_id node. Since we cant tell from the link itself
  862. // that this is happening, we will perform a final check to see if we've actually already
  863. // arrived to the node in the previous search call.
  864. if (path) {
  865. const [type, id] = path.split(':');
  866. if (
  867. type === 'span' &&
  868. isTransactionNode(parent) &&
  869. parent.value.span_id === id
  870. ) {
  871. current = parent;
  872. }
  873. }
  874. if (!current) {
  875. Sentry.captureMessage('Failed to scroll to node in trace tree');
  876. return null;
  877. }
  878. }
  879. // Reassing the parent to the current node so that
  880. // searching narrows down to the current level
  881. // and we dont need to search the entire tree each time
  882. parent = current;
  883. if (isTransactionNode(current)) {
  884. const nextSegment = segments[segments.length - 1];
  885. if (
  886. nextSegment?.startsWith('span:') ||
  887. nextSegment?.startsWith('ag:') ||
  888. nextSegment?.startsWith('ms:')
  889. ) {
  890. await tree.zoomIn(current, true, {
  891. api,
  892. organization,
  893. });
  894. return scrollToRow();
  895. }
  896. }
  897. if (isAutogroupedNode(current) && segments.length > 0) {
  898. tree.expand(current, true);
  899. return scrollToRow();
  900. }
  901. if (segments.length > 0) {
  902. return scrollToRow();
  903. }
  904. // We are at the last path segment (the node that the user clicked on)
  905. // and we should scroll the view to this node.
  906. const index = tree.list.findIndex(node => node === current);
  907. if (index === -1) {
  908. throw new Error("Couldn't find node in list");
  909. }
  910. rerender();
  911. this.scrollToRow(index);
  912. return {index, node: current};
  913. };
  914. return scrollToRow();
  915. }
  916. scrollToRow(index: number) {
  917. if (!this.list) {
  918. return;
  919. }
  920. this.list.scrollToRow(index);
  921. }
  922. computeTransformXFromTimestamp(timestamp: number): number {
  923. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  924. }
  925. computeSpanTextPlacement(span_space: [number, number], text: string): [number, number] {
  926. const TEXT_PADDING = 2;
  927. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  928. const width = this.text_measurer.measure(text);
  929. // precomput all anchor points aot, so we make the control flow more readable.
  930. // this wastes some cycles, but it's not a big deal as computers are fast when
  931. // it comes to simple arithmetic.
  932. const right_outside =
  933. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  934. const right_inside =
  935. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  936. width -
  937. TEXT_PADDING;
  938. const left_outside =
  939. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  940. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  941. const window_right =
  942. this.computeTransformXFromTimestamp(
  943. this.to_origin + this.trace_view.left + this.trace_view.width
  944. ) -
  945. width -
  946. TEXT_PADDING;
  947. const window_left =
  948. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  949. TEXT_PADDING;
  950. const view_left = this.trace_view.x;
  951. const view_right = view_left + this.trace_view.width;
  952. const span_left = span_space[0] - this.to_origin;
  953. const span_right = span_left + span_space[1];
  954. const space_right = view_right - span_right;
  955. const space_left = span_left - view_left;
  956. // Span is completely outside of the view on the left side
  957. if (span_right < this.trace_view.x) {
  958. return anchor_left ? [1, right_inside] : [0, right_outside];
  959. }
  960. // Span is completely outside of the view on the right side
  961. if (span_left > this.trace_view.right) {
  962. return anchor_left ? [0, left_outside] : [1, left_inside];
  963. }
  964. // Span "spans" the entire view
  965. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  966. return anchor_left ? [1, window_left] : [1, window_right];
  967. }
  968. const full_span_px_width = span_space[1] / this.span_to_px[0];
  969. if (anchor_left) {
  970. // While we have space on the left, place the text there
  971. if (space_left > 0) {
  972. return [0, left_outside];
  973. }
  974. const distance = span_right - this.trace_view.left;
  975. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  976. // If the text fits inside the visible portion of the span, anchor it to the left
  977. // side of the window so that it is visible while the user pans the view
  978. if (visible_width - TEXT_PADDING >= width) {
  979. return [1, window_left];
  980. }
  981. // If the text doesnt fit inside the visible portion of the span,
  982. // anchor it to the inside right place in the span.
  983. return [1, right_inside];
  984. }
  985. // While we have space on the right, place the text there
  986. if (space_right > 0) {
  987. return [0, right_outside];
  988. }
  989. // If text fits inside the span
  990. if (full_span_px_width > width) {
  991. const distance = span_right - this.trace_view.right;
  992. const visible_width =
  993. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  994. // If the text fits inside the visible portion of the span, anchor it to the right
  995. // side of the window so that it is visible while the user pans the view
  996. if (visible_width - TEXT_PADDING >= width) {
  997. return [1, window_right];
  998. }
  999. // If the text doesnt fit inside the visible portion of the span,
  1000. // anchor it to the inside left of the span
  1001. return [1, left_inside];
  1002. }
  1003. return [0, right_outside];
  1004. }
  1005. draw(options: {list?: number; span_list?: number} = {}) {
  1006. const list_width = options.list ?? this.columns.list.width;
  1007. const span_list_width = options.span_list ?? this.columns.span_list.width;
  1008. if (this.divider) {
  1009. this.divider.style.transform = `translateX(${
  1010. list_width * this.container_physical_space.width - DIVIDER_WIDTH / 2 - 1
  1011. }px)`;
  1012. }
  1013. if (this.indicator_container) {
  1014. this.indicator_container.style.width = span_list_width * 100 + '%';
  1015. }
  1016. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  1017. const list = this.columns.list.column_refs[i];
  1018. if (list) list.style.width = list_width * 100 + '%';
  1019. const span = this.columns.span_list.column_refs[i];
  1020. if (span) span.style.width = span_list_width * 100 + '%';
  1021. const span_bar = this.span_bars[i];
  1022. const span_arrow = this.span_arrows[i];
  1023. if (span_bar) {
  1024. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  1025. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1026. span_bar.ref.style.setProperty(
  1027. '--inverse-span-scale',
  1028. 1 / span_transform[0] + ''
  1029. );
  1030. }
  1031. const span_text = this.span_text[i];
  1032. if (span_text) {
  1033. const [inside, text_transform] = this.computeSpanTextPlacement(
  1034. span_text.space,
  1035. span_text.text
  1036. );
  1037. if (text_transform === null) {
  1038. continue;
  1039. }
  1040. span_text.ref.style.color = inside ? 'white' : '';
  1041. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1042. if (span_arrow && span_bar) {
  1043. const outside_left =
  1044. span_bar.space[0] - this.to_origin + span_bar.space[1] < this.trace_view.x;
  1045. const outside_right =
  1046. span_bar.space[0] - this.to_origin > this.trace_view.right;
  1047. const visible = outside_left || outside_right;
  1048. if (visible !== span_arrow.visible) {
  1049. span_arrow.visible = visible;
  1050. span_arrow.position = outside_left ? 0 : 1;
  1051. if (visible) {
  1052. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1053. } else {
  1054. span_arrow.ref.className = 'TraceArrow';
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. for (let i = 0; i < this.invisible_bars.length; i++) {
  1061. const invisible_bar = this.invisible_bars[i];
  1062. if (invisible_bar) {
  1063. invisible_bar.ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(invisible_bar.space[0])}px)`;
  1064. }
  1065. }
  1066. let start_indicator = 0;
  1067. let end_indicator = this.indicators.length;
  1068. while (start_indicator < this.indicators.length - 1) {
  1069. const indicator = this.indicators[start_indicator];
  1070. if (!indicator?.indicator) {
  1071. start_indicator++;
  1072. continue;
  1073. }
  1074. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1075. start_indicator++;
  1076. continue;
  1077. }
  1078. break;
  1079. }
  1080. while (end_indicator > start_indicator) {
  1081. const last_indicator = this.indicators[end_indicator - 1];
  1082. if (!last_indicator) {
  1083. end_indicator--;
  1084. continue;
  1085. }
  1086. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1087. end_indicator--;
  1088. continue;
  1089. }
  1090. break;
  1091. }
  1092. start_indicator = Math.max(0, start_indicator - 1);
  1093. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1094. for (let i = 0; i < this.indicators.length; i++) {
  1095. const entry = this.indicators[i];
  1096. if (!entry) {
  1097. continue;
  1098. }
  1099. if (i < start_indicator || i > end_indicator) {
  1100. entry.ref.style.opacity = '0';
  1101. continue;
  1102. }
  1103. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1104. const label = entry.ref.children[0] as HTMLElement | undefined;
  1105. const indicator_max = this.trace_physical_space.width + 1;
  1106. const indicator_min = -1;
  1107. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1108. const clamped_transform = clamp(transform, -1, indicator_max);
  1109. if (label_width === undefined) {
  1110. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1111. continue;
  1112. }
  1113. if (label) {
  1114. const PADDING = 2;
  1115. const label_window_left = PADDING;
  1116. const label_window_right = -label_width - PADDING;
  1117. if (transform < -1) {
  1118. label.style.transform = `translateX(${label_window_left}px)`;
  1119. } else if (transform >= indicator_max) {
  1120. label.style.transform = `translateX(${label_window_right}px)`;
  1121. } else {
  1122. const space_left = transform - PADDING - label_width / 2;
  1123. const space_right = transform + label_width / 2;
  1124. if (space_left < 0) {
  1125. const left = -label_width / 2 + Math.abs(space_left);
  1126. label.style.transform = `translateX(${left - 1}px)`;
  1127. } else if (space_right > this.trace_physical_space.width) {
  1128. const right =
  1129. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1130. label.style.transform = `translateX(${right}px)`;
  1131. } else {
  1132. label.style.transform = `translateX(${-label_width / 2}px)`;
  1133. }
  1134. }
  1135. }
  1136. entry.ref.style.opacity = '1';
  1137. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  1138. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1139. }
  1140. // Renders timeline indicators and labels
  1141. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1142. const indicator = this.timeline_indicators[i];
  1143. // Special case for when the timeline is empty - we want to show the first and last
  1144. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1145. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1146. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1147. if (i === 0 && this.intervals[0] === 0 && this.intervals[1] === 0) {
  1148. const first = this.timeline_indicators[0];
  1149. const last = this.timeline_indicators[1];
  1150. if (first && last) {
  1151. first.style.opacity = '1';
  1152. last.style.opacity = '1';
  1153. first.style.transform = `translateX(0)`;
  1154. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1155. // side of the indicator, we need to offset it by the width of the label to make it look like
  1156. // it is at the end of the timeline
  1157. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1158. const firstLabel = first.children[0] as HTMLElement | undefined;
  1159. if (firstLabel) {
  1160. firstLabel.textContent = '0.00ms';
  1161. }
  1162. const lastLabel = last.children[0] as HTMLElement | undefined;
  1163. const lastLine = last.children[1] as HTMLElement | undefined;
  1164. if (lastLine && lastLabel) {
  1165. lastLabel.textContent = '0.00ms';
  1166. lastLine.style.opacity = '0';
  1167. i = 1;
  1168. }
  1169. continue;
  1170. }
  1171. }
  1172. if (indicator) {
  1173. const interval = this.intervals[i];
  1174. if (interval === undefined) {
  1175. indicator.style.opacity = '0';
  1176. continue;
  1177. }
  1178. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1179. indicator.style.opacity = '1';
  1180. indicator.style.transform = `translateX(${placement}px)`;
  1181. const label = indicator.children[0] as HTMLElement | undefined;
  1182. const duration = getDuration(interval / 1000, 2, true);
  1183. if (label && label?.textContent !== duration) {
  1184. label.textContent = duration;
  1185. }
  1186. }
  1187. }
  1188. }
  1189. teardown() {
  1190. if (this.resize_observer) {
  1191. this.resize_observer.disconnect();
  1192. }
  1193. }
  1194. }
  1195. // The backing cache should be a proper LRU cache,
  1196. // so we dont end up storing an infinite amount of elements
  1197. class DOMWidthMeasurer<T> {
  1198. cache: Map<T, number> = new Map();
  1199. elements: HTMLElement[] = [];
  1200. queue: [T, HTMLElement][] = [];
  1201. drainRaf: number | null = null;
  1202. max: number = 0;
  1203. constructor() {
  1204. this.drain = this.drain.bind(this);
  1205. }
  1206. enqueueMeasure(node: T, element: HTMLElement) {
  1207. if (this.cache.has(node)) {
  1208. return;
  1209. }
  1210. this.queue.push([node, element]);
  1211. if (this.drainRaf !== null) {
  1212. window.cancelAnimationFrame(this.drainRaf);
  1213. }
  1214. this.drainRaf = window.requestAnimationFrame(this.drain);
  1215. }
  1216. drain() {
  1217. for (const [node, element] of this.queue) {
  1218. this.measure(node, element);
  1219. }
  1220. }
  1221. measure(node: T, element: HTMLElement): number {
  1222. const cache = this.cache.get(node);
  1223. if (cache !== undefined) {
  1224. return cache;
  1225. }
  1226. const width = element.getBoundingClientRect().width;
  1227. if (width > this.max) {
  1228. this.max = width;
  1229. }
  1230. this.cache.set(node, width);
  1231. return width;
  1232. }
  1233. }
  1234. // The backing cache should be a proper LRU cache,
  1235. // so we dont end up storing an infinite amount of elements
  1236. class TextMeasurer {
  1237. queue: string[] = [];
  1238. drainRaf: number | null = null;
  1239. cache: Map<string, number> = new Map();
  1240. ctx: CanvasRenderingContext2D;
  1241. number: number = 0;
  1242. dot: number = 0;
  1243. duration: Record<string, number> = {};
  1244. constructor() {
  1245. this.drain = this.drain.bind(this);
  1246. const canvas = document.createElement('canvas');
  1247. const ctx = canvas.getContext('2d');
  1248. if (!ctx) {
  1249. throw new Error('Canvas 2d context is not available');
  1250. }
  1251. canvas.width = 50 * window.devicePixelRatio ?? 1;
  1252. canvas.height = 50 * window.devicePixelRatio ?? 1;
  1253. this.ctx = ctx;
  1254. ctx.font = '11px' + theme.text.family;
  1255. this.dot = this.ctx.measureText('.').width;
  1256. for (let i = 0; i < 10; i++) {
  1257. const measurement = this.ctx.measureText(i.toString());
  1258. this.number = Math.max(this.number, measurement.width);
  1259. }
  1260. for (const duration of ['ns', 'ms', 's', 'm', 'h', 'd']) {
  1261. this.duration[duration] = this.ctx.measureText(duration).width;
  1262. }
  1263. }
  1264. drain() {
  1265. for (const string of this.queue) {
  1266. this.measure(string);
  1267. }
  1268. }
  1269. computeStringLength(string: string): number {
  1270. let width = 0;
  1271. for (let i = 0; i < string.length; i++) {
  1272. switch (string[i]) {
  1273. case '.':
  1274. width += this.dot;
  1275. break;
  1276. case '0':
  1277. case '1':
  1278. case '2':
  1279. case '3':
  1280. case '4':
  1281. case '5':
  1282. case '6':
  1283. case '7':
  1284. case '8':
  1285. case '9':
  1286. width += this.number;
  1287. break;
  1288. default:
  1289. const remaining = string.slice(i);
  1290. if (this.duration[remaining]) {
  1291. width += this.duration[remaining];
  1292. return width;
  1293. }
  1294. }
  1295. }
  1296. return width;
  1297. }
  1298. measure(string: string): number {
  1299. const cached_width = this.cache.get(string);
  1300. if (cached_width !== undefined) {
  1301. return cached_width;
  1302. }
  1303. const width = this.computeStringLength(string);
  1304. this.cache.set(string, width);
  1305. return width;
  1306. }
  1307. }
  1308. export class VirtualizedList {
  1309. container: HTMLElement | null = null;
  1310. scrollHeight: number = 0;
  1311. scrollTop: number = 0;
  1312. scrollToRow(index: number, anchor?: 'top') {
  1313. if (!this.container) {
  1314. return;
  1315. }
  1316. if (anchor === 'top') {
  1317. this.container.scrollTop = index * 24;
  1318. return;
  1319. }
  1320. const position = index * 24;
  1321. const top = this.container.scrollTop;
  1322. const height = this.scrollHeight;
  1323. if (position < top) {
  1324. // Row is above the view
  1325. this.container.scrollTop = index * 24;
  1326. } else if (position > top + height) {
  1327. // Row is under the view
  1328. this.container.scrollTop = index * 24 - height + 24;
  1329. } else {
  1330. return;
  1331. }
  1332. }
  1333. }
  1334. interface UseVirtualizedListProps {
  1335. container: HTMLElement | null;
  1336. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1337. manager: VirtualizedViewManager;
  1338. render: (item: VirtualizedRow) => React.ReactNode;
  1339. }
  1340. interface UseVirtualizedListResult {
  1341. list: VirtualizedList;
  1342. rendered: React.ReactNode[];
  1343. virtualized: VirtualizedRow[];
  1344. }
  1345. export const useVirtualizedList = (
  1346. props: UseVirtualizedListProps
  1347. ): UseVirtualizedListResult => {
  1348. const list = useRef<VirtualizedList | null>();
  1349. const scrollTopRef = useRef<number>(0);
  1350. const scrollHeightRef = useRef<number>(0);
  1351. const scrollContainerRef = useRef<HTMLElement | null>(null);
  1352. const renderCache = useRef<Map<number, React.ReactNode>>();
  1353. const styleCache = useRef<Map<number, React.CSSProperties>>();
  1354. const resizeObserverRef = useRef<ResizeObserver | null>(null);
  1355. if (!styleCache.current) {
  1356. styleCache.current = new Map();
  1357. }
  1358. if (!renderCache.current) {
  1359. renderCache.current = new Map();
  1360. }
  1361. const [items, setItems] = useState<{
  1362. rendered: React.ReactNode[];
  1363. virtualized: VirtualizedRow[];
  1364. }>({rendered: [], virtualized: []});
  1365. if (!list.current) {
  1366. list.current = new VirtualizedList();
  1367. props.manager.registerList(list.current);
  1368. }
  1369. const renderRef = useRef<(item: VirtualizedRow) => React.ReactNode>(props.render);
  1370. renderRef.current = props.render;
  1371. const itemsRef = useRef<ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>>(props.items);
  1372. itemsRef.current = props.items;
  1373. const managerRef = useRef<VirtualizedViewManager>(props.manager);
  1374. managerRef.current = props.manager;
  1375. useLayoutEffect(() => {
  1376. if (!props.container) {
  1377. return;
  1378. }
  1379. const scrollContainer = props.container.children[0] as HTMLElement | null;
  1380. if (!scrollContainer) {
  1381. throw new Error(
  1382. 'Virtualized list container has to render a scroll container as its first child.'
  1383. );
  1384. }
  1385. }, [props.container, props.items.length]);
  1386. useLayoutEffect(() => {
  1387. if (!props.container || !list.current) {
  1388. return;
  1389. }
  1390. list.current.container = props.container;
  1391. if (resizeObserverRef.current) {
  1392. resizeObserverRef.current.disconnect();
  1393. }
  1394. const resizeObserver = new ResizeObserver(elements => {
  1395. // We only care about changes to the height of the scroll container,
  1396. // if it has not changed then do not update the scroll height.
  1397. styleCache.current?.clear();
  1398. renderCache.current?.clear();
  1399. scrollHeightRef.current = elements[0].contentRect.height;
  1400. if (list.current) {
  1401. list.current.scrollHeight = scrollHeightRef.current;
  1402. }
  1403. const recomputedItems = findRenderedItems({
  1404. scrollTop: scrollTopRef.current,
  1405. items: itemsRef.current,
  1406. overscroll: 5,
  1407. rowHeight: 24,
  1408. scrollHeight: scrollHeightRef.current,
  1409. styleCache: styleCache.current!,
  1410. renderCache: renderCache.current!,
  1411. render: renderRef.current,
  1412. manager: managerRef.current,
  1413. });
  1414. setItems(recomputedItems);
  1415. });
  1416. resizeObserver.observe(props.container);
  1417. resizeObserverRef.current = resizeObserver;
  1418. }, [props.container]);
  1419. const rafId = useRef<number | null>(null);
  1420. const pointerEventsRaf = useRef<{id: number} | null>(null);
  1421. useLayoutEffect(() => {
  1422. if (!list.current || !props.container) {
  1423. return undefined;
  1424. }
  1425. if (props.container && !scrollContainerRef.current) {
  1426. scrollContainerRef.current = props.container.children[0] as HTMLElement | null;
  1427. }
  1428. props.container.style.height = '100%';
  1429. props.container.style.overflow = 'auto';
  1430. props.container.style.position = 'relative';
  1431. props.container.style.willChange = 'transform';
  1432. props.container.style.overscrollBehavior = 'none';
  1433. scrollContainerRef.current!.style.overflow = 'hidden';
  1434. scrollContainerRef.current!.style.position = 'relative';
  1435. scrollContainerRef.current!.style.willChange = 'transform';
  1436. scrollContainerRef.current!.style.height = `${props.items.length * 24}px`;
  1437. const onScroll = event => {
  1438. if (!list.current) {
  1439. return;
  1440. }
  1441. if (rafId.current !== null) {
  1442. window.cancelAnimationFrame(rafId.current);
  1443. }
  1444. managerRef.current.isScrolling = true;
  1445. managerRef.current.enqueueOnScrollEndOutOfBoundsCheck();
  1446. rafId.current = window.requestAnimationFrame(() => {
  1447. scrollTopRef.current = Math.max(0, event.target?.scrollTop ?? 0);
  1448. const recomputedItems = findRenderedItems({
  1449. scrollTop: scrollTopRef.current,
  1450. items: props.items,
  1451. overscroll: 5,
  1452. rowHeight: 24,
  1453. scrollHeight: scrollHeightRef.current,
  1454. styleCache: styleCache.current!,
  1455. renderCache: renderCache.current!,
  1456. render: renderRef.current,
  1457. manager: managerRef.current,
  1458. });
  1459. setItems(recomputedItems);
  1460. });
  1461. if (!pointerEventsRaf.current && scrollContainerRef.current) {
  1462. scrollContainerRef.current.style.pointerEvents = 'none';
  1463. }
  1464. if (pointerEventsRaf.current) {
  1465. window.cancelAnimationFrame(pointerEventsRaf.current.id);
  1466. }
  1467. pointerEventsRaf.current = requestAnimationTimeout(() => {
  1468. styleCache.current?.clear();
  1469. renderCache.current?.clear();
  1470. managerRef.current.isScrolling = false;
  1471. const recomputedItems = findRenderedItems({
  1472. scrollTop: scrollTopRef.current,
  1473. items: props.items,
  1474. overscroll: 5,
  1475. rowHeight: 24,
  1476. scrollHeight: scrollHeightRef.current,
  1477. styleCache: styleCache.current!,
  1478. renderCache: renderCache.current!,
  1479. render: renderRef.current,
  1480. manager: managerRef.current,
  1481. });
  1482. setItems(recomputedItems);
  1483. if (list.current && scrollContainerRef.current) {
  1484. scrollContainerRef.current.style.pointerEvents = 'auto';
  1485. pointerEventsRaf.current = null;
  1486. }
  1487. }, 50);
  1488. };
  1489. props.container.addEventListener('scroll', onScroll, {passive: true});
  1490. return () => {
  1491. props.container?.removeEventListener('scroll', onScroll);
  1492. };
  1493. }, [props.container, props.items, props.items.length]);
  1494. useLayoutEffect(() => {
  1495. if (!list.current || !styleCache.current || !renderCache.current) {
  1496. return;
  1497. }
  1498. styleCache.current.clear();
  1499. renderCache.current.clear();
  1500. const recomputedItems = findRenderedItems({
  1501. scrollTop: scrollTopRef.current,
  1502. items: props.items,
  1503. overscroll: 5,
  1504. rowHeight: 24,
  1505. scrollHeight: scrollHeightRef.current,
  1506. styleCache: styleCache.current!,
  1507. renderCache: renderCache.current,
  1508. render: renderRef.current,
  1509. manager: managerRef.current,
  1510. });
  1511. setItems(recomputedItems);
  1512. }, [props.items, props.items.length, props.render]);
  1513. return {
  1514. virtualized: items.virtualized,
  1515. rendered: items.rendered,
  1516. list: list.current!,
  1517. };
  1518. };
  1519. export interface VirtualizedRow {
  1520. index: number;
  1521. item: TraceTreeNode<TraceTree.NodeValue>;
  1522. key: number;
  1523. style: React.CSSProperties;
  1524. }
  1525. function findRenderedItems({
  1526. items,
  1527. overscroll,
  1528. rowHeight,
  1529. scrollHeight,
  1530. scrollTop,
  1531. styleCache,
  1532. renderCache,
  1533. render,
  1534. manager,
  1535. }: {
  1536. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1537. manager: VirtualizedViewManager;
  1538. overscroll: number;
  1539. render: (arg: VirtualizedRow) => React.ReactNode;
  1540. renderCache: Map<number, React.ReactNode>;
  1541. rowHeight: number;
  1542. scrollHeight: number;
  1543. scrollTop: number;
  1544. styleCache: Map<number, React.CSSProperties>;
  1545. }): {rendered: React.ReactNode[]; virtualized: VirtualizedRow[]} {
  1546. // This is overscroll height for single direction, when computing the total,
  1547. // we need to multiply this by 2 because we overscroll in both directions.
  1548. const OVERSCROLL_HEIGHT = overscroll * rowHeight;
  1549. const virtualized: VirtualizedRow[] = [];
  1550. const rendered: React.ReactNode[] = [];
  1551. // Clamp viewport to scrollHeight bounds [0, length * rowHeight] because some browsers may fire
  1552. // scrollTop with negative values when the user scrolls up past the top of the list (overscroll behavior)
  1553. const viewport = {
  1554. top: Math.max(scrollTop - OVERSCROLL_HEIGHT, 0),
  1555. bottom: Math.min(
  1556. scrollTop + scrollHeight + OVERSCROLL_HEIGHT,
  1557. items.length * rowHeight
  1558. ),
  1559. };
  1560. // Points to the position inside the visible array
  1561. let visibleItemIndex = 0;
  1562. // Points to the currently iterated item
  1563. let indexPointer = findOptimisticStartIndex({
  1564. items,
  1565. viewport,
  1566. scrollTop,
  1567. rowHeight,
  1568. overscroll,
  1569. });
  1570. manager.start_virtualized_index = indexPointer;
  1571. // Max number of visible items in our list
  1572. const MAX_VISIBLE_ITEMS = Math.ceil((scrollHeight + OVERSCROLL_HEIGHT * 2) / rowHeight);
  1573. const ALL_ITEMS = items.length;
  1574. // While number of visible items is less than max visible items, and we haven't reached the end of the list
  1575. while (visibleItemIndex < MAX_VISIBLE_ITEMS && indexPointer < ALL_ITEMS) {
  1576. const elementTop = indexPointer * rowHeight;
  1577. const elementBottom = elementTop + rowHeight;
  1578. // An element is inside a viewport if the top of the element is below the top of the viewport
  1579. // and the bottom of the element is above the bottom of the viewport
  1580. if (elementTop >= viewport.top && elementBottom <= viewport.bottom) {
  1581. let style = styleCache.get(indexPointer);
  1582. if (!style) {
  1583. style = {position: 'absolute', top: elementTop};
  1584. styleCache.set(indexPointer, style);
  1585. }
  1586. const virtualizedRow: VirtualizedRow = {
  1587. key: indexPointer,
  1588. style,
  1589. index: indexPointer,
  1590. item: items[indexPointer],
  1591. };
  1592. virtualized[visibleItemIndex] = virtualizedRow;
  1593. const renderedRow = renderCache.get(indexPointer) || render(virtualizedRow);
  1594. rendered[visibleItemIndex] = renderedRow;
  1595. renderCache.set(indexPointer, renderedRow);
  1596. visibleItemIndex++;
  1597. }
  1598. indexPointer++;
  1599. }
  1600. return {rendered, virtualized};
  1601. }
  1602. export function findOptimisticStartIndex({
  1603. items,
  1604. overscroll,
  1605. rowHeight,
  1606. scrollTop,
  1607. viewport,
  1608. }: {
  1609. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1610. overscroll: number;
  1611. rowHeight: number;
  1612. scrollTop: number;
  1613. viewport: {bottom: number; top: number};
  1614. }): number {
  1615. if (!items.length || viewport.top === 0) {
  1616. return 0;
  1617. }
  1618. return Math.max(Math.floor(scrollTop / rowHeight) - overscroll, 0);
  1619. }
  1620. function findInTreeFromSegment(
  1621. start: TraceTreeNode<TraceTree.NodeValue>,
  1622. segment: TraceTree.NodePath
  1623. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1624. const [type, id] = segment.split(':');
  1625. if (!type || !id) {
  1626. throw new TypeError('Node path must be in the format of `type:id`');
  1627. }
  1628. return TraceTreeNode.Find(start, node => {
  1629. if (type === 'txn' && isTransactionNode(node)) {
  1630. return node.value.event_id === id;
  1631. }
  1632. if (type === 'span' && isSpanNode(node)) {
  1633. return node.value.span_id === id;
  1634. }
  1635. if (type === 'ag' && isAutogroupedNode(node)) {
  1636. if (isParentAutogroupedNode(node)) {
  1637. return node.head.value.span_id === id || node.tail.value.span_id === id;
  1638. }
  1639. if (isSiblingAutogroupedNode(node)) {
  1640. const child = node.children[0];
  1641. if (isSpanNode(child)) {
  1642. return child.value.span_id === id;
  1643. }
  1644. }
  1645. }
  1646. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1647. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1648. }
  1649. if (type === 'error' && isTraceErrorNode(node)) {
  1650. return node.value.event_id === id;
  1651. }
  1652. return false;
  1653. });
  1654. }
  1655. function hasEventWithEventId(
  1656. node: TraceTreeNode<TraceTree.NodeValue>,
  1657. eventId: string
  1658. ): boolean {
  1659. // Skip trace nodes since they accumulate all errors and performance issues
  1660. // in the trace and is not an event.
  1661. if (isTraceNode(node)) {
  1662. return false;
  1663. }
  1664. // Search in errors
  1665. if (node.errors.size > 0) {
  1666. for (const e of node.errors) {
  1667. if (e.event_id === eventId) {
  1668. return true;
  1669. }
  1670. }
  1671. }
  1672. // Search in performance issues
  1673. if (node.performance_issues.size > 0) {
  1674. for (const p of node.performance_issues) {
  1675. if (p.event_id === eventId) {
  1676. return true;
  1677. }
  1678. }
  1679. }
  1680. // Check if we are maybe looking for the profile_id
  1681. if (node.value && 'profile_id' in node.value && node.value.profile_id === eventId) {
  1682. return true;
  1683. }
  1684. return false;
  1685. }
  1686. function findInTreeByEventId(start: TraceTreeNode<TraceTree.NodeValue>, eventId: string) {
  1687. return TraceTreeNode.Find(start, node => {
  1688. if (isTransactionNode(node)) {
  1689. if (node.value.event_id === eventId) {
  1690. return true;
  1691. }
  1692. } else if (isSpanNode(node)) {
  1693. return node.value.span_id === eventId;
  1694. } else if (isTraceErrorNode(node)) {
  1695. return node.value.event_id === eventId;
  1696. }
  1697. return hasEventWithEventId(node, eventId);
  1698. });
  1699. }