virtualizedViewManager.tsx 56 KB

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