virtualizedViewManager.tsx 53 KB

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