virtualizedViewManager.tsx 55 KB

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