virtualizedViewManager.tsx 53 KB

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