virtualizedViewManager.tsx 49 KB

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