virtualizedViewManager.tsx 53 KB

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