virtualizedViewManager.tsx 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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 (Math.abs(distance) !== 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(span_space: [number, number], text: string): [number, number] {
  858. const TEXT_PADDING = 2;
  859. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  860. const width = this.text_measurer.measure(text);
  861. // precompute all anchor points aot, so we make the control flow more readable.
  862. // this wastes some cycles, but it's not a big deal as computers are fast when
  863. // it comes to simple arithmetic.
  864. const right_outside =
  865. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  866. const right_inside =
  867. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  868. width -
  869. TEXT_PADDING;
  870. const left_outside =
  871. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  872. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  873. const window_right =
  874. this.computeTransformXFromTimestamp(
  875. this.to_origin + this.trace_view.left + this.trace_view.width
  876. ) -
  877. width -
  878. TEXT_PADDING;
  879. const window_left =
  880. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  881. TEXT_PADDING;
  882. const view_left = this.trace_view.x;
  883. const view_right = view_left + this.trace_view.width;
  884. const span_left = span_space[0] - this.to_origin;
  885. const span_right = span_left + span_space[1];
  886. const space_right = view_right - span_right;
  887. const space_left = span_left - view_left;
  888. // Span is completely outside of the view on the left side
  889. if (span_right < this.trace_view.x) {
  890. return anchor_left ? [1, right_inside] : [0, right_outside];
  891. }
  892. // Span is completely outside of the view on the right side
  893. if (span_left > this.trace_view.right) {
  894. return anchor_left ? [0, left_outside] : [1, left_inside];
  895. }
  896. // Span "spans" the entire view
  897. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  898. return anchor_left ? [1, window_left] : [1, window_right];
  899. }
  900. const full_span_px_width = span_space[1] / this.span_to_px[0];
  901. if (anchor_left) {
  902. // While we have space on the left, place the text there
  903. if (space_left > 0) {
  904. return [0, left_outside];
  905. }
  906. const distance = span_right - this.trace_view.left;
  907. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  908. // If the text fits inside the visible portion of the span, anchor it to the left
  909. // side of the window so that it is visible while the user pans the view
  910. if (visible_width - TEXT_PADDING >= width) {
  911. return [1, window_left];
  912. }
  913. // If the text doesnt fit inside the visible portion of the span,
  914. // anchor it to the inside right place in the span.
  915. return [1, right_inside];
  916. }
  917. // While we have space on the right, place the text there
  918. if (space_right > 0) {
  919. if (
  920. // If the right edge of the span is within 10% to the right edge of the space,
  921. // try and fit the text inside the span if possible. In case the span is too short
  922. // to fit the text, anchor_left case above will take care of anchoring it to the left
  923. // of the view.
  924. // Note: the accurate way for us to determine if the text fits to the right side
  925. // of the view would have been to compute the scaling matrix for a non zoomed view at 0,0
  926. // origin and check if it fits into the distance of space right edge - span right edge. In practice
  927. // however, it seems that a magical number works just fine.
  928. span_right > this.trace_space.right * 0.9 &&
  929. space_right / this.span_to_px[0] < width
  930. ) {
  931. return [1, right_inside];
  932. }
  933. return [0, right_outside];
  934. }
  935. // If text fits inside the span
  936. if (full_span_px_width > width) {
  937. const distance = span_right - this.trace_view.right;
  938. const visible_width =
  939. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  940. // If the text fits inside the visible portion of the span, anchor it to the right
  941. // side of the window so that it is visible while the user pans the view
  942. if (visible_width - TEXT_PADDING >= width) {
  943. return [1, window_right];
  944. }
  945. // If the text doesnt fit inside the visible portion of the span,
  946. // anchor it to the inside left of the span
  947. return [1, left_inside];
  948. }
  949. return [0, right_outside];
  950. }
  951. draw(options: {list?: number; span_list?: number} = {}) {
  952. const list_width = options.list ?? this.columns.list.width;
  953. const span_list_width = options.span_list ?? this.columns.span_list.width;
  954. if (this.divider) {
  955. this.divider.style.setProperty(
  956. '--translate-x',
  957. // @ts-expect-error we set number value type on purpose
  958. Math.round(
  959. (list_width * (this.container_physical_space.width - this.scrollbar_width) -
  960. DIVIDER_WIDTH / 2 -
  961. 1) *
  962. 10
  963. ) / 10
  964. );
  965. }
  966. if (this.indicator_container) {
  967. const correction =
  968. (this.scrollbar_width / this.container_physical_space.width) * span_list_width;
  969. // @ts-expect-error we set number value type on purpose
  970. this.indicator_container.style.setProperty('--translate-x', -this.scrollbar_width);
  971. this.indicator_container.style.width = (span_list_width - correction) * 100 + '%';
  972. }
  973. if (this.container) {
  974. this.container.style.setProperty(
  975. '--list-column-width',
  976. // @ts-expect-error we set number value type on purpose
  977. Math.round(list_width * 1000) / 1000
  978. );
  979. this.container.style.setProperty(
  980. '--span-column-width',
  981. // @ts-expect-error we set number value type on purpose
  982. Math.round(span_list_width * 1000) / 1000
  983. );
  984. }
  985. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  986. const span_bar = this.span_bars[i];
  987. const span_arrow = this.span_arrows[i];
  988. if (span_bar) {
  989. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  990. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  991. span_bar.ref.style.setProperty(
  992. '--inverse-span-scale',
  993. 1 / span_transform[0] + ''
  994. );
  995. }
  996. const span_text = this.span_text[i];
  997. if (span_text) {
  998. const [inside, text_transform] = this.computeSpanTextPlacement(
  999. span_text.space,
  1000. span_text.text
  1001. );
  1002. if (text_transform === null) {
  1003. continue;
  1004. }
  1005. span_text.ref.style.color = inside ? 'white' : '';
  1006. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1007. if (span_arrow && span_bar) {
  1008. const outside_left =
  1009. span_bar.space[0] - this.to_origin + span_bar.space[1] < this.trace_view.x;
  1010. const outside_right =
  1011. span_bar.space[0] - this.to_origin > this.trace_view.right;
  1012. const visible = outside_left || outside_right;
  1013. if (visible !== span_arrow.visible) {
  1014. span_arrow.visible = visible;
  1015. span_arrow.position = outside_left ? 0 : 1;
  1016. if (visible) {
  1017. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1018. } else {
  1019. span_arrow.ref.className = 'TraceArrow';
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. for (let i = 0; i < this.invisible_bars.length; i++) {
  1026. const invisible_bar = this.invisible_bars[i];
  1027. if (invisible_bar) {
  1028. invisible_bar.ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(invisible_bar.space[0])}px)`;
  1029. }
  1030. }
  1031. let start_indicator = 0;
  1032. let end_indicator = this.indicators.length;
  1033. while (start_indicator < this.indicators.length - 1) {
  1034. const indicator = this.indicators[start_indicator];
  1035. if (!indicator?.indicator) {
  1036. start_indicator++;
  1037. continue;
  1038. }
  1039. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1040. start_indicator++;
  1041. continue;
  1042. }
  1043. break;
  1044. }
  1045. while (end_indicator > start_indicator) {
  1046. const last_indicator = this.indicators[end_indicator - 1];
  1047. if (!last_indicator) {
  1048. end_indicator--;
  1049. continue;
  1050. }
  1051. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1052. end_indicator--;
  1053. continue;
  1054. }
  1055. break;
  1056. }
  1057. start_indicator = Math.max(0, start_indicator - 1);
  1058. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1059. for (let i = 0; i < this.indicators.length; i++) {
  1060. const entry = this.indicators[i];
  1061. if (!entry) {
  1062. continue;
  1063. }
  1064. if (i < start_indicator || i > end_indicator) {
  1065. entry.ref.style.opacity = '0';
  1066. continue;
  1067. }
  1068. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1069. const label = entry.ref.children[0] as HTMLElement | undefined;
  1070. const indicator_max = this.trace_physical_space.width + 1;
  1071. const indicator_min = -1;
  1072. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1073. const clamped_transform = clamp(transform, -1, indicator_max);
  1074. if (label_width === undefined) {
  1075. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1076. continue;
  1077. }
  1078. if (label) {
  1079. const PADDING = 2;
  1080. const label_window_left = PADDING;
  1081. const label_window_right = -label_width - PADDING;
  1082. if (transform < -1) {
  1083. label.style.transform = `translateX(${label_window_left}px)`;
  1084. } else if (transform >= indicator_max) {
  1085. label.style.transform = `translateX(${label_window_right}px)`;
  1086. } else {
  1087. const space_left = transform - PADDING - label_width / 2;
  1088. const space_right = transform + label_width / 2;
  1089. if (space_left < 0) {
  1090. const left = -label_width / 2 + Math.abs(space_left);
  1091. label.style.transform = `translateX(${left - 1}px)`;
  1092. } else if (space_right > this.trace_physical_space.width) {
  1093. const right =
  1094. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1095. label.style.transform = `translateX(${right}px)`;
  1096. } else {
  1097. label.style.transform = `translateX(${-label_width / 2}px)`;
  1098. }
  1099. }
  1100. }
  1101. entry.ref.style.opacity = '1';
  1102. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  1103. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1104. }
  1105. // Renders timeline indicators and labels
  1106. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1107. const indicator = this.timeline_indicators[i];
  1108. // Special case for when the timeline is empty - we want to show the first and last
  1109. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1110. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1111. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1112. if (i === 0 && this.intervals[0] === 0 && this.intervals[1] === 0) {
  1113. const first = this.timeline_indicators[0];
  1114. const last = this.timeline_indicators[1];
  1115. if (first && last) {
  1116. first.style.opacity = '1';
  1117. last.style.opacity = '1';
  1118. first.style.transform = `translateX(0)`;
  1119. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1120. // side of the indicator, we need to offset it by the width of the label to make it look like
  1121. // it is at the end of the timeline
  1122. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1123. const firstLabel = first.children[0] as HTMLElement | undefined;
  1124. if (firstLabel) {
  1125. firstLabel.textContent = '0.00ms';
  1126. }
  1127. const lastLabel = last.children[0] as HTMLElement | undefined;
  1128. const lastLine = last.children[1] as HTMLElement | undefined;
  1129. if (lastLine && lastLabel) {
  1130. lastLabel.textContent = '0.00ms';
  1131. lastLine.style.opacity = '0';
  1132. i = 1;
  1133. }
  1134. continue;
  1135. }
  1136. }
  1137. if (indicator) {
  1138. const interval = this.intervals[i];
  1139. if (interval === undefined) {
  1140. indicator.style.opacity = '0';
  1141. continue;
  1142. }
  1143. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1144. indicator.style.opacity = '1';
  1145. indicator.style.transform = `translateX(${placement}px)`;
  1146. const label = indicator.children[0] as HTMLElement | undefined;
  1147. const duration = getDuration(interval / 1000, 2, true);
  1148. if (label && label?.textContent !== duration) {
  1149. label.textContent = duration;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. teardown() {
  1155. this.row_measurer.off('max', this.onNewMaxRowWidth);
  1156. if (this.resize_observer) {
  1157. this.resize_observer.disconnect();
  1158. }
  1159. }
  1160. }
  1161. // Jest does not implement scroll updates, however since we have the
  1162. // middleware to handle scroll updates, we can dispatch a scroll event ourselves
  1163. function dispatchJestScrollUpdate(container: HTMLElement) {
  1164. if (!container) return;
  1165. if (process.env.NODE_ENV !== 'test') return;
  1166. // since we do not tightly control how browsers handle event dispatching, dispatch it async
  1167. window.requestAnimationFrame(() => {
  1168. container.dispatchEvent(new CustomEvent('scroll'));
  1169. });
  1170. }
  1171. function computeTimelineIntervals(
  1172. view: TraceView,
  1173. targetInterval: number,
  1174. results: (number | undefined)[]
  1175. ): void {
  1176. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  1177. let interval = minInterval;
  1178. if (targetInterval / interval > 5) {
  1179. interval *= 5;
  1180. } else if (targetInterval / interval > 2) {
  1181. interval *= 2;
  1182. }
  1183. let x = Math.ceil(view.x / interval) * interval;
  1184. let idx = -1;
  1185. if (x > 0) {
  1186. x -= interval;
  1187. }
  1188. while (x <= view.right) {
  1189. results[++idx] = x;
  1190. x += interval;
  1191. }
  1192. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  1193. results[++idx] = undefined;
  1194. }
  1195. }
  1196. export class VirtualizedList {
  1197. container: HTMLElement | null = null;
  1198. scrollHeight: number = 0;
  1199. scrollTop: number = 0;
  1200. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  1201. if (!this.container) {
  1202. return;
  1203. }
  1204. let position = index * 24;
  1205. const top = this.container.scrollTop;
  1206. const height = this.scrollHeight;
  1207. if (anchor === 'top') {
  1208. position = index * 24;
  1209. } else if (anchor === 'center') {
  1210. position = position - height / 2;
  1211. } else if (anchor === 'center if outside') {
  1212. if (position < top) {
  1213. // Element is above the view
  1214. position = position - height / 2;
  1215. } else if (position > top + height) {
  1216. // Element below the view
  1217. position = position - height / 2;
  1218. } else {
  1219. // Element is inside the view
  1220. return;
  1221. }
  1222. } else {
  1223. // If no anchor is provided, we default to 'auto'
  1224. if (position < top) {
  1225. position = position;
  1226. } else if (position > top + height) {
  1227. position = index * 24 - height + 24;
  1228. } else {
  1229. return;
  1230. }
  1231. }
  1232. this.container.scrollTop = position;
  1233. dispatchJestScrollUpdate(this.container);
  1234. }
  1235. }