virtualizedViewManager.tsx 55 KB

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