virtualizedViewManager.tsx 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. import {mat3, vec2} from 'gl-matrix';
  2. import {getDuration} from 'sentry/utils/formatters';
  3. import clamp from 'sentry/utils/number/clamp';
  4. import {requestAnimationTimeout} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  5. import type {
  6. TraceTree,
  7. TraceTreeNode,
  8. } from 'sentry/views/performance/newTraceDetails/traceModels/traceTree';
  9. import {TraceRowWidthMeasurer} from 'sentry/views/performance/newTraceDetails/traceRenderers/traceRowWidthMeasurer';
  10. import {TraceTextMeasurer} from 'sentry/views/performance/newTraceDetails/traceRenderers/traceTextMeasurer';
  11. import {TraceView} from 'sentry/views/performance/newTraceDetails/traceRenderers/traceView';
  12. const DIVIDER_WIDTH = 6;
  13. function easeOutSine(x: number): number {
  14. return Math.sin((x * Math.PI) / 2);
  15. }
  16. type ViewColumn = {
  17. column_nodes: TraceTreeNode<TraceTree.NodeValue>[];
  18. column_refs: (HTMLElement | undefined)[];
  19. translate: [number, number];
  20. width: number;
  21. };
  22. type ArgumentTypes<F> = F extends (...args: infer A) => any ? A : never;
  23. type EventStore = {
  24. [K in keyof VirtualizedViewManagerEvents]: Set<VirtualizedViewManagerEvents[K]>;
  25. };
  26. interface VirtualizedViewManagerEvents {
  27. ['divider resize end']: (list_width: number) => void;
  28. ['virtualized list init']: () => void;
  29. }
  30. /**
  31. * Tracks the state of the virtualized view and manages the resizing of the columns.
  32. * Children components should call the appropriate register*Ref methods to register their
  33. * HTML elements.
  34. */
  35. export type ViewManagerScrollAnchor = 'top' | 'center if outside' | 'center';
  36. export class VirtualizedViewManager {
  37. // Represents the space of the entire trace, for example
  38. // a trace starting at 0 and ending at 1000 would have a space of [0, 1000]
  39. to_origin: number = 0;
  40. trace_space: TraceView = TraceView.Empty();
  41. // The view defines what the user is currently looking at, it is a subset
  42. // of the trace space. For example, if the user is currently looking at the
  43. // trace from 500 to 1000, the view would be represented by [x, width] = [500, 500]
  44. trace_view: TraceView = TraceView.Empty();
  45. // Represents the pixel space of the entire trace - this is the container
  46. // that we render to. For example, if the container is 1000px wide, the
  47. // pixel space would be [0, 1000]
  48. trace_physical_space: TraceView = TraceView.Empty();
  49. container_physical_space: TraceView = TraceView.Empty();
  50. events: EventStore = {
  51. ['divider resize end']: new Set<VirtualizedViewManagerEvents['divider resize end']>(),
  52. ['virtualized list init']: new Set<
  53. VirtualizedViewManagerEvents['virtualized list init']
  54. >(),
  55. };
  56. row_measurer: TraceRowWidthMeasurer<TraceTreeNode<TraceTree.NodeValue>> =
  57. new TraceRowWidthMeasurer();
  58. indicator_label_measurer: TraceRowWidthMeasurer<TraceTree['indicators'][0]> =
  59. new TraceRowWidthMeasurer();
  60. text_measurer: TraceTextMeasurer = new TraceTextMeasurer();
  61. resize_observer: ResizeObserver | null = null;
  62. list: VirtualizedList | null = null;
  63. scrolling_source: 'list' | 'fake scrollbar' | null = null;
  64. start_virtualized_index: number = 0;
  65. // HTML refs that we need to keep track of such
  66. // that rendering can be done programmatically
  67. divider: HTMLElement | null = null;
  68. container: HTMLElement | null = null;
  69. horizontal_scrollbar_container: HTMLElement | null = null;
  70. indicator_container: HTMLElement | null = null;
  71. intervals: (number | undefined)[] = [];
  72. // We want to render an indicator every 100px, but because we dont track resizing
  73. // of the container, we need to precompute the number of intervals we need to render.
  74. // We'll oversize the count by 3x, assuming no user will ever resize the window to 3x the
  75. // original size.
  76. interval_bars = new Array(Math.ceil(window.innerWidth / 100) * 3).fill(0);
  77. indicators: ({indicator: TraceTree['indicators'][0]; ref: HTMLElement} | undefined)[] =
  78. [];
  79. timeline_indicators: (HTMLElement | undefined)[] = [];
  80. span_bars: ({color: string; ref: HTMLElement; space: [number, number]} | undefined)[] =
  81. [];
  82. span_patterns: ({ref: HTMLElement; space: [number, number]} | undefined)[][] = [];
  83. invisible_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  84. span_arrows: (
  85. | {
  86. position: 0 | 1;
  87. ref: HTMLElement;
  88. space: [number, number];
  89. visible: boolean;
  90. }
  91. | undefined
  92. )[] = [];
  93. span_text: ({ref: HTMLElement; space: [number, number]; text: string} | undefined)[] =
  94. [];
  95. // Holds the span to px matrix so we dont keep recalculating it
  96. span_to_px: mat3 = mat3.create();
  97. row_depth_padding: number = 22;
  98. // Smallest of time that can be displayed across the entire view.
  99. private readonly MAX_ZOOM_PRECISION = 1;
  100. private readonly ROW_PADDING_PX = 16;
  101. // Column configuration
  102. columns: Record<'list' | 'span_list', ViewColumn>;
  103. constructor(columns: {
  104. list: Pick<ViewColumn, 'width'>;
  105. span_list: Pick<ViewColumn, 'width'>;
  106. }) {
  107. this.columns = {
  108. list: {...columns.list, column_nodes: [], column_refs: [], translate: [0, 0]},
  109. span_list: {
  110. ...columns.span_list,
  111. column_nodes: [],
  112. column_refs: [],
  113. translate: [0, 0],
  114. },
  115. };
  116. this.registerContainerRef = this.registerContainerRef.bind(this);
  117. this.registerHorizontalScrollBarContainerRef =
  118. this.registerHorizontalScrollBarContainerRef.bind(this);
  119. this.registerDividerRef = this.registerDividerRef.bind(this);
  120. this.registerIndicatorContainerRef = this.registerIndicatorContainerRef.bind(this);
  121. this.onDividerMouseDown = this.onDividerMouseDown.bind(this);
  122. this.onDividerMouseUp = this.onDividerMouseUp.bind(this);
  123. this.onDividerMouseMove = this.onDividerMouseMove.bind(this);
  124. this.onSyncedScrollbarScroll = this.onSyncedScrollbarScroll.bind(this);
  125. this.onWheel = this.onWheel.bind(this);
  126. this.onWheelEnd = this.onWheelEnd.bind(this);
  127. this.onWheelStart = this.onWheelStart.bind(this);
  128. this.onNewMaxRowWidth = this.onNewMaxRowWidth.bind(this);
  129. this.onHorizontalScrollbarScroll = this.onHorizontalScrollbarScroll.bind(this);
  130. }
  131. once<K extends keyof VirtualizedViewManagerEvents>(eventName: K, cb: Function) {
  132. const wrapper = (...args: any[]) => {
  133. cb(...args);
  134. this.off(eventName, wrapper);
  135. };
  136. this.on(eventName, wrapper);
  137. }
  138. on<K extends keyof VirtualizedViewManagerEvents>(
  139. eventName: K,
  140. cb: VirtualizedViewManagerEvents[K]
  141. ): void {
  142. const set = this.events[eventName] as unknown as Set<VirtualizedViewManagerEvents[K]>;
  143. if (set.has(cb)) {
  144. return;
  145. }
  146. set.add(cb);
  147. }
  148. off<K extends keyof VirtualizedViewManagerEvents>(
  149. eventName: K,
  150. cb: VirtualizedViewManagerEvents[K]
  151. ): void {
  152. const set = this.events[eventName] as unknown as Set<VirtualizedViewManagerEvents[K]>;
  153. if (set.has(cb)) {
  154. set.delete(cb);
  155. }
  156. }
  157. dispatch<K extends keyof VirtualizedViewManagerEvents>(
  158. event: K,
  159. ...args: ArgumentTypes<VirtualizedViewManagerEvents[K]>
  160. ): void {
  161. for (const handler of this.events[event]) {
  162. // @ts-expect-error
  163. handler(...args);
  164. }
  165. }
  166. initializeTraceSpace(space: [x: number, y: number, width: number, height: number]) {
  167. this.to_origin = space[0];
  168. this.trace_space = new TraceView(0, 0, space[2], space[3]);
  169. this.trace_view = new TraceView(0, 0, space[2], space[3]);
  170. this.recomputeTimelineIntervals();
  171. this.recomputeSpanToPxMatrix();
  172. }
  173. initializePhysicalSpace(width: number, height: number) {
  174. this.container_physical_space = new TraceView(0, 0, width, height);
  175. this.trace_physical_space = new TraceView(
  176. 0,
  177. 0,
  178. width * this.columns.span_list.width,
  179. height
  180. );
  181. this.recomputeTimelineIntervals();
  182. this.recomputeSpanToPxMatrix();
  183. }
  184. dividerScale: 1 | undefined = undefined;
  185. dividerStartVec: [number, number] | null = null;
  186. previousDividerClientVec: [number, number] | null = null;
  187. onDividerMouseDown(event: MouseEvent) {
  188. if (!this.container) {
  189. return;
  190. }
  191. this.dividerScale = this.trace_view.width === this.trace_space.width ? 1 : undefined;
  192. this.dividerStartVec = [event.clientX, event.clientY];
  193. this.previousDividerClientVec = [event.clientX, event.clientY];
  194. document.body.style.cursor = 'ew-resize !important';
  195. document.body.style.userSelect = 'none';
  196. document.addEventListener('mouseup', this.onDividerMouseUp, {passive: true});
  197. document.addEventListener('mousemove', this.onDividerMouseMove, {
  198. passive: true,
  199. });
  200. }
  201. onDividerMouseUp(event: MouseEvent) {
  202. if (!this.container || !this.dividerStartVec) {
  203. return;
  204. }
  205. this.dividerScale = undefined;
  206. const distance = event.clientX - this.dividerStartVec[0];
  207. const distancePercentage = distance / this.container_physical_space.width;
  208. this.columns.list.width = this.columns.list.width + distancePercentage;
  209. this.columns.span_list.width = this.columns.span_list.width - distancePercentage;
  210. document.body.style.cursor = '';
  211. document.body.style.userSelect = '';
  212. this.dividerStartVec = null;
  213. this.previousDividerClientVec = null;
  214. this.enqueueOnScrollEndOutOfBoundsCheck();
  215. document.removeEventListener('mouseup', this.onDividerMouseUp);
  216. document.removeEventListener('mousemove', this.onDividerMouseMove);
  217. this.dispatch('divider resize end', this.columns.list.width);
  218. }
  219. onDividerMouseMove(event: MouseEvent) {
  220. if (!this.dividerStartVec || !this.divider || !this.previousDividerClientVec) {
  221. return;
  222. }
  223. const distance = event.clientX - this.dividerStartVec[0];
  224. const distancePercentage = distance / this.container_physical_space.width;
  225. this.trace_physical_space.width =
  226. (this.columns.span_list.width - distancePercentage) *
  227. this.container_physical_space.width;
  228. const physical_distance = this.previousDividerClientVec[0] - event.clientX;
  229. const config_distance_pct = physical_distance / this.trace_physical_space.width;
  230. const config_distance = this.trace_view.width * config_distance_pct;
  231. if (this.dividerScale) {
  232. // just recompute the draw matrix and let the view scale itself
  233. this.recomputeSpanToPxMatrix();
  234. } else {
  235. this.setTraceView({
  236. x: this.trace_view.x - config_distance,
  237. width: this.trace_view.width + config_distance,
  238. });
  239. }
  240. this.recomputeTimelineIntervals();
  241. this.draw({
  242. list: this.columns.list.width + distancePercentage,
  243. span_list: this.columns.span_list.width - distancePercentage,
  244. });
  245. this.previousDividerClientVec = [event.clientX, event.clientY];
  246. }
  247. private scrollbar_width: number = 0;
  248. onScrollbarWidthChange(width: number) {
  249. if (width === this.scrollbar_width) {
  250. return;
  251. }
  252. this.scrollbar_width = width;
  253. this.draw();
  254. }
  255. registerContainerRef(container: HTMLElement | null) {
  256. if (container) {
  257. this.initialize(container);
  258. } else {
  259. this.teardown();
  260. }
  261. }
  262. registerGhostRowRef(column: string, ref: HTMLElement | null) {
  263. if (column === 'list' && ref) {
  264. const scrollableElement = ref.children[0] as HTMLElement | undefined;
  265. if (scrollableElement) {
  266. ref.addEventListener('wheel', this.onSyncedScrollbarScroll, {passive: false});
  267. }
  268. }
  269. if (column === 'span_list' && ref) {
  270. ref.addEventListener('wheel', this.onWheel, {passive: false});
  271. }
  272. }
  273. registerList(list: VirtualizedList | null) {
  274. this.list = list;
  275. }
  276. registerIndicatorContainerRef(ref: HTMLElement | null) {
  277. if (ref) {
  278. const correction =
  279. (this.scrollbar_width / this.container_physical_space.width) *
  280. this.columns.span_list.width;
  281. ref.style.transform = `translateX(${-this.scrollbar_width}px)`;
  282. ref.style.width = (this.columns.span_list.width - correction) * 100 + '%';
  283. }
  284. this.indicator_container = ref;
  285. }
  286. registerDividerRef(ref: HTMLElement | null) {
  287. if (!ref) {
  288. if (this.divider) {
  289. this.divider.removeEventListener('mousedown', this.onDividerMouseDown);
  290. }
  291. this.divider = null;
  292. return;
  293. }
  294. this.divider = ref;
  295. this.divider.style.width = `${DIVIDER_WIDTH}px`;
  296. ref.addEventListener('mousedown', this.onDividerMouseDown, {passive: true});
  297. }
  298. registerSpanBarRef(
  299. ref: HTMLElement | null,
  300. space: [number, number],
  301. color: string,
  302. index: number
  303. ) {
  304. if (ref) {
  305. this.span_bars[index] = {ref, space, color};
  306. }
  307. if (ref) {
  308. this.drawSpanBar(this.span_bars[index]!);
  309. this.span_bars[index]!.ref.style.backgroundColor = color;
  310. }
  311. }
  312. registerArrowRef(ref: HTMLElement | null, space: [number, number], index: number) {
  313. if (ref) {
  314. this.span_arrows[index] = {ref, space, visible: false, position: 0};
  315. }
  316. }
  317. registerSpanBarTextRef(
  318. ref: HTMLElement | null,
  319. text: string,
  320. space: [number, number],
  321. index: number
  322. ) {
  323. if (ref) {
  324. this.span_text[index] = {ref, text, space};
  325. this.drawSpanText(this.span_text[index]!, this.columns.list.column_nodes[index]);
  326. }
  327. }
  328. registerInvisibleBarRef(
  329. ref: HTMLElement | null,
  330. space: [number, number],
  331. index: number
  332. ) {
  333. if (ref) {
  334. this.invisible_bars[index] = ref ? {ref, space} : undefined;
  335. const span_transform = this.computeSpanCSSMatrixTransform(space);
  336. ref.style.transform = `matrix(${span_transform.join(',')}`;
  337. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  338. ref.style.setProperty(
  339. '--inverse-span-scale',
  340. // @ts-expect-error this is a number
  341. isNaN(inverseScale) ? 1 : inverseScale
  342. );
  343. }
  344. }
  345. registerColumnRef(
  346. column: string,
  347. ref: HTMLElement | null,
  348. index: number,
  349. node: TraceTreeNode<any>
  350. ) {
  351. if (column === 'list' && ref) {
  352. const scrollableElement = ref.children[0] as HTMLElement | undefined;
  353. if (scrollableElement) {
  354. scrollableElement.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  355. this.row_measurer.enqueueMeasure(node, scrollableElement as HTMLElement);
  356. ref.addEventListener('wheel', this.onSyncedScrollbarScroll, {passive: false});
  357. }
  358. }
  359. if (column === 'span_list' && ref) {
  360. ref.addEventListener('wheel', this.onWheel, {passive: false});
  361. }
  362. if (ref && node) {
  363. this.columns[column].column_refs[index] = ref;
  364. this.columns[column].column_nodes[index] = node;
  365. }
  366. }
  367. registerIndicatorRef(
  368. ref: HTMLElement | null,
  369. index: number,
  370. indicator: TraceTree['indicators'][0]
  371. ) {
  372. if (!ref) {
  373. const element = this.indicators[index]?.ref;
  374. if (element) {
  375. element.removeEventListener('wheel', this.onWheel);
  376. }
  377. } else {
  378. this.indicators[index] = {ref, indicator};
  379. }
  380. if (ref) {
  381. const label = ref.children[0] as HTMLElement | undefined;
  382. if (label) {
  383. this.indicator_label_measurer.enqueueMeasure(indicator, label);
  384. }
  385. ref.addEventListener('wheel', this.onWheel, {passive: false});
  386. ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(
  387. indicator.start
  388. )}px)`;
  389. }
  390. }
  391. registerTimelineIndicatorRef(ref: HTMLElement | null, index: number) {
  392. if (ref) {
  393. this.timeline_indicators[index] = ref;
  394. this.drawTimelineInterval(ref, index);
  395. }
  396. }
  397. getConfigSpaceCursor(cursor: {x: number; y: number}): [number, number] {
  398. const left_percentage = cursor.x / this.trace_physical_space.width;
  399. const left_view = left_percentage * this.trace_view.width;
  400. return [this.trace_view.x + left_view, 0];
  401. }
  402. onWheel(event: WheelEvent) {
  403. if (event.metaKey || event.ctrlKey) {
  404. event.preventDefault();
  405. if (!this.onWheelEndRaf) {
  406. this.onWheelStart();
  407. }
  408. this.enqueueOnWheelEndRaf();
  409. const scale = 1 - event.deltaY * 0.01 * -1;
  410. const configSpaceCursor = this.getConfigSpaceCursor({
  411. x: event.offsetX,
  412. y: event.offsetY,
  413. });
  414. const center = vec2.fromValues(configSpaceCursor[0], 0);
  415. const centerScaleMatrix = mat3.create();
  416. mat3.fromTranslation(centerScaleMatrix, center);
  417. mat3.scale(centerScaleMatrix, centerScaleMatrix, vec2.fromValues(scale, 1));
  418. mat3.translate(
  419. centerScaleMatrix,
  420. centerScaleMatrix,
  421. vec2.fromValues(-center[0], 0)
  422. );
  423. const newView = this.trace_view.transform(centerScaleMatrix);
  424. this.setTraceView({
  425. x: newView[0],
  426. width: newView[2],
  427. });
  428. this.draw();
  429. } else {
  430. if (!this.onWheelEndRaf) {
  431. this.onWheelStart();
  432. }
  433. this.enqueueOnWheelEndRaf();
  434. // Holding shift key allows for horizontal scrolling
  435. const distance = event.shiftKey ? event.deltaY : event.deltaX;
  436. if (
  437. event.shiftKey ||
  438. (!event.shiftKey && Math.abs(event.deltaX) > Math.abs(event.deltaY))
  439. ) {
  440. event.preventDefault();
  441. }
  442. const physical_delta_pct = distance / this.trace_physical_space.width;
  443. const view_delta = physical_delta_pct * this.trace_view.width;
  444. this.setTraceView({
  445. x: this.trace_view.x + view_delta,
  446. });
  447. this.draw();
  448. }
  449. }
  450. onBringRowIntoView(space: [number, number]) {
  451. if (this.zoomIntoSpaceRaf !== null) {
  452. window.cancelAnimationFrame(this.zoomIntoSpaceRaf);
  453. this.zoomIntoSpaceRaf = null;
  454. }
  455. if (space[0] - this.to_origin > this.trace_view.x) {
  456. this.onZoomIntoSpace([
  457. space[0] + space[1] / 2 - this.trace_view.width / 2,
  458. this.trace_view.width,
  459. ]);
  460. } else if (space[0] - this.to_origin < this.trace_view.x) {
  461. this.onZoomIntoSpace([
  462. space[0] + space[1] / 2 - this.trace_view.width / 2,
  463. this.trace_view.width,
  464. ]);
  465. }
  466. }
  467. animateViewTo(node_space: [number, number]) {
  468. const start = node_space[0];
  469. const width = node_space[1] > 0 ? node_space[1] : this.trace_view.width;
  470. const margin = 0.2 * width;
  471. this.setTraceView({x: start - margin - this.to_origin, width: width + margin * 2});
  472. this.draw();
  473. }
  474. zoomIntoSpaceRaf: number | null = null;
  475. onZoomIntoSpace(space: [number, number]) {
  476. let distance_x = space[0] - this.to_origin - this.trace_view.x;
  477. let final_x = space[0] - this.to_origin;
  478. let final_width = space[1];
  479. const distance_width = this.trace_view.width - space[1];
  480. if (space[1] < this.MAX_ZOOM_PRECISION) {
  481. distance_x -= this.MAX_ZOOM_PRECISION / 2 - space[1] / 2;
  482. final_x -= this.MAX_ZOOM_PRECISION / 2 - space[1] / 2;
  483. final_width = this.MAX_ZOOM_PRECISION;
  484. }
  485. const start_x = this.trace_view.x;
  486. const start_width = this.trace_view.width;
  487. const max_distance = Math.max(Math.abs(distance_x), Math.abs(distance_width));
  488. const p = max_distance !== 0 ? Math.log10(max_distance) : 1;
  489. // We need to clamp the duration to prevent the animation from being too slow,
  490. // sometimes the distances are very large as traces can be hours in duration
  491. const duration = clamp(200 + 70 * Math.abs(p), 200, 600);
  492. const start = performance.now();
  493. const rafCallback = (now: number) => {
  494. const elapsed = now - start;
  495. const progress = elapsed / duration;
  496. const eased = easeOutSine(progress);
  497. const x = start_x + distance_x * eased;
  498. const width = start_width - distance_width * eased;
  499. this.setTraceView({x, width});
  500. this.draw();
  501. if (progress < 1) {
  502. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  503. } else {
  504. this.zoomIntoSpaceRaf = null;
  505. this.setTraceView({x: final_x, width: final_width});
  506. this.draw();
  507. }
  508. };
  509. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  510. }
  511. resetZoom() {
  512. this.onZoomIntoSpace([this.to_origin, this.trace_space.width]);
  513. }
  514. onWheelEndRaf: number | null = null;
  515. enqueueOnWheelEndRaf() {
  516. if (this.onWheelEndRaf !== null) {
  517. window.cancelAnimationFrame(this.onWheelEndRaf);
  518. }
  519. const start = performance.now();
  520. const rafCallback = (now: number) => {
  521. const elapsed = now - start;
  522. if (elapsed > 200) {
  523. this.onWheelEnd();
  524. } else {
  525. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  526. }
  527. };
  528. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  529. }
  530. onWheelStart() {
  531. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  532. const span_list = this.columns.span_list.column_refs[i];
  533. if (span_list?.children?.[0]) {
  534. (span_list.children[0] as HTMLElement).style.pointerEvents = 'none';
  535. }
  536. const span_text = this.span_text[i];
  537. if (span_text) {
  538. span_text.ref.style.pointerEvents = 'none';
  539. }
  540. }
  541. for (let i = 0; i < this.indicators.length; i++) {
  542. const indicator = this.indicators[i];
  543. if (indicator?.ref) {
  544. indicator.ref.style.pointerEvents = 'none';
  545. }
  546. }
  547. }
  548. onWheelEnd() {
  549. this.onWheelEndRaf = null;
  550. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  551. const span_list = this.columns.span_list.column_refs[i];
  552. if (span_list?.children?.[0]) {
  553. (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto';
  554. }
  555. const span_text = this.span_text[i];
  556. if (span_text) {
  557. span_text.ref.style.pointerEvents = 'auto';
  558. }
  559. }
  560. for (let i = 0; i < this.indicators.length; i++) {
  561. const indicator = this.indicators[i];
  562. if (indicator?.ref) {
  563. indicator.ref.style.pointerEvents = 'auto';
  564. }
  565. }
  566. }
  567. setTraceView(view: {width?: number; x?: number}) {
  568. // In cases where a trace might have a single error, there is no concept of a timeline
  569. if (this.trace_view.width === 0) {
  570. return;
  571. }
  572. const x = view.x ?? this.trace_view.x;
  573. const width = view.width ?? this.trace_view.width;
  574. this.trace_view.x = clamp(x, 0, this.trace_space.width - width);
  575. this.trace_view.width = clamp(
  576. width,
  577. this.MAX_ZOOM_PRECISION,
  578. this.trace_space.width - this.trace_view.x
  579. );
  580. this.recomputeTimelineIntervals();
  581. this.recomputeSpanToPxMatrix();
  582. }
  583. registerHorizontalScrollBarContainerRef(ref: HTMLElement | null) {
  584. if (ref) {
  585. ref.style.width = Math.round(this.columns.list.width * 100) + '%';
  586. ref.addEventListener('scroll', this.onHorizontalScrollbarScroll, {passive: false});
  587. } else {
  588. if (this.horizontal_scrollbar_container) {
  589. this.horizontal_scrollbar_container.removeEventListener(
  590. 'scroll',
  591. this.onHorizontalScrollbarScroll
  592. );
  593. }
  594. }
  595. this.horizontal_scrollbar_container = ref;
  596. }
  597. onNewMaxRowWidth(max) {
  598. this.syncHorizontalScrollbar(max);
  599. }
  600. syncHorizontalScrollbar(max: number) {
  601. const child = this.horizontal_scrollbar_container?.children[0] as
  602. | HTMLElement
  603. | undefined;
  604. if (child) {
  605. child.style.width =
  606. Math.round(max - this.scrollbar_width + this.ROW_PADDING_PX) + 'px';
  607. }
  608. }
  609. onHorizontalScrollbarScroll(_event: Event) {
  610. if (!this.scrolling_source) {
  611. this.scrolling_source = 'fake scrollbar';
  612. }
  613. if (this.scrolling_source !== 'fake scrollbar') {
  614. return;
  615. }
  616. const scrollLeft = this.horizontal_scrollbar_container?.scrollLeft;
  617. if (typeof scrollLeft !== 'number') {
  618. return;
  619. }
  620. this.enqueueOnScrollEndOutOfBoundsCheck();
  621. this.columns.list.translate[0] = this.clampRowTransform(-scrollLeft);
  622. const rows = Array.from(
  623. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  624. ) as HTMLElement[];
  625. for (const row of rows) {
  626. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  627. }
  628. }
  629. syncedRaf: number | null = null;
  630. onSyncedScrollbarScroll(event: WheelEvent) {
  631. if (!this.scrolling_source) {
  632. this.scrolling_source = 'list';
  633. }
  634. if (this.scrolling_source !== 'list') {
  635. return;
  636. }
  637. // Holding shift key allows for horizontal scrolling
  638. const distance = event.shiftKey ? event.deltaY : event.deltaX;
  639. if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
  640. // Prevents firing back/forward navigation
  641. event.preventDefault();
  642. } else {
  643. return;
  644. }
  645. if (this.bringRowIntoViewAnimation !== null) {
  646. window.cancelAnimationFrame(this.bringRowIntoViewAnimation);
  647. this.bringRowIntoViewAnimation = null;
  648. }
  649. this.enqueueOnScrollEndOutOfBoundsCheck();
  650. const newTransform = this.clampRowTransform(
  651. this.columns.list.translate[0] - distance
  652. );
  653. if (newTransform === this.columns.list.translate[0]) {
  654. return;
  655. }
  656. this.columns.list.translate[0] = newTransform;
  657. const rows = Array.from(
  658. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  659. ) as HTMLElement[];
  660. for (const row of rows) {
  661. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  662. }
  663. if (this.horizontal_scrollbar_container) {
  664. this.horizontal_scrollbar_container.scrollLeft = -Math.round(
  665. this.columns.list.translate[0]
  666. );
  667. }
  668. }
  669. clampRowTransform(transform: number): number {
  670. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  671. const max = this.row_measurer.max - columnWidth + this.ROW_PADDING_PX;
  672. if (this.row_measurer.queue.length > 0) {
  673. this.row_measurer.drain();
  674. }
  675. if (this.row_measurer.max < columnWidth) {
  676. return 0;
  677. }
  678. // Sometimes the wheel event glitches or jumps to a very high value
  679. if (transform > 0) {
  680. return 0;
  681. }
  682. if (transform < -max) {
  683. return -max;
  684. }
  685. return transform;
  686. }
  687. scrollEndSyncRaf: {id: number} | null = null;
  688. enqueueOnScrollEndOutOfBoundsCheck() {
  689. if (this.bringRowIntoViewAnimation !== null) {
  690. // Dont enqueue updates while view is scrolling
  691. return;
  692. }
  693. window.cancelAnimationFrame(this.scrollEndSyncRaf?.id ?? 0);
  694. this.scrollEndSyncRaf = requestAnimationTimeout(() => {
  695. this.onScrollEndOutOfBoundsCheck();
  696. }, 300);
  697. }
  698. onScrollEndOutOfBoundsCheck() {
  699. this.scrollEndSyncRaf = null;
  700. this.scrolling_source = null;
  701. const translation = this.columns.list.translate[0];
  702. let min = Number.POSITIVE_INFINITY;
  703. let max = Number.NEGATIVE_INFINITY;
  704. let innerMostNode: TraceTreeNode<any> | undefined;
  705. for (let i = 5; i < this.columns.span_list.column_refs.length - 5; i++) {
  706. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  707. if (width === undefined) {
  708. // this is unlikely to happen, but we should trigger a sync measure event if it does
  709. continue;
  710. }
  711. min = Math.min(min, width);
  712. max = Math.max(max, width);
  713. innerMostNode =
  714. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  715. ? this.columns.list.column_nodes[i]
  716. : innerMostNode;
  717. }
  718. if (innerMostNode) {
  719. if (translation + max < 0) {
  720. this.scrollRowIntoViewHorizontally(innerMostNode);
  721. } else if (
  722. translation + innerMostNode.depth * this.row_depth_padding >
  723. this.columns.list.width * this.container_physical_space.width
  724. ) {
  725. this.scrollRowIntoViewHorizontally(innerMostNode);
  726. }
  727. }
  728. }
  729. isOutsideOfViewOnKeyDown(node: TraceTreeNode<any>): boolean {
  730. const width = this.row_measurer.cache.get(node);
  731. if (width === undefined) {
  732. // this is unlikely to happen, but we should trigger a sync measure event if it does
  733. return false;
  734. }
  735. const translation = this.columns.list.translate[0];
  736. return (
  737. translation + node.depth * this.row_depth_padding < 0 ||
  738. translation + node.depth * this.row_depth_padding >
  739. (this.columns.list.width * this.container_physical_space.width) / 2
  740. );
  741. }
  742. scrollRowIntoViewHorizontally(
  743. node: TraceTreeNode<any>,
  744. duration: number = 600,
  745. offset_px: number = 0,
  746. position: 'exact' | 'measured' = 'measured'
  747. ) {
  748. const depth_px = -node.depth * this.row_depth_padding + offset_px;
  749. const newTransform =
  750. position === 'exact' ? depth_px : this.clampRowTransform(depth_px);
  751. this.animateScrollColumnTo(newTransform, duration);
  752. }
  753. bringRowIntoViewAnimation: number | null = null;
  754. animateScrollColumnTo(x: number, duration: number) {
  755. const start = performance.now();
  756. const startPosition = this.columns.list.translate[0];
  757. const distance = x - startPosition;
  758. if (duration === 0) {
  759. const rows = Array.from(
  760. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  761. ) as HTMLElement[];
  762. for (const row of rows) {
  763. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  764. }
  765. this.columns.list.translate[0] = x;
  766. if (this.horizontal_scrollbar_container) {
  767. this.horizontal_scrollbar_container.scrollLeft = -x;
  768. }
  769. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  770. return;
  771. }
  772. const animate = (now: number) => {
  773. const elapsed = now - start;
  774. const progress = duration > 0 ? elapsed / duration : 1;
  775. const eased = easeOutSine(progress);
  776. const pos = startPosition + distance * eased;
  777. const rows = Array.from(
  778. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  779. ) as HTMLElement[];
  780. for (const row of rows) {
  781. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  782. }
  783. if (progress < 1) {
  784. this.columns.list.translate[0] = pos;
  785. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  786. } else {
  787. this.bringRowIntoViewAnimation = null;
  788. if (this.horizontal_scrollbar_container) {
  789. this.horizontal_scrollbar_container.scrollLeft = -x;
  790. }
  791. this.columns.list.translate[0] = x;
  792. }
  793. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  794. };
  795. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  796. }
  797. initialize(container: HTMLElement) {
  798. if (this.container !== container && this.resize_observer !== null) {
  799. this.teardown();
  800. return;
  801. }
  802. this.container = container;
  803. this.drawContainers(this.container, {
  804. list_width: this.columns.list.width,
  805. span_list_width: this.columns.span_list.width,
  806. });
  807. this.row_measurer.on('max', this.onNewMaxRowWidth);
  808. this.resize_observer = new ResizeObserver(entries => {
  809. const entry = entries[0];
  810. if (!entry) {
  811. throw new Error('ResizeObserver entry is undefined');
  812. }
  813. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  814. this.draw();
  815. });
  816. this.resize_observer.observe(container);
  817. }
  818. recomputeSpanToPxMatrix() {
  819. const traceViewToSpace = this.trace_space.between(this.trace_view);
  820. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  821. this.span_to_px = mat3.multiply(
  822. this.span_to_px,
  823. traceViewToSpace,
  824. tracePhysicalToView
  825. );
  826. }
  827. computeRelativeLeftPositionFromOrigin(
  828. timestamp: number,
  829. entire_space: [number, number]
  830. ) {
  831. return (timestamp - entire_space[0]) / entire_space[1];
  832. }
  833. recomputeTimelineIntervals() {
  834. if (this.trace_view.width === 0) {
  835. this.intervals[0] = 0;
  836. this.intervals[1] = 0;
  837. for (let i = 2; i < this.intervals.length; i++) {
  838. this.intervals[i] = undefined;
  839. }
  840. return;
  841. }
  842. const tracePhysicalToView = this.trace_physical_space.between(this.trace_view);
  843. const time_at_100 =
  844. tracePhysicalToView[0] * (100 * window.devicePixelRatio) +
  845. tracePhysicalToView[6] -
  846. this.trace_view.x;
  847. computeTimelineIntervals(this.trace_view, time_at_100, this.intervals);
  848. }
  849. readonly span_matrix: [number, number, number, number, number, number] = [
  850. 1, 0, 0, 1, 0, 0,
  851. ];
  852. computeSpanCSSMatrixTransform(
  853. space: [number, number]
  854. ): [number, number, number, number, number, number] {
  855. const scale = space[1] / this.trace_view.width;
  856. this.span_matrix[0] = Math.max(scale, this.span_to_px[0] / this.trace_view.width);
  857. this.span_matrix[4] =
  858. (space[0] - this.to_origin) / this.span_to_px[0] -
  859. this.trace_view.x / this.span_to_px[0];
  860. return this.span_matrix;
  861. }
  862. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  863. if (!this.list) {
  864. return;
  865. }
  866. this.list.scrollToRow(index, anchor);
  867. }
  868. computeTransformXFromTimestamp(timestamp: number): number {
  869. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  870. }
  871. computeSpanTextPlacement(
  872. node: TraceTreeNode<TraceTree.NodeValue>,
  873. span_space: [number, number],
  874. text: string
  875. ): [number, number] {
  876. const text_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  877. const width = this.text_measurer.measure(text);
  878. const has_profiles = node && node.profiles.length > 0;
  879. const has_error_icons =
  880. node &&
  881. (node.profiles.length > 0 ||
  882. node.errors.size > 0 ||
  883. node.performance_issues.size > 0);
  884. const has_icons = has_profiles || has_error_icons;
  885. const node_width = span_space[1] / this.span_to_px[0];
  886. const TEXT_PADDING = 2;
  887. // This is inaccurate in the case of left anchored text. In order to determine a true overlap, we would need to compute
  888. // the distance between the min timestamp of an icon and beginning of the span. Once we determine the distance, we can compute
  889. // the width and see if there is an actual overlap. Since this is a rare case which only happens in the case where we anchor the text
  890. // to the left (20% of the time) and the node may have many errors, this could be computationally expensive to do on every frame.
  891. // We'll live with the inaccuracy for now as it is purely visual and just make sure to handle a single error case as it will be easy
  892. // to determine if there is an overlap.
  893. const TEXT_PADDING_LEFT = text_left && has_icons ? 10 : TEXT_PADDING;
  894. const TEXT_PADDING_RIGHT =
  895. !text_left && has_icons
  896. ? node_width < 10
  897. ? // If the node is too small, we need to make sure the text is anchored to the right edge of the icon.
  898. // We take the distance from the right edge of the node to the right edge of the icon and subtract it from
  899. // the base width (10) and the base padding when (expanded) to get the correct padding. If we take only 10px
  900. // as our padding, the text can be anchored directly to the right edge of our icon - we want to preserve
  901. // a min padding of 2px.
  902. 12 - node_width
  903. : TEXT_PADDING
  904. : TEXT_PADDING;
  905. // precompute all anchor points aot, so we make the control flow more readable.
  906. // this wastes some cycles, but it's not a big deal as computers go brrrr when it comes to simple arithmetic.
  907. /// |---| text
  908. const right_outside =
  909. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) +
  910. TEXT_PADDING_RIGHT;
  911. /// text |---|
  912. const left_outside =
  913. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING_LEFT - width;
  914. // | text|
  915. const right_inside =
  916. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  917. width -
  918. TEXT_PADDING;
  919. // |text |
  920. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  921. // Right edge of the window (when span extends beyond the view)
  922. const window_right =
  923. this.computeTransformXFromTimestamp(
  924. this.to_origin + this.trace_view.left + this.trace_view.width
  925. ) -
  926. width -
  927. TEXT_PADDING;
  928. const window_left =
  929. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  930. TEXT_PADDING;
  931. const view_left = this.trace_view.x;
  932. const view_right = view_left + this.trace_view.width;
  933. const span_left = span_space[0] - this.to_origin;
  934. const span_right = span_left + span_space[1];
  935. const space_right = view_right - span_right;
  936. const space_left = span_left - view_left;
  937. // Span is completely outside of the view on the left side
  938. if (span_right < this.trace_view.x) {
  939. return text_left ? [1, right_inside] : [0, right_outside];
  940. }
  941. // Span is completely outside of the view on the right side
  942. if (span_left > this.trace_view.right) {
  943. return text_left ? [0, left_outside] : [1, left_inside];
  944. }
  945. // Span "spans" the entire view
  946. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  947. return text_left ? [1, window_left] : [1, window_right];
  948. }
  949. const full_span_px_width = span_space[1] / this.span_to_px[0];
  950. if (text_left) {
  951. // While we have space on the left, place the text there
  952. if (space_left > 0) {
  953. return [0, left_outside];
  954. }
  955. const distance = span_right - this.trace_view.left;
  956. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  957. // If the text fits inside the visible portion of the span, anchor it to the left
  958. // side of the window so that it is visible while the user pans the view
  959. if (visible_width - TEXT_PADDING >= width) {
  960. return [1, window_left];
  961. }
  962. // If the text doesnt fit inside the visible portion of the span,
  963. // anchor it to the inside right place in the span.
  964. return [1, right_inside];
  965. }
  966. // While we have space on the right, place the text there
  967. if (space_right > 0) {
  968. if (
  969. // If the right edge of the span is within 10% to the right edge of the space,
  970. // try and fit the text inside the span if possible. In case the span is too short
  971. // to fit the text, text_left case above will take care of anchoring it to the left
  972. // of the view.
  973. // Note: the accurate way for us to determine if the text fits to the right side
  974. // of the view would have been to compute the scaling matrix for a non zoomed view at 0,0
  975. // origin and check if it fits into the distance of space right edge - span right edge. In practice
  976. // however, it seems that a magical number works just fine.
  977. span_right > this.trace_space.right * 0.9 &&
  978. space_right / this.span_to_px[0] < width
  979. ) {
  980. return [1, right_inside];
  981. }
  982. return [0, right_outside];
  983. }
  984. // If text fits inside the span
  985. if (full_span_px_width > width) {
  986. const distance = span_right - this.trace_view.right;
  987. const visible_width =
  988. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  989. // If the text fits inside the visible portion of the span, anchor it to the right
  990. // side of the window so that it is visible while the user pans the view
  991. if (visible_width - TEXT_PADDING >= width) {
  992. return [1, window_right];
  993. }
  994. // If the text doesnt fit inside the visible portion of the span,
  995. // anchor it to the inside left of the span
  996. return [1, left_inside];
  997. }
  998. return [0, right_outside];
  999. }
  1000. last_indicator_width = 0;
  1001. draw(options: {list?: number; span_list?: number} = {}) {
  1002. const list_width = options.list ?? this.columns.list.width;
  1003. const span_list_width = options.span_list ?? this.columns.span_list.width;
  1004. this.drawContainers(this.container, {
  1005. list_width,
  1006. span_list_width,
  1007. });
  1008. // 60px error margin. ~52px is roughly the width of 500.00ms, we add a bit more, to be safe.
  1009. const error_margin = 60 * this.span_to_px[0];
  1010. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  1011. const span = this.span_bars[i];
  1012. if (!span) {
  1013. continue;
  1014. }
  1015. const outside_left =
  1016. span.space[0] - this.to_origin + span.space[1] < this.trace_view.x - error_margin;
  1017. const outside_right = span.space[0] - this.to_origin > this.trace_view.right;
  1018. if (outside_left || outside_right) {
  1019. this.hideSpanBar(this.span_bars[i], this.span_text[i]);
  1020. this.drawSpanArrow(this.span_arrows[i], true, outside_left ? 0 : 1);
  1021. continue;
  1022. }
  1023. this.drawSpanBar(this.span_bars[i]);
  1024. this.drawSpanText(this.span_text[i], this.columns.list.column_nodes[i]);
  1025. this.drawSpanArrow(this.span_arrows[i], false, 0);
  1026. }
  1027. this.drawInvisibleBars();
  1028. let start_indicator = 0;
  1029. let end_indicator = this.indicators.length;
  1030. while (start_indicator < this.indicators.length - 1) {
  1031. const indicator = this.indicators[start_indicator];
  1032. if (!indicator?.indicator) {
  1033. start_indicator++;
  1034. continue;
  1035. }
  1036. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1037. start_indicator++;
  1038. continue;
  1039. }
  1040. break;
  1041. }
  1042. while (end_indicator > start_indicator) {
  1043. const last_indicator = this.indicators[end_indicator - 1];
  1044. if (!last_indicator) {
  1045. end_indicator--;
  1046. continue;
  1047. }
  1048. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1049. end_indicator--;
  1050. continue;
  1051. }
  1052. break;
  1053. }
  1054. start_indicator = Math.max(0, start_indicator - 1);
  1055. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1056. for (let i = 0; i < this.indicators.length; i++) {
  1057. const entry = this.indicators[i];
  1058. if (!entry) {
  1059. continue;
  1060. }
  1061. if (i < start_indicator || i > end_indicator) {
  1062. entry.ref.style.opacity = '0';
  1063. continue;
  1064. }
  1065. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1066. const label = entry.ref.children[0] as HTMLElement | undefined;
  1067. const indicator_max = this.trace_physical_space.width + 1;
  1068. const indicator_min = -1;
  1069. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1070. const clamped_transform = clamp(transform, -1, indicator_max);
  1071. if (label_width === undefined) {
  1072. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1073. continue;
  1074. }
  1075. if (label) {
  1076. const PADDING = 2;
  1077. const label_window_left = PADDING;
  1078. const label_window_right = -label_width - PADDING;
  1079. if (transform < -1) {
  1080. label.style.transform = `translateX(${label_window_left}px)`;
  1081. } else if (transform >= indicator_max) {
  1082. label.style.transform = `translateX(${label_window_right}px)`;
  1083. } else {
  1084. const space_left = transform - PADDING - label_width / 2;
  1085. const space_right = transform + label_width / 2;
  1086. if (space_left < 0) {
  1087. const left = -label_width / 2 + Math.abs(space_left);
  1088. label.style.transform = `translateX(${left - 1}px)`;
  1089. } else if (space_right > this.trace_physical_space.width) {
  1090. const right =
  1091. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1092. label.style.transform = `translateX(${right}px)`;
  1093. } else {
  1094. label.style.transform = `translateX(${-label_width / 2}px)`;
  1095. }
  1096. }
  1097. }
  1098. entry.ref.style.opacity = '1';
  1099. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1100. }
  1101. this.drawTimelineIntervals();
  1102. }
  1103. // DRAW METHODS
  1104. hideSpanBar(span_bar: this['span_bars'][0], span_text: this['span_text'][0]) {
  1105. span_bar && (span_bar.ref.style.transform = 'translate(-10000px, -10000px)');
  1106. span_text && (span_text.ref.style.transform = 'translate(-10000px, -10000px)');
  1107. }
  1108. hideSpanArrow(span_arrow: this['span_arrows'][0]) {
  1109. if (!span_arrow) return;
  1110. span_arrow.ref.className = 'TraceArrow';
  1111. span_arrow.visible = false;
  1112. span_arrow.ref.style.opacity = '0';
  1113. }
  1114. drawSpanBar(span_bar: this['span_bars'][0]) {
  1115. if (!span_bar) return;
  1116. const span_transform = this.computeSpanCSSMatrixTransform(span_bar?.space);
  1117. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1118. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1119. span_bar.ref.style.setProperty(
  1120. '--inverse-span-scale',
  1121. // @ts-expect-error we set number value type on purpose
  1122. isNaN(inverseScale) ? 1 : inverseScale
  1123. );
  1124. }
  1125. drawSpanText(span_text: this['span_text'][0], node: TraceTreeNode<any> | undefined) {
  1126. if (!span_text) return;
  1127. const [inside, text_transform] = this.computeSpanTextPlacement(
  1128. node!,
  1129. span_text.space,
  1130. span_text.text
  1131. );
  1132. if (text_transform === null) {
  1133. return;
  1134. }
  1135. span_text.ref.style.color = inside ? 'white' : '';
  1136. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1137. }
  1138. drawSpanArrow(span_arrow: this['span_arrows'][0], visible: boolean, position: 0 | 1) {
  1139. if (!span_arrow) return;
  1140. if (visible !== span_arrow.visible) {
  1141. span_arrow.visible = visible;
  1142. span_arrow.position = position;
  1143. if (visible) {
  1144. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1145. } else {
  1146. span_arrow.ref.className = 'TraceArrow';
  1147. }
  1148. }
  1149. }
  1150. drawTimelineInterval(ref: HTMLElement | undefined, index: number) {
  1151. if (!ref) {
  1152. return;
  1153. }
  1154. const interval = this.intervals[index];
  1155. if (interval === undefined) {
  1156. ref.style.opacity = '0';
  1157. return;
  1158. }
  1159. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1160. ref.style.opacity = '1';
  1161. ref.style.transform = `translateX(${placement}px)`;
  1162. const label = ref.children[0] as HTMLElement | undefined;
  1163. const duration = getDuration(interval / 1000, 2, true);
  1164. if (label && label?.textContent !== duration) {
  1165. label.textContent = duration;
  1166. }
  1167. }
  1168. drawTimelineIntervals() {
  1169. if (this.intervals[0] === 0 && this.intervals[1] === 0) {
  1170. this.drawEmptyTimelineIntervals();
  1171. for (let i = 2; i < this.timeline_indicators.length; i++) {
  1172. const indicator = this.timeline_indicators[i];
  1173. if (indicator) {
  1174. indicator.style.opacity = '0';
  1175. }
  1176. }
  1177. return;
  1178. }
  1179. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1180. this.drawTimelineInterval(this.timeline_indicators[i], i);
  1181. }
  1182. }
  1183. // Special case for when the timeline is empty - we want to show the first and last
  1184. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1185. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1186. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1187. drawEmptyTimelineIntervals() {
  1188. const first = this.timeline_indicators[0];
  1189. const last = this.timeline_indicators[1];
  1190. if (first && last) {
  1191. first.style.opacity = '1';
  1192. last.style.opacity = '1';
  1193. first.style.transform = `translateX(0)`;
  1194. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1195. // side of the indicator, we need to offset it by the width of the label to make it look like
  1196. // it is at the end of the timeline
  1197. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1198. const firstLabel = first.children[0] as HTMLElement | undefined;
  1199. if (firstLabel) {
  1200. firstLabel.textContent = '0.00ms';
  1201. }
  1202. const lastLabel = last.children[0] as HTMLElement | undefined;
  1203. const lastLine = last.children[1] as HTMLElement | undefined;
  1204. if (lastLine && lastLabel) {
  1205. lastLabel.textContent = '0.00ms';
  1206. lastLine.style.opacity = '0';
  1207. }
  1208. }
  1209. }
  1210. drawContainers(
  1211. container: HTMLElement | null,
  1212. options: {list_width: number; span_list_width: number}
  1213. ) {
  1214. if (!container) return;
  1215. if (this.last_list_column_width !== options.list_width) {
  1216. container.style.setProperty(
  1217. '--list-column-width',
  1218. // @ts-expect-error we set number value type on purpose
  1219. Math.round(options.list_width * 1000) / 1000
  1220. );
  1221. this.last_list_column_width = options.list_width;
  1222. }
  1223. if (this.last_span_column_width !== options.span_list_width) {
  1224. container.style.setProperty(
  1225. '--span-column-width',
  1226. // @ts-expect-error we set number value type on purpose
  1227. Math.round(options.span_list_width * 1000) / 1000
  1228. );
  1229. this.last_span_column_width = options.span_list_width;
  1230. }
  1231. if (this.indicator_container) {
  1232. const correction =
  1233. (this.scrollbar_width / this.container_physical_space.width) *
  1234. options.span_list_width;
  1235. this.indicator_container.style.transform = `transform(${-this.scrollbar_width}px, 0)`;
  1236. const new_indicator_container_width = options.span_list_width - correction;
  1237. if (this.last_indicator_width !== new_indicator_container_width) {
  1238. this.indicator_container.style.width = new_indicator_container_width * 100 + '%';
  1239. this.last_indicator_width = new_indicator_container_width;
  1240. }
  1241. }
  1242. const dividerPosition =
  1243. Math.round(
  1244. (options.list_width *
  1245. (this.container_physical_space.width - this.scrollbar_width) -
  1246. DIVIDER_WIDTH / 2 -
  1247. 1) *
  1248. 10
  1249. ) / 10;
  1250. if (this.horizontal_scrollbar_container) {
  1251. this.horizontal_scrollbar_container.style.width =
  1252. (dividerPosition / this.container_physical_space.width) * 100 + '%';
  1253. }
  1254. if (this.divider) {
  1255. this.divider.style.transform = `translate(
  1256. ${dividerPosition}px, 0)`;
  1257. }
  1258. }
  1259. last_list_column_width = 0;
  1260. last_span_column_width = 0;
  1261. drawInvisibleBars() {
  1262. for (let i = 0; i < this.invisible_bars.length; i++) {
  1263. const invisible_bar = this.invisible_bars[i];
  1264. const text = this.span_text[i];
  1265. if (invisible_bar) {
  1266. const span_transform = this.computeSpanCSSMatrixTransform(invisible_bar?.space);
  1267. invisible_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1268. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1269. invisible_bar.ref.style.setProperty(
  1270. '--inverse-span-scale',
  1271. // @ts-expect-error we set number value type on purpose
  1272. isNaN(inverseScale) ? 1 : inverseScale
  1273. );
  1274. }
  1275. if (text) {
  1276. const [inside, text_transform] = this.computeSpanTextPlacement(
  1277. this.columns.list.column_nodes[i],
  1278. text.space,
  1279. text.text
  1280. );
  1281. if (text_transform === null) {
  1282. return;
  1283. }
  1284. text.ref.style.color = inside ? 'white' : '';
  1285. text.ref.style.transform = `translateX(${text_transform}px)`;
  1286. }
  1287. }
  1288. }
  1289. // END DRAW METHODS
  1290. teardown() {
  1291. this.row_measurer.off('max', this.onNewMaxRowWidth);
  1292. if (this.resize_observer) {
  1293. this.resize_observer.disconnect();
  1294. this.resize_observer = null;
  1295. this.container = null;
  1296. }
  1297. }
  1298. }
  1299. // Jest does not implement scroll updates, however since we have the
  1300. // middleware to handle scroll updates, we can dispatch a scroll event ourselves
  1301. function dispatchJestScrollUpdate(container: HTMLElement) {
  1302. if (!container) return;
  1303. if (process.env.NODE_ENV !== 'test') return;
  1304. // since we do not tightly control how browsers handle event dispatching, dispatch it async
  1305. window.requestAnimationFrame(() => {
  1306. container.dispatchEvent(new CustomEvent('scroll'));
  1307. });
  1308. }
  1309. function computeTimelineIntervals(
  1310. view: TraceView,
  1311. targetInterval: number,
  1312. results: (number | undefined)[]
  1313. ): void {
  1314. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  1315. let interval = minInterval;
  1316. if (targetInterval / interval > 5) {
  1317. interval *= 5;
  1318. } else if (targetInterval / interval > 2) {
  1319. interval *= 2;
  1320. }
  1321. let x = Math.ceil(view.x / interval) * interval;
  1322. let idx = -1;
  1323. if (x > 0) {
  1324. x -= interval;
  1325. }
  1326. while (x <= view.right) {
  1327. results[++idx] = x;
  1328. x += interval;
  1329. }
  1330. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  1331. results[++idx] = undefined;
  1332. }
  1333. }
  1334. export class VirtualizedList {
  1335. container: HTMLElement | null = null;
  1336. scrollHeight: number = 0;
  1337. scrollTop: number = 0;
  1338. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  1339. if (!this.container) {
  1340. return;
  1341. }
  1342. let position = index * 24;
  1343. const top = this.container.scrollTop;
  1344. const height = this.scrollHeight;
  1345. if (anchor === 'top') {
  1346. position = index * 24;
  1347. } else if (anchor === 'center') {
  1348. position = position - height / 2;
  1349. } else if (anchor === 'center if outside') {
  1350. if (position < top) {
  1351. // Element is above the view
  1352. position = position - height / 2;
  1353. } else if (position > top + height) {
  1354. // Element below the view
  1355. position = position - height / 2;
  1356. } else {
  1357. // Element is inside the view
  1358. return;
  1359. }
  1360. } else {
  1361. // If no anchor is provided, we default to 'auto'
  1362. if (position < top) {
  1363. position = position;
  1364. } else if (position > top + height) {
  1365. position = index * 24 - height + 24;
  1366. } else {
  1367. return;
  1368. }
  1369. }
  1370. this.container.scrollTop = position;
  1371. dispatchJestScrollUpdate(this.container);
  1372. }
  1373. }