virtualizedViewManager.tsx 54 KB

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