virtualizedViewManager.tsx 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  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) !== 0) {
  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. this.horizontal_scrollbar_container!.scrollLeft = -Math.round(
  664. this.columns.list.translate[0]
  665. );
  666. }
  667. clampRowTransform(transform: number): number {
  668. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  669. const max = this.row_measurer.max - columnWidth + this.ROW_PADDING_PX;
  670. if (this.row_measurer.queue.length > 0) {
  671. this.row_measurer.drain();
  672. }
  673. if (this.row_measurer.max < columnWidth) {
  674. return 0;
  675. }
  676. // Sometimes the wheel event glitches or jumps to a very high value
  677. if (transform > 0) {
  678. return 0;
  679. }
  680. if (transform < -max) {
  681. return -max;
  682. }
  683. return transform;
  684. }
  685. scrollEndSyncRaf: {id: number} | null = null;
  686. enqueueOnScrollEndOutOfBoundsCheck() {
  687. if (this.bringRowIntoViewAnimation !== null) {
  688. // Dont enqueue updates while view is scrolling
  689. return;
  690. }
  691. window.cancelAnimationFrame(this.scrollEndSyncRaf?.id ?? 0);
  692. this.scrollEndSyncRaf = requestAnimationTimeout(() => {
  693. this.onScrollEndOutOfBoundsCheck();
  694. }, 300);
  695. }
  696. onScrollEndOutOfBoundsCheck() {
  697. this.scrollEndSyncRaf = null;
  698. this.scrolling_source = null;
  699. const translation = this.columns.list.translate[0];
  700. let min = Number.POSITIVE_INFINITY;
  701. let max = Number.NEGATIVE_INFINITY;
  702. let innerMostNode: TraceTreeNode<any> | undefined;
  703. for (let i = 5; i < this.columns.span_list.column_refs.length - 5; i++) {
  704. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  705. if (width === undefined) {
  706. // this is unlikely to happen, but we should trigger a sync measure event if it does
  707. continue;
  708. }
  709. min = Math.min(min, width);
  710. max = Math.max(max, width);
  711. innerMostNode =
  712. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  713. ? this.columns.list.column_nodes[i]
  714. : innerMostNode;
  715. }
  716. if (innerMostNode) {
  717. if (translation + max < 0) {
  718. this.scrollRowIntoViewHorizontally(innerMostNode);
  719. } else if (
  720. translation + innerMostNode.depth * this.row_depth_padding >
  721. this.columns.list.width * this.container_physical_space.width
  722. ) {
  723. this.scrollRowIntoViewHorizontally(innerMostNode);
  724. }
  725. }
  726. }
  727. isOutsideOfViewOnKeyDown(node: TraceTreeNode<any>): boolean {
  728. const width = this.row_measurer.cache.get(node);
  729. if (width === undefined) {
  730. // this is unlikely to happen, but we should trigger a sync measure event if it does
  731. return false;
  732. }
  733. const translation = this.columns.list.translate[0];
  734. return (
  735. translation + node.depth * this.row_depth_padding < 0 ||
  736. translation + node.depth * this.row_depth_padding >
  737. (this.columns.list.width * this.container_physical_space.width) / 2
  738. );
  739. }
  740. scrollRowIntoViewHorizontally(
  741. node: TraceTreeNode<any>,
  742. duration: number = 600,
  743. offset_px: number = 0,
  744. position: 'exact' | 'measured' = 'measured'
  745. ) {
  746. const depth_px = -node.depth * this.row_depth_padding + offset_px;
  747. const newTransform =
  748. position === 'exact' ? depth_px : this.clampRowTransform(depth_px);
  749. this.animateScrollColumnTo(newTransform, duration);
  750. }
  751. bringRowIntoViewAnimation: number | null = null;
  752. animateScrollColumnTo(x: number, duration: number) {
  753. const start = performance.now();
  754. const startPosition = this.columns.list.translate[0];
  755. const distance = x - startPosition;
  756. if (duration === 0) {
  757. const rows = Array.from(
  758. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  759. ) as HTMLElement[];
  760. for (const row of rows) {
  761. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  762. }
  763. this.columns.list.translate[0] = x;
  764. if (this.horizontal_scrollbar_container) {
  765. this.horizontal_scrollbar_container.scrollLeft = -x;
  766. }
  767. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  768. return;
  769. }
  770. const animate = (now: number) => {
  771. const elapsed = now - start;
  772. const progress = duration > 0 ? elapsed / duration : 1;
  773. const eased = easeOutSine(progress);
  774. const pos = startPosition + distance * eased;
  775. const rows = Array.from(
  776. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  777. ) as HTMLElement[];
  778. for (const row of rows) {
  779. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  780. }
  781. if (progress < 1) {
  782. this.columns.list.translate[0] = pos;
  783. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  784. } else {
  785. this.bringRowIntoViewAnimation = null;
  786. this.horizontal_scrollbar_container!.scrollLeft = -x;
  787. this.columns.list.translate[0] = x;
  788. }
  789. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  790. };
  791. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  792. }
  793. initialize(container: HTMLElement) {
  794. if (this.container !== container && this.resize_observer !== null) {
  795. this.teardown();
  796. return;
  797. }
  798. this.container = container;
  799. this.drawContainers(this.container, {
  800. list_width: this.columns.list.width,
  801. span_list_width: this.columns.span_list.width,
  802. });
  803. this.row_measurer.on('max', this.onNewMaxRowWidth);
  804. this.resize_observer = new ResizeObserver(entries => {
  805. const entry = entries[0];
  806. if (!entry) {
  807. throw new Error('ResizeObserver entry is undefined');
  808. }
  809. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  810. this.draw();
  811. });
  812. this.resize_observer.observe(container);
  813. }
  814. recomputeSpanToPxMatrix() {
  815. const traceViewToSpace = this.trace_space.between(this.trace_view);
  816. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  817. this.span_to_px = mat3.multiply(
  818. this.span_to_px,
  819. traceViewToSpace,
  820. tracePhysicalToView
  821. );
  822. }
  823. computeRelativeLeftPositionFromOrigin(
  824. timestamp: number,
  825. entire_space: [number, number]
  826. ) {
  827. return (timestamp - entire_space[0]) / entire_space[1];
  828. }
  829. recomputeTimelineIntervals() {
  830. if (this.trace_view.width === 0) {
  831. this.intervals[0] = 0;
  832. this.intervals[1] = 0;
  833. for (let i = 2; i < this.intervals.length; i++) {
  834. this.intervals[i] = undefined;
  835. }
  836. return;
  837. }
  838. const tracePhysicalToView = this.trace_physical_space.between(this.trace_view);
  839. const time_at_100 =
  840. tracePhysicalToView[0] * (100 * window.devicePixelRatio) +
  841. tracePhysicalToView[6] -
  842. this.trace_view.x;
  843. computeTimelineIntervals(this.trace_view, time_at_100, this.intervals);
  844. }
  845. readonly span_matrix: [number, number, number, number, number, number] = [
  846. 1, 0, 0, 1, 0, 0,
  847. ];
  848. computeSpanCSSMatrixTransform(
  849. space: [number, number]
  850. ): [number, number, number, number, number, number] {
  851. const scale = space[1] / this.trace_view.width;
  852. this.span_matrix[0] = Math.max(scale, this.span_to_px[0] / this.trace_view.width);
  853. this.span_matrix[4] =
  854. (space[0] - this.to_origin) / this.span_to_px[0] -
  855. this.trace_view.x / this.span_to_px[0];
  856. return this.span_matrix;
  857. }
  858. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  859. if (!this.list) {
  860. return;
  861. }
  862. this.list.scrollToRow(index, anchor);
  863. }
  864. computeTransformXFromTimestamp(timestamp: number): number {
  865. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  866. }
  867. computeSpanTextPlacement(
  868. node: TraceTreeNode<TraceTree.NodeValue>,
  869. span_space: [number, number],
  870. text: string
  871. ): [number, number] {
  872. const text_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  873. const width = this.text_measurer.measure(text);
  874. const has_profiles = node && node.profiles.length > 0;
  875. const has_error_icons =
  876. node &&
  877. (node.profiles.length > 0 ||
  878. node.errors.size > 0 ||
  879. node.performance_issues.size > 0);
  880. const has_icons = has_profiles || has_error_icons;
  881. const node_width = span_space[1] / this.span_to_px[0];
  882. const TEXT_PADDING = 2;
  883. // This is inaccurate in the case of left anchored text. In order to determine a true overlap, we would need to compute
  884. // the distance between the min timestamp of an icon and beginning of the span. Once we determine the distance, we can compute
  885. // 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
  886. // to the left (20% of the time) and the node may have many errors, this could be computationally expensive to do on every frame.
  887. // 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
  888. // to determine if there is an overlap.
  889. const TEXT_PADDING_LEFT = text_left && has_icons ? 10 : TEXT_PADDING;
  890. const TEXT_PADDING_RIGHT =
  891. !text_left && has_icons
  892. ? node_width < 10
  893. ? // If the node is too small, we need to make sure the text is anchored to the right edge of the icon.
  894. // We take the distance from the right edge of the node to the right edge of the icon and subtract it from
  895. // the base width (10) and the base padding when (expanded) to get the correct padding. If we take only 10px
  896. // as our padding, the text can be anchored directly to the right edge of our icon - we want to preserve
  897. // a min padding of 2px.
  898. 12 - node_width
  899. : TEXT_PADDING
  900. : TEXT_PADDING;
  901. // precompute all anchor points aot, so we make the control flow more readable.
  902. // this wastes some cycles, but it's not a big deal as computers go brrrr when it comes to simple arithmetic.
  903. /// |---| text
  904. const right_outside =
  905. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) +
  906. TEXT_PADDING_RIGHT;
  907. /// text |---|
  908. const left_outside =
  909. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING_LEFT - width;
  910. // | text|
  911. const right_inside =
  912. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  913. width -
  914. TEXT_PADDING;
  915. // |text |
  916. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  917. // Right edge of the window (when span extends beyond the view)
  918. const window_right =
  919. this.computeTransformXFromTimestamp(
  920. this.to_origin + this.trace_view.left + this.trace_view.width
  921. ) -
  922. width -
  923. TEXT_PADDING;
  924. const window_left =
  925. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  926. TEXT_PADDING;
  927. const view_left = this.trace_view.x;
  928. const view_right = view_left + this.trace_view.width;
  929. const span_left = span_space[0] - this.to_origin;
  930. const span_right = span_left + span_space[1];
  931. const space_right = view_right - span_right;
  932. const space_left = span_left - view_left;
  933. // Span is completely outside of the view on the left side
  934. if (span_right < this.trace_view.x) {
  935. return text_left ? [1, right_inside] : [0, right_outside];
  936. }
  937. // Span is completely outside of the view on the right side
  938. if (span_left > this.trace_view.right) {
  939. return text_left ? [0, left_outside] : [1, left_inside];
  940. }
  941. // Span "spans" the entire view
  942. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  943. return text_left ? [1, window_left] : [1, window_right];
  944. }
  945. const full_span_px_width = span_space[1] / this.span_to_px[0];
  946. if (text_left) {
  947. // While we have space on the left, place the text there
  948. if (space_left > 0) {
  949. return [0, left_outside];
  950. }
  951. const distance = span_right - this.trace_view.left;
  952. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  953. // If the text fits inside the visible portion of the span, anchor it to the left
  954. // side of the window so that it is visible while the user pans the view
  955. if (visible_width - TEXT_PADDING >= width) {
  956. return [1, window_left];
  957. }
  958. // If the text doesnt fit inside the visible portion of the span,
  959. // anchor it to the inside right place in the span.
  960. return [1, right_inside];
  961. }
  962. // While we have space on the right, place the text there
  963. if (space_right > 0) {
  964. if (
  965. // If the right edge of the span is within 10% to the right edge of the space,
  966. // try and fit the text inside the span if possible. In case the span is too short
  967. // to fit the text, text_left case above will take care of anchoring it to the left
  968. // of the view.
  969. // Note: the accurate way for us to determine if the text fits to the right side
  970. // of the view would have been to compute the scaling matrix for a non zoomed view at 0,0
  971. // origin and check if it fits into the distance of space right edge - span right edge. In practice
  972. // however, it seems that a magical number works just fine.
  973. span_right > this.trace_space.right * 0.9 &&
  974. space_right / this.span_to_px[0] < width
  975. ) {
  976. return [1, right_inside];
  977. }
  978. return [0, right_outside];
  979. }
  980. // If text fits inside the span
  981. if (full_span_px_width > width) {
  982. const distance = span_right - this.trace_view.right;
  983. const visible_width =
  984. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  985. // If the text fits inside the visible portion of the span, anchor it to the right
  986. // side of the window so that it is visible while the user pans the view
  987. if (visible_width - TEXT_PADDING >= width) {
  988. return [1, window_right];
  989. }
  990. // If the text doesnt fit inside the visible portion of the span,
  991. // anchor it to the inside left of the span
  992. return [1, left_inside];
  993. }
  994. return [0, right_outside];
  995. }
  996. last_indicator_width = 0;
  997. draw(options: {list?: number; span_list?: number} = {}) {
  998. const list_width = options.list ?? this.columns.list.width;
  999. const span_list_width = options.span_list ?? this.columns.span_list.width;
  1000. this.drawContainers(this.container, {
  1001. list_width,
  1002. span_list_width,
  1003. });
  1004. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  1005. this.drawSpanBar(this.span_bars[i]);
  1006. this.drawSpanText(this.span_text[i], this.columns.list.column_nodes[i]);
  1007. this.drawSpanArrow(this.span_bars[i], this.span_arrows[i]);
  1008. }
  1009. this.drawInvisibleBars();
  1010. let start_indicator = 0;
  1011. let end_indicator = this.indicators.length;
  1012. while (start_indicator < this.indicators.length - 1) {
  1013. const indicator = this.indicators[start_indicator];
  1014. if (!indicator?.indicator) {
  1015. start_indicator++;
  1016. continue;
  1017. }
  1018. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1019. start_indicator++;
  1020. continue;
  1021. }
  1022. break;
  1023. }
  1024. while (end_indicator > start_indicator) {
  1025. const last_indicator = this.indicators[end_indicator - 1];
  1026. if (!last_indicator) {
  1027. end_indicator--;
  1028. continue;
  1029. }
  1030. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1031. end_indicator--;
  1032. continue;
  1033. }
  1034. break;
  1035. }
  1036. start_indicator = Math.max(0, start_indicator - 1);
  1037. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1038. for (let i = 0; i < this.indicators.length; i++) {
  1039. const entry = this.indicators[i];
  1040. if (!entry) {
  1041. continue;
  1042. }
  1043. if (i < start_indicator || i > end_indicator) {
  1044. entry.ref.style.opacity = '0';
  1045. continue;
  1046. }
  1047. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1048. const label = entry.ref.children[0] as HTMLElement | undefined;
  1049. const indicator_max = this.trace_physical_space.width + 1;
  1050. const indicator_min = -1;
  1051. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1052. const clamped_transform = clamp(transform, -1, indicator_max);
  1053. if (label_width === undefined) {
  1054. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1055. continue;
  1056. }
  1057. if (label) {
  1058. const PADDING = 2;
  1059. const label_window_left = PADDING;
  1060. const label_window_right = -label_width - PADDING;
  1061. if (transform < -1) {
  1062. label.style.transform = `translateX(${label_window_left}px)`;
  1063. } else if (transform >= indicator_max) {
  1064. label.style.transform = `translateX(${label_window_right}px)`;
  1065. } else {
  1066. const space_left = transform - PADDING - label_width / 2;
  1067. const space_right = transform + label_width / 2;
  1068. if (space_left < 0) {
  1069. const left = -label_width / 2 + Math.abs(space_left);
  1070. label.style.transform = `translateX(${left - 1}px)`;
  1071. } else if (space_right > this.trace_physical_space.width) {
  1072. const right =
  1073. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1074. label.style.transform = `translateX(${right}px)`;
  1075. } else {
  1076. label.style.transform = `translateX(${-label_width / 2}px)`;
  1077. }
  1078. }
  1079. }
  1080. entry.ref.style.opacity = '1';
  1081. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1082. }
  1083. this.drawTimelineIntervals();
  1084. }
  1085. // DRAW METHODS
  1086. drawSpanBar(span_bar: this['span_bars'][0]) {
  1087. if (!span_bar) return;
  1088. const span_transform = this.computeSpanCSSMatrixTransform(span_bar?.space);
  1089. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1090. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1091. span_bar.ref.style.setProperty(
  1092. '--inverse-span-scale',
  1093. // @ts-expect-error we set number value type on purpose
  1094. isNaN(inverseScale) ? 1 : inverseScale
  1095. );
  1096. }
  1097. drawSpanText(span_text: this['span_text'][0], node: TraceTreeNode<any> | undefined) {
  1098. if (!span_text) return;
  1099. const [inside, text_transform] = this.computeSpanTextPlacement(
  1100. node!,
  1101. span_text.space,
  1102. span_text.text
  1103. );
  1104. if (text_transform === null) {
  1105. return;
  1106. }
  1107. span_text.ref.style.color = inside ? 'white' : '';
  1108. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1109. }
  1110. drawSpanArrow(span_bar: this['span_bars'][0], span_arrow: this['span_arrows'][0]) {
  1111. if (!span_arrow || !span_bar) return;
  1112. const outside_left =
  1113. span_bar.space[0] - this.to_origin + span_bar.space[1] < this.trace_view.x;
  1114. const outside_right = span_bar.space[0] - this.to_origin > this.trace_view.right;
  1115. const visible = outside_left || outside_right;
  1116. if (visible !== span_arrow.visible) {
  1117. span_arrow.visible = visible;
  1118. span_arrow.position = outside_left ? 0 : 1;
  1119. if (visible) {
  1120. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1121. } else {
  1122. span_arrow.ref.className = 'TraceArrow';
  1123. }
  1124. }
  1125. }
  1126. drawTimelineInterval(ref: HTMLElement | undefined, index: number) {
  1127. if (!ref) {
  1128. return;
  1129. }
  1130. const interval = this.intervals[index];
  1131. if (interval === undefined) {
  1132. ref.style.opacity = '0';
  1133. return;
  1134. }
  1135. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1136. ref.style.opacity = '1';
  1137. ref.style.transform = `translateX(${placement}px)`;
  1138. const label = ref.children[0] as HTMLElement | undefined;
  1139. const duration = getDuration(interval / 1000, 2, true);
  1140. if (label && label?.textContent !== duration) {
  1141. label.textContent = duration;
  1142. }
  1143. }
  1144. drawTimelineIntervals() {
  1145. if (this.intervals[0] === 0 && this.intervals[1] === 0) {
  1146. this.drawEmptyTimelineIntervals();
  1147. for (let i = 2; i < this.timeline_indicators.length; i++) {
  1148. const indicator = this.timeline_indicators[i];
  1149. if (indicator) {
  1150. indicator.style.opacity = '0';
  1151. }
  1152. }
  1153. return;
  1154. }
  1155. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1156. this.drawTimelineInterval(this.timeline_indicators[i], i);
  1157. }
  1158. }
  1159. // Special case for when the timeline is empty - we want to show the first and last
  1160. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1161. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1162. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1163. drawEmptyTimelineIntervals() {
  1164. const first = this.timeline_indicators[0];
  1165. const last = this.timeline_indicators[1];
  1166. if (first && last) {
  1167. first.style.opacity = '1';
  1168. last.style.opacity = '1';
  1169. first.style.transform = `translateX(0)`;
  1170. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1171. // side of the indicator, we need to offset it by the width of the label to make it look like
  1172. // it is at the end of the timeline
  1173. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1174. const firstLabel = first.children[0] as HTMLElement | undefined;
  1175. if (firstLabel) {
  1176. firstLabel.textContent = '0.00ms';
  1177. }
  1178. const lastLabel = last.children[0] as HTMLElement | undefined;
  1179. const lastLine = last.children[1] as HTMLElement | undefined;
  1180. if (lastLine && lastLabel) {
  1181. lastLabel.textContent = '0.00ms';
  1182. lastLine.style.opacity = '0';
  1183. }
  1184. }
  1185. }
  1186. drawContainers(
  1187. container: HTMLElement | null,
  1188. options: {list_width: number; span_list_width: number}
  1189. ) {
  1190. if (!container) return;
  1191. if (this.last_list_column_width !== options.list_width) {
  1192. container.style.setProperty(
  1193. '--list-column-width',
  1194. // @ts-expect-error we set number value type on purpose
  1195. Math.round(options.list_width * 1000) / 1000
  1196. );
  1197. this.last_list_column_width = options.list_width;
  1198. }
  1199. if (this.last_span_column_width !== options.span_list_width) {
  1200. container.style.setProperty(
  1201. '--span-column-width',
  1202. // @ts-expect-error we set number value type on purpose
  1203. Math.round(options.span_list_width * 1000) / 1000
  1204. );
  1205. this.last_span_column_width = options.span_list_width;
  1206. }
  1207. if (this.indicator_container) {
  1208. const correction =
  1209. (this.scrollbar_width / this.container_physical_space.width) *
  1210. options.span_list_width;
  1211. this.indicator_container.style.transform = `transform(${-this.scrollbar_width}px, 0)`;
  1212. const new_indicator_container_width = options.span_list_width - correction;
  1213. if (this.last_indicator_width !== new_indicator_container_width) {
  1214. this.indicator_container.style.width = new_indicator_container_width * 100 + '%';
  1215. this.last_indicator_width = new_indicator_container_width;
  1216. }
  1217. }
  1218. if (this.divider) {
  1219. this.divider.style.transform = `translate(
  1220. ${
  1221. Math.round(
  1222. (options.list_width *
  1223. (this.container_physical_space.width - this.scrollbar_width) -
  1224. DIVIDER_WIDTH / 2 -
  1225. 1) *
  1226. 10
  1227. ) / 10
  1228. }px, 0)`;
  1229. }
  1230. }
  1231. last_list_column_width = 0;
  1232. last_span_column_width = 0;
  1233. drawInvisibleBars() {
  1234. for (let i = 0; i < this.invisible_bars.length; i++) {
  1235. const invisible_bar = this.invisible_bars[i];
  1236. if (invisible_bar) {
  1237. const span_transform = this.computeSpanCSSMatrixTransform(invisible_bar?.space);
  1238. invisible_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1239. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1240. invisible_bar.ref.style.setProperty(
  1241. '--inverse-span-scale',
  1242. // @ts-expect-error we set number value type on purpose
  1243. isNaN(inverseScale) ? 1 : inverseScale
  1244. );
  1245. }
  1246. }
  1247. }
  1248. // END DRAW METHODS
  1249. teardown() {
  1250. this.row_measurer.off('max', this.onNewMaxRowWidth);
  1251. if (this.resize_observer) {
  1252. this.resize_observer.disconnect();
  1253. this.resize_observer = null;
  1254. this.container = null;
  1255. }
  1256. }
  1257. }
  1258. // Jest does not implement scroll updates, however since we have the
  1259. // middleware to handle scroll updates, we can dispatch a scroll event ourselves
  1260. function dispatchJestScrollUpdate(container: HTMLElement) {
  1261. if (!container) return;
  1262. if (process.env.NODE_ENV !== 'test') return;
  1263. // since we do not tightly control how browsers handle event dispatching, dispatch it async
  1264. window.requestAnimationFrame(() => {
  1265. container.dispatchEvent(new CustomEvent('scroll'));
  1266. });
  1267. }
  1268. function computeTimelineIntervals(
  1269. view: TraceView,
  1270. targetInterval: number,
  1271. results: (number | undefined)[]
  1272. ): void {
  1273. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  1274. let interval = minInterval;
  1275. if (targetInterval / interval > 5) {
  1276. interval *= 5;
  1277. } else if (targetInterval / interval > 2) {
  1278. interval *= 2;
  1279. }
  1280. let x = Math.ceil(view.x / interval) * interval;
  1281. let idx = -1;
  1282. if (x > 0) {
  1283. x -= interval;
  1284. }
  1285. while (x <= view.right) {
  1286. results[++idx] = x;
  1287. x += interval;
  1288. }
  1289. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  1290. results[++idx] = undefined;
  1291. }
  1292. }
  1293. export class VirtualizedList {
  1294. container: HTMLElement | null = null;
  1295. scrollHeight: number = 0;
  1296. scrollTop: number = 0;
  1297. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  1298. if (!this.container) {
  1299. return;
  1300. }
  1301. let position = index * 24;
  1302. const top = this.container.scrollTop;
  1303. const height = this.scrollHeight;
  1304. if (anchor === 'top') {
  1305. position = index * 24;
  1306. } else if (anchor === 'center') {
  1307. position = position - height / 2;
  1308. } else if (anchor === 'center if outside') {
  1309. if (position < top) {
  1310. // Element is above the view
  1311. position = position - height / 2;
  1312. } else if (position > top + height) {
  1313. // Element below the view
  1314. position = position - height / 2;
  1315. } else {
  1316. // Element is inside the view
  1317. return;
  1318. }
  1319. } else {
  1320. // If no anchor is provided, we default to 'auto'
  1321. if (position < top) {
  1322. position = position;
  1323. } else if (position > top + height) {
  1324. position = index * 24 - height + 24;
  1325. } else {
  1326. return;
  1327. }
  1328. }
  1329. this.container.scrollTop = position;
  1330. dispatchJestScrollUpdate(this.container);
  1331. }
  1332. }