virtualizedViewManager.tsx 54 KB

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