virtualizedViewManager.tsx 55 KB

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