virtualizedViewManager.tsx 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792
  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 is the first zoom event, then read the clientX and offset it from the container element as offset
  465. // is relative to the **target element**. In subsequent events, we can use the offsetX property as
  466. // the pointer-events are going to be disabled and we will receive the correct offsetX value
  467. let offsetX = 0;
  468. if (!this.timers.onWheelEnd) {
  469. offsetX =
  470. (event.currentTarget as HTMLElement | null)?.getBoundingClientRect()?.left ?? 0;
  471. this.onWheelStart();
  472. }
  473. this.enqueueOnWheelEndRaf();
  474. const scale = 1 - event.deltaY * 0.01 * -1;
  475. const x = offsetX > 0 ? event.clientX - offsetX : event.offsetX;
  476. const configSpaceCursor = this.getConfigSpaceCursor({
  477. x: x,
  478. y: 0,
  479. });
  480. const center = vec2.fromValues(configSpaceCursor[0], 0);
  481. const centerScaleMatrix = mat3.create();
  482. mat3.fromTranslation(centerScaleMatrix, center);
  483. mat3.scale(centerScaleMatrix, centerScaleMatrix, vec2.fromValues(scale, 1));
  484. mat3.translate(
  485. centerScaleMatrix,
  486. centerScaleMatrix,
  487. vec2.fromValues(-center[0], 0)
  488. );
  489. const newView = this.trace_view.transform(centerScaleMatrix);
  490. // When users zoom in, the matrix will compute a width value that is lower than the min,
  491. // which results in the value of x being incorrectly set and the view moving to the right.
  492. // To prevent this, we will only update the x position if the new width is greater than the min zoom precision.
  493. this.setTraceView({
  494. x: newView[2] < this.MAX_ZOOM_PRECISION ? this.trace_view.x : newView[0],
  495. width: newView[2],
  496. });
  497. this.draw();
  498. } else {
  499. if (!this.timers.onWheelEnd) {
  500. this.onWheelStart();
  501. }
  502. this.enqueueOnWheelEndRaf();
  503. // Holding shift key allows for horizontal scrolling
  504. const distance = event.shiftKey
  505. ? getHorizontalDelta(event.deltaX, event.deltaY)
  506. : event.deltaX;
  507. if (
  508. event.shiftKey ||
  509. (!event.shiftKey && Math.abs(event.deltaX) > Math.abs(event.deltaY))
  510. ) {
  511. event.preventDefault();
  512. }
  513. const physical_delta_pct = distance / this.trace_physical_space.width;
  514. const view_delta = physical_delta_pct * this.trace_view.width;
  515. this.setTraceView({
  516. x: this.trace_view.x + view_delta,
  517. });
  518. this.draw();
  519. }
  520. }
  521. onBringRowIntoView(space: [number, number]) {
  522. if (this.timers.onZoomIntoSpace !== null) {
  523. window.cancelAnimationFrame(this.timers.onZoomIntoSpace);
  524. this.timers.onZoomIntoSpace = null;
  525. }
  526. if (space[0] - this.to_origin > this.trace_view.x) {
  527. this.onZoomIntoSpace([
  528. space[0] + space[1] / 2 - this.trace_view.width / 2,
  529. this.trace_view.width,
  530. ]);
  531. } else if (space[0] - this.to_origin < this.trace_view.x) {
  532. this.onZoomIntoSpace([
  533. space[0] + space[1] / 2 - this.trace_view.width / 2,
  534. this.trace_view.width,
  535. ]);
  536. }
  537. }
  538. animateViewTo(node_space: [number, number]) {
  539. const start = node_space[0];
  540. const width = node_space[1] > 0 ? node_space[1] : this.trace_view.width;
  541. const margin = 0.2 * width;
  542. this.setTraceView({x: start - margin - this.to_origin, width: width + margin * 2});
  543. this.draw();
  544. }
  545. onZoomIntoSpace(space: [number, number]) {
  546. let distance_x = space[0] - this.to_origin - this.trace_view.x;
  547. let final_x = space[0] - this.to_origin;
  548. let final_width = space[1];
  549. const distance_width = this.trace_view.width - space[1];
  550. if (space[1] < this.MAX_ZOOM_PRECISION) {
  551. distance_x -= this.MAX_ZOOM_PRECISION / 2 - space[1] / 2;
  552. final_x -= this.MAX_ZOOM_PRECISION / 2 - space[1] / 2;
  553. final_width = this.MAX_ZOOM_PRECISION;
  554. }
  555. const start_x = this.trace_view.x;
  556. const start_width = this.trace_view.width;
  557. const max_distance = Math.max(Math.abs(distance_x), Math.abs(distance_width));
  558. const p = max_distance !== 0 ? Math.log10(max_distance) : 1;
  559. // We need to clamp the duration to prevent the animation from being too slow,
  560. // sometimes the distances are very large as traces can be hours in duration
  561. const duration = clamp(200 + 70 * Math.abs(p), 200, 600);
  562. const start = performance.now();
  563. const rafCallback = (now: number) => {
  564. const elapsed = now - start;
  565. const progress = elapsed / duration;
  566. const eased = easeOutSine(progress);
  567. const x = start_x + distance_x * eased;
  568. const width = start_width - distance_width * eased;
  569. this.setTraceView({x, width});
  570. this.draw();
  571. if (progress < 1) {
  572. this.timers.onZoomIntoSpace = window.requestAnimationFrame(rafCallback);
  573. } else {
  574. this.timers.onZoomIntoSpace = null;
  575. this.setTraceView({x: final_x, width: final_width});
  576. this.draw();
  577. }
  578. };
  579. this.timers.onZoomIntoSpace = window.requestAnimationFrame(rafCallback);
  580. }
  581. resetZoom() {
  582. this.onZoomIntoSpace([this.to_origin, this.trace_space.width]);
  583. }
  584. enqueueOnWheelEndRaf() {
  585. if (this.timers.onWheelEnd !== null) {
  586. window.cancelAnimationFrame(this.timers.onWheelEnd);
  587. }
  588. const start = performance.now();
  589. const rafCallback = (now: number) => {
  590. const elapsed = now - start;
  591. if (elapsed > 200) {
  592. this.onWheelEnd();
  593. } else {
  594. this.timers.onWheelEnd = window.requestAnimationFrame(rafCallback);
  595. }
  596. };
  597. this.timers.onWheelEnd = window.requestAnimationFrame(rafCallback);
  598. }
  599. onWheelStart() {
  600. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  601. const span_list = this.columns.span_list.column_refs[i];
  602. if (span_list?.children?.[0]) {
  603. (span_list.children[0] as HTMLElement).style.pointerEvents = 'none';
  604. }
  605. const span_text = this.span_text[i];
  606. if (span_text) {
  607. span_text.ref.style.pointerEvents = 'none';
  608. }
  609. }
  610. for (let i = 0; i < this.indicators.length; i++) {
  611. const indicator = this.indicators[i];
  612. if (indicator?.ref) {
  613. indicator.ref.style.pointerEvents = 'none';
  614. }
  615. }
  616. }
  617. onWheelEnd() {
  618. this.timers.onWheelEnd = null;
  619. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  620. const span_list = this.columns.span_list.column_refs[i];
  621. if (span_list?.children?.[0]) {
  622. (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto';
  623. }
  624. const span_text = this.span_text[i];
  625. if (span_text) {
  626. span_text.ref.style.pointerEvents = 'auto';
  627. }
  628. }
  629. for (let i = 0; i < this.indicators.length; i++) {
  630. const indicator = this.indicators[i];
  631. if (indicator?.ref) {
  632. indicator.ref.style.pointerEvents = 'auto';
  633. }
  634. }
  635. }
  636. maybeInitializeTraceViewFromQS(fov: string): void {
  637. const [x, width] = fov.split(',').map(parseFloat);
  638. if (isNaN(x) || isNaN(width)) {
  639. return;
  640. }
  641. if (width <= 0 || width > this.trace_space.width) {
  642. return;
  643. }
  644. if (x < 0 || x > this.trace_space.width) {
  645. return;
  646. }
  647. this.setTraceView({x, width});
  648. }
  649. setTraceView(view: {width?: number; x?: number}) {
  650. // In cases where a trace might have a single error, there is no concept of a timeline
  651. if (this.trace_view.width === 0) {
  652. return;
  653. }
  654. const x = view.x ?? this.trace_view.x;
  655. const width = view.width ?? this.trace_view.width;
  656. this.trace_view.width = clamp(
  657. width,
  658. this.MAX_ZOOM_PRECISION,
  659. this.trace_space.width - this.trace_view.x
  660. );
  661. this.trace_view.x = clamp(
  662. x,
  663. 0,
  664. Math.max(this.trace_space.width - width, this.MAX_ZOOM_PRECISION)
  665. );
  666. this.recomputeTimelineIntervals();
  667. this.recomputeSpanToPxMatrix();
  668. this.enqueueFOVQueryParamSync();
  669. this.syncResetZoomButton();
  670. }
  671. enqueueFOVQueryParamSync() {
  672. if (this.timers.onFovChange !== null) {
  673. window.cancelAnimationFrame(this.timers.onFovChange.id);
  674. }
  675. this.timers.onFovChange = requestAnimationTimeout(() => {
  676. browserHistory.replace({
  677. pathname: location.pathname,
  678. query: {
  679. ...qs.parse(location.search),
  680. fov: `${this.trace_view.x},${this.trace_view.width}`,
  681. },
  682. });
  683. this.timers.onFovChange = null;
  684. }, 500);
  685. }
  686. onNewMaxRowWidth(max) {
  687. this.syncHorizontalScrollbar(max);
  688. }
  689. syncHorizontalScrollbar(max: number) {
  690. const child = this.horizontal_scrollbar_container?.children[0] as
  691. | HTMLElement
  692. | undefined;
  693. if (child) {
  694. child.style.width =
  695. Math.round(max - this.scrollbar_width + this.ROW_PADDING_PX) + 'px';
  696. }
  697. }
  698. syncResetZoomButton() {
  699. if (!this.reset_zoom_button) return;
  700. this.reset_zoom_button.disabled =
  701. this.trace_view.x === 0 && this.trace_view.width === this.trace_space.width;
  702. }
  703. maybeSyncViewWithVerticalIndicator(key: string) {
  704. const indicator = this.vertical_indicators[key];
  705. if (!indicator || typeof indicator.timestamp !== 'number') {
  706. return;
  707. }
  708. const timestamp = indicator.timestamp - this.to_origin;
  709. this.setTraceView({
  710. x: timestamp - this.trace_view.width / 2,
  711. width: this.trace_view.width,
  712. });
  713. this.draw();
  714. }
  715. onHorizontalScrollbarScroll(_event: Event) {
  716. if (!this.scrolling_source) {
  717. this.scrolling_source = 'fake scrollbar';
  718. }
  719. if (this.scrolling_source !== 'fake scrollbar') {
  720. return;
  721. }
  722. const scrollLeft = this.horizontal_scrollbar_container?.scrollLeft;
  723. if (typeof scrollLeft !== 'number') {
  724. return;
  725. }
  726. this.enqueueOnScrollEndOutOfBoundsCheck();
  727. this.columns.list.translate[0] = this.clampRowTransform(-scrollLeft);
  728. const rows = Array.from(
  729. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  730. ) as HTMLElement[];
  731. for (const row of rows) {
  732. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  733. }
  734. }
  735. onSyncedScrollbarScroll(event: WheelEvent) {
  736. if (!this.scrolling_source) {
  737. this.scrolling_source = 'list';
  738. }
  739. if (this.scrolling_source !== 'list') {
  740. return;
  741. }
  742. // Holding shift key allows for horizontal scrolling
  743. const distance = event.shiftKey ? event.deltaY : event.deltaX;
  744. if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
  745. // Prevents firing back/forward navigation
  746. event.preventDefault();
  747. } else {
  748. return;
  749. }
  750. if (this.timers.onRowIntoView !== null) {
  751. window.cancelAnimationFrame(this.timers.onRowIntoView);
  752. this.timers.onRowIntoView = null;
  753. }
  754. this.enqueueOnScrollEndOutOfBoundsCheck();
  755. const newTransform = this.clampRowTransform(
  756. this.columns.list.translate[0] - distance
  757. );
  758. if (newTransform === this.columns.list.translate[0]) {
  759. return;
  760. }
  761. this.columns.list.translate[0] = newTransform;
  762. const rows = Array.from(
  763. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  764. ) as HTMLElement[];
  765. for (const row of rows) {
  766. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  767. }
  768. if (this.horizontal_scrollbar_container) {
  769. this.horizontal_scrollbar_container.scrollLeft = -Math.round(
  770. this.columns.list.translate[0]
  771. );
  772. }
  773. }
  774. clampRowTransform(transform: number): number {
  775. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  776. const max = this.row_measurer.max - columnWidth + this.ROW_PADDING_PX;
  777. if (this.row_measurer.queue.length > 0) {
  778. this.row_measurer.drain();
  779. }
  780. if (this.row_measurer.max < columnWidth) {
  781. return 0;
  782. }
  783. // Sometimes the wheel event glitches or jumps to a very high value
  784. if (transform > 0) {
  785. return 0;
  786. }
  787. if (transform < -max) {
  788. return -max;
  789. }
  790. return transform;
  791. }
  792. enqueueOnScrollEndOutOfBoundsCheck() {
  793. if (this.timers.onRowIntoView !== null) {
  794. // Dont enqueue updates while view is scrolling
  795. return;
  796. }
  797. window.cancelAnimationFrame(this.timers.onScrollEndSync?.id ?? 0);
  798. this.timers.onScrollEndSync = requestAnimationTimeout(() => {
  799. this.onScrollEndOutOfBoundsCheck();
  800. }, 300);
  801. }
  802. onScrollEndOutOfBoundsCheck() {
  803. this.timers.onScrollEndSync = null;
  804. this.scrolling_source = null;
  805. const translation = this.columns.list.translate[0];
  806. let min = Number.POSITIVE_INFINITY;
  807. let max = Number.NEGATIVE_INFINITY;
  808. let innerMostNode: TraceTreeNode<any> | undefined;
  809. for (let i = 5; i < this.columns.span_list.column_refs.length - 5; i++) {
  810. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  811. if (width === undefined) {
  812. // this is unlikely to happen, but we should trigger a sync measure event if it does
  813. continue;
  814. }
  815. min = Math.min(min, width);
  816. max = Math.max(max, width);
  817. innerMostNode =
  818. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  819. ? this.columns.list.column_nodes[i]
  820. : innerMostNode;
  821. }
  822. if (innerMostNode) {
  823. if (translation + max < 0) {
  824. this.scrollRowIntoViewHorizontally(innerMostNode);
  825. } else if (
  826. translation + innerMostNode.depth * this.row_depth_padding >
  827. this.columns.list.width * this.container_physical_space.width
  828. ) {
  829. this.scrollRowIntoViewHorizontally(innerMostNode);
  830. }
  831. }
  832. }
  833. isOutsideOfViewOnKeyDown(node: TraceTreeNode<any>): boolean {
  834. const width = this.row_measurer.cache.get(node);
  835. if (width === undefined) {
  836. // this is unlikely to happen, but we should trigger a sync measure event if it does
  837. return false;
  838. }
  839. const translation = this.columns.list.translate[0];
  840. return (
  841. translation + node.depth * this.row_depth_padding < 0 ||
  842. translation + node.depth * this.row_depth_padding >
  843. (this.columns.list.width * this.container_physical_space.width) / 2
  844. );
  845. }
  846. scrollRowIntoViewHorizontally(
  847. node: TraceTreeNode<any>,
  848. duration: number = 600,
  849. offset_px: number = 0,
  850. position: 'exact' | 'measured' = 'measured'
  851. ) {
  852. const depth_px = -node.depth * this.row_depth_padding + offset_px;
  853. const newTransform =
  854. position === 'exact' ? depth_px : this.clampRowTransform(depth_px);
  855. this.animateScrollColumnTo(newTransform, duration);
  856. }
  857. animateScrollColumnTo(x: number, duration: number) {
  858. const start = performance.now();
  859. const startPosition = this.columns.list.translate[0];
  860. const distance = x - startPosition;
  861. if (duration === 0) {
  862. const rows = Array.from(
  863. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  864. ) as HTMLElement[];
  865. for (const row of rows) {
  866. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  867. }
  868. this.columns.list.translate[0] = x;
  869. if (this.horizontal_scrollbar_container) {
  870. this.horizontal_scrollbar_container.scrollLeft = -x;
  871. }
  872. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  873. return;
  874. }
  875. const animate = (now: number) => {
  876. const elapsed = now - start;
  877. const progress = duration > 0 ? elapsed / duration : 1;
  878. const eased = easeOutSine(progress);
  879. const pos = startPosition + distance * eased;
  880. const rows = Array.from(
  881. document.querySelectorAll('.TraceRow .TraceLeftColumn > div')
  882. ) as HTMLElement[];
  883. for (const row of rows) {
  884. row.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  885. }
  886. if (progress < 1) {
  887. this.columns.list.translate[0] = pos;
  888. this.timers.onRowIntoView = window.requestAnimationFrame(animate);
  889. } else {
  890. this.timers.onRowIntoView = null;
  891. if (this.horizontal_scrollbar_container) {
  892. this.horizontal_scrollbar_container.scrollLeft = -x;
  893. }
  894. this.columns.list.translate[0] = x;
  895. }
  896. dispatchJestScrollUpdate(this.horizontal_scrollbar_container!);
  897. };
  898. this.timers.onRowIntoView = window.requestAnimationFrame(animate);
  899. }
  900. initialize(container: HTMLElement) {
  901. if (this.container !== container && this.resize_observer !== null) {
  902. this.teardown();
  903. return;
  904. }
  905. this.container = container;
  906. this.drawContainers(this.container, {
  907. list_width: this.columns.list.width,
  908. span_list_width: this.columns.span_list.width,
  909. });
  910. this.row_measurer.on('max', this.onNewMaxRowWidth);
  911. this.resize_observer = new ResizeObserver(entries => {
  912. const entry = entries[0];
  913. if (!entry) {
  914. throw new Error('ResizeObserver entry is undefined');
  915. }
  916. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  917. this.draw();
  918. });
  919. this.resize_observer.observe(container);
  920. }
  921. recomputeSpanToPxMatrix() {
  922. const traceViewToSpace = this.trace_space.between(this.trace_view);
  923. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  924. this.span_to_px = mat3.multiply(
  925. this.span_to_px,
  926. traceViewToSpace,
  927. tracePhysicalToView
  928. );
  929. }
  930. computeRelativeLeftPositionFromOrigin(
  931. timestamp: number,
  932. entire_space: [number, number]
  933. ) {
  934. return (timestamp - entire_space[0]) / entire_space[1];
  935. }
  936. recomputeTimelineIntervals() {
  937. if (this.trace_view.width === 0) {
  938. this.intervals[0] = 0;
  939. this.intervals[1] = 0;
  940. for (let i = 2; i < this.intervals.length; i++) {
  941. this.intervals[i] = undefined;
  942. }
  943. return;
  944. }
  945. const tracePhysicalToView = this.trace_physical_space.between(this.trace_view);
  946. const time_at_100 =
  947. tracePhysicalToView[0] * (100 * window.devicePixelRatio) +
  948. tracePhysicalToView[6] -
  949. this.trace_view.x;
  950. computeTimelineIntervals(this.trace_view, time_at_100, this.intervals);
  951. }
  952. readonly span_matrix: [number, number, number, number, number, number] = [
  953. 1, 0, 0, 1, 0, 0,
  954. ];
  955. computeSpanCSSMatrixTransform(
  956. space: [number, number]
  957. ): [number, number, number, number, number, number] {
  958. const scale = space[1] / this.trace_view.width;
  959. this.span_matrix[0] = Math.max(scale, this.span_to_px[0] / this.trace_view.width);
  960. this.span_matrix[4] =
  961. (space[0] - this.to_origin) / this.span_to_px[0] -
  962. this.trace_view.x / this.span_to_px[0];
  963. return this.span_matrix;
  964. }
  965. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  966. if (!this.list) {
  967. return;
  968. }
  969. this.list.scrollToRow(index, anchor);
  970. }
  971. computeTransformXFromTimestamp(timestamp: number): number {
  972. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  973. }
  974. computeSpanTextPlacement(
  975. node: TraceTreeNode<TraceTree.NodeValue>,
  976. span_space: [number, number],
  977. text: string
  978. ): [number, number] {
  979. const text_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  980. const width = this.text_measurer.measure(text);
  981. const has_profiles = node && node.profiles.length > 0;
  982. const has_error_icons =
  983. node &&
  984. (node.profiles.length > 0 ||
  985. node.errors.size > 0 ||
  986. node.performance_issues.size > 0);
  987. const has_icons = has_profiles || has_error_icons;
  988. const node_width = span_space[1] / this.span_to_px[0];
  989. const TEXT_PADDING = 2;
  990. // This is inaccurate in the case of left anchored text. In order to determine a true overlap, we would need to compute
  991. // the distance between the min timestamp of an icon and beginning of the span. Once we determine the distance, we can compute
  992. // 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
  993. // to the left (20% of the time) and the node may have many errors, this could be computationally expensive to do on every frame.
  994. // 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
  995. // to determine if there is an overlap.
  996. const TEXT_PADDING_LEFT = text_left && has_icons ? 10 : TEXT_PADDING;
  997. const TEXT_PADDING_RIGHT =
  998. !text_left && has_icons
  999. ? node_width < 10
  1000. ? // If the node is too small, we need to make sure the text is anchored to the right edge of the icon.
  1001. // We take the distance from the right edge of the node to the right edge of the icon and subtract it from
  1002. // the base width (10) and the base padding when (expanded) to get the correct padding. If we take only 10px
  1003. // as our padding, the text can be anchored directly to the right edge of our icon - we want to preserve
  1004. // a min padding of 2px.
  1005. 12 - node_width
  1006. : TEXT_PADDING
  1007. : TEXT_PADDING;
  1008. // precompute all anchor points aot, so we make the control flow more readable.
  1009. // this wastes some cycles, but it's not a big deal as computers go brrrr when it comes to simple arithmetic.
  1010. /// |---| text
  1011. const right_outside =
  1012. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) +
  1013. TEXT_PADDING_RIGHT;
  1014. /// text |---|
  1015. const left_outside =
  1016. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING_LEFT - width;
  1017. // | text|
  1018. const right_inside =
  1019. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  1020. width -
  1021. TEXT_PADDING;
  1022. // |text |
  1023. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  1024. // Right edge of the window (when span extends beyond the view)
  1025. const window_right =
  1026. this.computeTransformXFromTimestamp(
  1027. this.to_origin + this.trace_view.left + this.trace_view.width
  1028. ) -
  1029. width -
  1030. TEXT_PADDING;
  1031. const window_left =
  1032. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  1033. TEXT_PADDING;
  1034. const view_left = this.trace_view.x;
  1035. const view_right = view_left + this.trace_view.width;
  1036. const span_left = span_space[0] - this.to_origin;
  1037. const span_right = span_left + span_space[1];
  1038. const space_right = view_right - span_right;
  1039. const space_left = span_left - view_left;
  1040. // Span is completely outside of the view on the left side
  1041. if (span_right < this.trace_view.x) {
  1042. return text_left ? [1, right_inside] : [0, right_outside];
  1043. }
  1044. // Span is completely outside of the view on the right side
  1045. if (span_left > this.trace_view.right) {
  1046. return text_left ? [0, left_outside] : [1, left_inside];
  1047. }
  1048. // Span "spans" the entire view
  1049. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  1050. return text_left ? [1, window_left] : [1, window_right];
  1051. }
  1052. const full_span_px_width = span_space[1] / this.span_to_px[0];
  1053. if (text_left) {
  1054. // While we have space on the left, place the text there
  1055. if (space_left > 0) {
  1056. return [0, left_outside];
  1057. }
  1058. const distance = span_right - this.trace_view.left;
  1059. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  1060. // If the text fits inside the visible portion of the span, anchor it to the left
  1061. // side of the window so that it is visible while the user pans the view
  1062. if (visible_width - TEXT_PADDING >= width) {
  1063. return [1, window_left];
  1064. }
  1065. // If the text doesnt fit inside the visible portion of the span,
  1066. // anchor it to the inside right place in the span.
  1067. return [1, right_inside];
  1068. }
  1069. // While we have space on the right, place the text there
  1070. if (space_right > 0) {
  1071. if (
  1072. // If the right edge of the span is within 10% to the right edge of the space,
  1073. // try and fit the text inside the span if possible. In case the span is too short
  1074. // to fit the text, text_left case above will take care of anchoring it to the left
  1075. // of the view.
  1076. // Note: the accurate way for us to determine if the text fits to the right side
  1077. // of the view would have been to compute the scaling matrix for a non zoomed view at 0,0
  1078. // origin and check if it fits into the distance of space right edge - span right edge. In practice
  1079. // however, it seems that a magical number works just fine.
  1080. span_right > this.trace_space.right * 0.9 &&
  1081. space_right / this.span_to_px[0] < width
  1082. ) {
  1083. return [1, right_inside];
  1084. }
  1085. return [0, right_outside];
  1086. }
  1087. // If text fits inside the span
  1088. if (full_span_px_width > width) {
  1089. const distance = span_right - this.trace_view.right;
  1090. const visible_width =
  1091. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  1092. // If the text fits inside the visible portion of the span, anchor it to the right
  1093. // side of the window so that it is visible while the user pans the view
  1094. if (visible_width - TEXT_PADDING >= width) {
  1095. return [1, window_right];
  1096. }
  1097. // If the text doesnt fit inside the visible portion of the span,
  1098. // anchor it to the inside left of the span
  1099. return [1, left_inside];
  1100. }
  1101. return [0, right_outside];
  1102. }
  1103. last_indicator_width = 0;
  1104. draw(options: {list?: number; span_list?: number} = {}) {
  1105. const list_width = options.list ?? this.columns.list.width;
  1106. const span_list_width = options.span_list ?? this.columns.span_list.width;
  1107. this.drawContainers(this.container, {
  1108. list_width,
  1109. span_list_width,
  1110. });
  1111. // 60px error margin. ~52px is roughly the width of 500.00ms, we add a bit more, to be safe.
  1112. const error_margin = 60 * this.span_to_px[0];
  1113. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  1114. const span = this.span_bars[i];
  1115. if (!span) {
  1116. continue;
  1117. }
  1118. const outside_left =
  1119. span.space[0] - this.to_origin + span.space[1] < this.trace_view.x - error_margin;
  1120. const outside_right =
  1121. span.space[0] - this.to_origin - error_margin > this.trace_view.right;
  1122. if (outside_left || outside_right) {
  1123. this.hideSpanBar(this.span_bars[i], this.span_text[i]);
  1124. this.drawSpanArrow(this.span_arrows[i], true, outside_left ? 0 : 1);
  1125. continue;
  1126. }
  1127. this.drawSpanBar(this.span_bars[i]);
  1128. this.drawSpanText(this.span_text[i], this.columns.list.column_nodes[i]);
  1129. this.drawSpanArrow(this.span_arrows[i], false, 0);
  1130. }
  1131. this.drawInvisibleBars();
  1132. let start_indicator = 0;
  1133. let end_indicator = this.indicators.length;
  1134. while (start_indicator < this.indicators.length - 1) {
  1135. const indicator = this.indicators[start_indicator];
  1136. if (!indicator?.indicator) {
  1137. start_indicator++;
  1138. continue;
  1139. }
  1140. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1141. start_indicator++;
  1142. continue;
  1143. }
  1144. break;
  1145. }
  1146. while (end_indicator > start_indicator) {
  1147. const last_indicator = this.indicators[end_indicator - 1];
  1148. if (!last_indicator) {
  1149. end_indicator--;
  1150. continue;
  1151. }
  1152. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1153. end_indicator--;
  1154. continue;
  1155. }
  1156. break;
  1157. }
  1158. start_indicator = Math.max(0, start_indicator - 1);
  1159. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1160. for (let i = 0; i < this.indicators.length; i++) {
  1161. const entry = this.indicators[i];
  1162. if (!entry) {
  1163. continue;
  1164. }
  1165. if (i < start_indicator || i > end_indicator) {
  1166. entry.ref.style.opacity = '0';
  1167. continue;
  1168. }
  1169. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1170. const label = entry.ref.children[0] as HTMLElement | undefined;
  1171. const indicator_max = this.trace_physical_space.width + 1;
  1172. const indicator_min = -1;
  1173. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1174. const clamped_transform = clamp(transform, -1, indicator_max);
  1175. if (label_width === undefined) {
  1176. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1177. continue;
  1178. }
  1179. if (label) {
  1180. const PADDING = 2;
  1181. const label_window_left = PADDING;
  1182. const label_window_right = -label_width - PADDING;
  1183. if (transform < -1) {
  1184. label.style.transform = `translateX(${label_window_left}px)`;
  1185. } else if (transform >= indicator_max) {
  1186. label.style.transform = `translateX(${label_window_right}px)`;
  1187. } else {
  1188. const space_left = transform - PADDING - label_width / 2;
  1189. const space_right = transform + label_width / 2;
  1190. if (space_left < 0) {
  1191. const left = -label_width / 2 + Math.abs(space_left);
  1192. label.style.transform = `translateX(${left - 1}px)`;
  1193. } else if (space_right > this.trace_physical_space.width) {
  1194. const right =
  1195. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1196. label.style.transform = `translateX(${right}px)`;
  1197. } else {
  1198. label.style.transform = `translateX(${-label_width / 2}px)`;
  1199. }
  1200. }
  1201. }
  1202. entry.ref.style.opacity = '1';
  1203. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1204. }
  1205. this.drawVerticalIndicators();
  1206. this.drawTimelineIntervals();
  1207. }
  1208. // DRAW METHODS
  1209. hideSpanBar(span_bar: this['span_bars'][0], span_text: this['span_text'][0]) {
  1210. span_bar && (span_bar.ref.style.transform = 'translate(-10000px, -10000px)');
  1211. span_text && (span_text.ref.style.transform = 'translate(-10000px, -10000px)');
  1212. }
  1213. hideSpanArrow(span_arrow: this['span_arrows'][0]) {
  1214. if (!span_arrow) return;
  1215. span_arrow.ref.className = 'TraceArrow';
  1216. span_arrow.visible = false;
  1217. span_arrow.ref.style.opacity = '0';
  1218. }
  1219. drawSpanBar(span_bar: this['span_bars'][0]) {
  1220. if (!span_bar) return;
  1221. const span_transform = this.computeSpanCSSMatrixTransform(span_bar?.space);
  1222. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1223. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1224. span_bar.ref.style.setProperty(
  1225. '--inverse-span-scale',
  1226. // @ts-expect-error we set number value type on purpose
  1227. isNaN(inverseScale) ? 1 : inverseScale
  1228. );
  1229. }
  1230. drawSpanText(span_text: this['span_text'][0], node: TraceTreeNode<any> | undefined) {
  1231. if (!span_text) return;
  1232. const [inside, text_transform] = this.computeSpanTextPlacement(
  1233. node!,
  1234. span_text.space,
  1235. span_text.text
  1236. );
  1237. if (text_transform === null) {
  1238. return;
  1239. }
  1240. span_text.ref.style.color = inside ? 'white' : '';
  1241. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1242. }
  1243. drawSpanArrow(span_arrow: this['span_arrows'][0], visible: boolean, position: 0 | 1) {
  1244. if (!span_arrow) return;
  1245. if (visible !== span_arrow.visible) {
  1246. span_arrow.visible = visible;
  1247. span_arrow.position = position;
  1248. if (visible) {
  1249. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1250. } else {
  1251. span_arrow.ref.className = 'TraceArrow';
  1252. }
  1253. }
  1254. }
  1255. drawVerticalIndicators() {
  1256. for (const key in this.vertical_indicators) {
  1257. this.drawVerticalIndicator(this.vertical_indicators[key]);
  1258. }
  1259. }
  1260. drawVerticalIndicator(indicator: VerticalIndicator) {
  1261. if (!indicator.ref) {
  1262. return;
  1263. }
  1264. if (indicator.timestamp === undefined) {
  1265. indicator.ref.style.opacity = '0';
  1266. return;
  1267. }
  1268. const placement = this.computeTransformXFromTimestamp(indicator.timestamp);
  1269. indicator.ref.style.opacity = '1';
  1270. indicator.ref.style.transform = `translateX(${placement}px)`;
  1271. }
  1272. drawTimelineInterval(ref: HTMLElement | undefined, index: number) {
  1273. if (!ref) {
  1274. return;
  1275. }
  1276. const interval = this.intervals[index];
  1277. if (interval === undefined) {
  1278. ref.style.opacity = '0';
  1279. return;
  1280. }
  1281. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1282. ref.style.opacity = '1';
  1283. ref.style.transform = `translateX(${placement}px)`;
  1284. const label = ref.children[0] as HTMLElement | undefined;
  1285. const duration = getDuration(interval / 1000, 2, true);
  1286. if (label && label?.textContent !== duration) {
  1287. label.textContent = duration;
  1288. }
  1289. }
  1290. drawTimelineIntervals() {
  1291. if (this.intervals[0] === 0 && this.intervals[1] === 0) {
  1292. this.drawEmptyTimelineIntervals();
  1293. for (let i = 2; i < this.timeline_indicators.length; i++) {
  1294. const indicator = this.timeline_indicators[i];
  1295. if (indicator) {
  1296. indicator.style.opacity = '0';
  1297. }
  1298. }
  1299. return;
  1300. }
  1301. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1302. this.drawTimelineInterval(this.timeline_indicators[i], i);
  1303. }
  1304. }
  1305. // Special case for when the timeline is empty - we want to show the first and last
  1306. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1307. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1308. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1309. drawEmptyTimelineIntervals() {
  1310. const first = this.timeline_indicators[0];
  1311. const last = this.timeline_indicators[1];
  1312. if (first && last) {
  1313. first.style.opacity = '1';
  1314. last.style.opacity = '1';
  1315. first.style.transform = `translateX(0)`;
  1316. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1317. // side of the indicator, we need to offset it by the width of the label to make it look like
  1318. // it is at the end of the timeline
  1319. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1320. const firstLabel = first.children[0] as HTMLElement | undefined;
  1321. if (firstLabel) {
  1322. firstLabel.textContent = '0.00ms';
  1323. }
  1324. const lastLabel = last.children[0] as HTMLElement | undefined;
  1325. const lastLine = last.children[1] as HTMLElement | undefined;
  1326. if (lastLine && lastLabel) {
  1327. lastLabel.textContent = '0.00ms';
  1328. lastLine.style.opacity = '0';
  1329. }
  1330. }
  1331. }
  1332. drawContainers(
  1333. container: HTMLElement | null,
  1334. options: {list_width: number; span_list_width: number}
  1335. ) {
  1336. if (!container) return;
  1337. if (this.last_list_column_width !== options.list_width) {
  1338. container.style.setProperty(
  1339. '--list-column-width',
  1340. // @ts-expect-error we set number value type on purpose
  1341. Math.round(options.list_width * 1000) / 1000
  1342. );
  1343. this.last_list_column_width = options.list_width;
  1344. }
  1345. if (this.last_span_column_width !== options.span_list_width) {
  1346. container.style.setProperty(
  1347. '--span-column-width',
  1348. // @ts-expect-error we set number value type on purpose
  1349. Math.round(options.span_list_width * 1000) / 1000
  1350. );
  1351. this.last_span_column_width = options.span_list_width;
  1352. }
  1353. if (this.indicator_container) {
  1354. const correction =
  1355. (this.scrollbar_width / this.container_physical_space.width) *
  1356. options.span_list_width;
  1357. this.indicator_container.style.transform = `translateX(${-this.scrollbar_width}px)`;
  1358. const new_indicator_container_width = options.span_list_width - correction;
  1359. if (this.last_indicator_width !== new_indicator_container_width) {
  1360. this.indicator_container.style.width = new_indicator_container_width * 100 + '%';
  1361. this.last_indicator_width = new_indicator_container_width;
  1362. }
  1363. }
  1364. const dividerPosition =
  1365. Math.round(
  1366. (options.list_width *
  1367. (this.container_physical_space.width - this.scrollbar_width) -
  1368. DIVIDER_WIDTH / 2 -
  1369. 1) *
  1370. 10
  1371. ) / 10;
  1372. if (this.horizontal_scrollbar_container) {
  1373. this.horizontal_scrollbar_container.style.width =
  1374. (dividerPosition / this.container_physical_space.width) * 100 + '%';
  1375. }
  1376. if (this.divider) {
  1377. this.divider.style.transform = `translate(
  1378. ${dividerPosition}px, 0)`;
  1379. }
  1380. }
  1381. last_list_column_width = 0;
  1382. last_span_column_width = 0;
  1383. drawInvisibleBars() {
  1384. for (let i = 0; i < this.invisible_bars.length; i++) {
  1385. const invisible_bar = this.invisible_bars[i];
  1386. const text = this.span_text[i];
  1387. if (invisible_bar) {
  1388. const span_transform = this.computeSpanCSSMatrixTransform(invisible_bar?.space);
  1389. invisible_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1390. const inverseScale = Math.round((1 / span_transform[0]) * 1e4) / 1e4;
  1391. invisible_bar.ref.style.setProperty(
  1392. '--inverse-span-scale',
  1393. // @ts-expect-error we set number value type on purpose
  1394. isNaN(inverseScale) ? 1 : inverseScale
  1395. );
  1396. }
  1397. if (text) {
  1398. const [inside, text_transform] = this.computeSpanTextPlacement(
  1399. this.columns.list.column_nodes[i],
  1400. text.space,
  1401. text.text
  1402. );
  1403. if (text_transform === null) {
  1404. return;
  1405. }
  1406. text.ref.style.color = inside ? 'white' : '';
  1407. text.ref.style.transform = `translateX(${text_transform}px)`;
  1408. }
  1409. }
  1410. }
  1411. // END DRAW METHODS
  1412. teardown() {
  1413. this.row_measurer.off('max', this.onNewMaxRowWidth);
  1414. if (this.resize_observer) {
  1415. this.resize_observer.disconnect();
  1416. this.resize_observer = null;
  1417. this.container = null;
  1418. }
  1419. }
  1420. }
  1421. // Jest does not implement scroll updates, however since we have the
  1422. // middleware to handle scroll updates, we can dispatch a scroll event ourselves
  1423. function dispatchJestScrollUpdate(container: HTMLElement) {
  1424. if (!container) return;
  1425. if (process.env.NODE_ENV !== 'test') return;
  1426. // since we do not tightly control how browsers handle event dispatching, dispatch it async
  1427. window.requestAnimationFrame(() => {
  1428. container.dispatchEvent(new CustomEvent('scroll'));
  1429. });
  1430. }
  1431. function computeTimelineIntervals(
  1432. view: TraceView,
  1433. targetInterval: number,
  1434. results: (number | undefined)[]
  1435. ): void {
  1436. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  1437. let interval = minInterval;
  1438. if (targetInterval / interval > 5) {
  1439. interval *= 5;
  1440. } else if (targetInterval / interval > 2) {
  1441. interval *= 2;
  1442. }
  1443. let x = Math.ceil(view.x / interval) * interval;
  1444. let idx = -1;
  1445. if (x > 0) {
  1446. x -= interval;
  1447. }
  1448. while (x <= view.right) {
  1449. results[++idx] = x;
  1450. x += interval;
  1451. }
  1452. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  1453. results[++idx] = undefined;
  1454. }
  1455. }
  1456. export class VirtualizedList {
  1457. container: HTMLElement | null = null;
  1458. scrollHeight: number = 0;
  1459. scrollTop: number = 0;
  1460. scrollToRow(index: number, anchor?: ViewManagerScrollAnchor) {
  1461. if (!this.container) {
  1462. return;
  1463. }
  1464. let position = index * 24;
  1465. const top = this.container.scrollTop;
  1466. const height = this.scrollHeight;
  1467. if (anchor === 'top') {
  1468. position = index * 24;
  1469. } else if (anchor === 'center') {
  1470. position = position - height / 2;
  1471. } else if (anchor === 'center if outside') {
  1472. if (position < top) {
  1473. // Element is above the view
  1474. position = position - height / 2;
  1475. } else if (position > top + height) {
  1476. // Element below the view
  1477. position = position - height / 2;
  1478. } else {
  1479. // Element is inside the view
  1480. return;
  1481. }
  1482. } else {
  1483. // If no anchor is provided, we default to 'auto'
  1484. if (position < top) {
  1485. position = position;
  1486. } else if (position > top + height) {
  1487. position = index * 24 - height + 24;
  1488. } else {
  1489. return;
  1490. }
  1491. }
  1492. this.container.scrollTop = position;
  1493. dispatchJestScrollUpdate(this.container);
  1494. }
  1495. }