virtualizedViewManager.tsx 54 KB

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