virtualizedViewManager.tsx 61 KB

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