virtualizedViewManager.tsx 62 KB

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