virtualizedViewManager.tsx 55 KB

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