virtualizedViewManager.tsx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. import type {List} from 'react-virtualized';
  2. import * as Sentry from '@sentry/react';
  3. import {mat3, vec2} from 'gl-matrix';
  4. import type {Client} from 'sentry/api';
  5. import type {Organization} from 'sentry/types';
  6. import clamp from 'sentry/utils/number/clamp';
  7. import {lightTheme as theme} from 'sentry/utils/theme';
  8. import {
  9. isAutogroupedNode,
  10. isMissingInstrumentationNode,
  11. isParentAutogroupedNode,
  12. isSiblingAutogroupedNode,
  13. isSpanNode,
  14. isTraceErrorNode,
  15. isTransactionNode,
  16. } from 'sentry/views/performance/newTraceDetails/guards';
  17. import {
  18. type TraceTree,
  19. TraceTreeNode,
  20. } from 'sentry/views/performance/newTraceDetails/traceTree';
  21. const DIVIDER_WIDTH = 6;
  22. function easeOutSine(x: number): number {
  23. return Math.sin((x * Math.PI) / 2);
  24. }
  25. function onPreventBackForwardNavigation(event: WheelEvent) {
  26. if (event.deltaX !== 0) {
  27. event.preventDefault();
  28. }
  29. }
  30. type ViewColumn = {
  31. column_nodes: TraceTreeNode<TraceTree.NodeValue>[];
  32. column_refs: (HTMLElement | undefined)[];
  33. translate: [number, number];
  34. width: number;
  35. };
  36. class View {
  37. public x: number;
  38. public y: number;
  39. public width: number;
  40. public height: number;
  41. constructor(x: number, y: number, width: number, height: number) {
  42. this.x = x;
  43. this.y = y;
  44. this.width = width;
  45. this.height = height;
  46. }
  47. static From(view: View): View {
  48. return new View(view.x, view.y, view.width, view.height);
  49. }
  50. static Empty(): View {
  51. return new View(0, 0, 1000, 1);
  52. }
  53. serialize() {
  54. return [this.x, this.y, this.width, this.height];
  55. }
  56. between(to: View): mat3 {
  57. return mat3.fromValues(
  58. to.width / this.width,
  59. 0,
  60. 0,
  61. to.height / this.height,
  62. 0,
  63. 0,
  64. to.x - this.x * (to.width / this.width),
  65. to.y - this.y * (to.height / this.height),
  66. 1
  67. );
  68. }
  69. transform(mat: mat3): [number, number, number, number] {
  70. const x = this.x * mat[0] + this.y * mat[3] + mat[6];
  71. const y = this.x * mat[1] + this.y * mat[4] + mat[7];
  72. const width = this.width * mat[0] + this.height * mat[3];
  73. const height = this.width * mat[1] + this.height * mat[4];
  74. return [x, y, width, height];
  75. }
  76. get center() {
  77. return this.x + this.width / 2;
  78. }
  79. get left() {
  80. return this.x;
  81. }
  82. get right() {
  83. return this.x + this.width;
  84. }
  85. get top() {
  86. return this.y;
  87. }
  88. get bottom() {
  89. return this.y + this.height;
  90. }
  91. }
  92. /**
  93. * Tracks the state of the virtualized view and manages the resizing of the columns.
  94. * Children components should call the appropriate register*Ref methods to register their
  95. * HTML elements.
  96. */
  97. export class VirtualizedViewManager {
  98. // Represents the space of the entire trace, for example
  99. // a trace starting at 0 and ending at 1000 would have a space of [0, 1000]
  100. to_origin: number = 0;
  101. trace_space: View = View.Empty();
  102. // The view defines what the user is currently looking at, it is a subset
  103. // of the trace space. For example, if the user is currently looking at the
  104. // trace from 500 to 1000, the view would be represented by [x, width] = [500, 500]
  105. trace_view: View = View.Empty();
  106. // Represents the pixel space of the entire trace - this is the container
  107. // that we render to. For example, if the container is 1000px wide, the
  108. // pixel space would be [0, 1000]
  109. trace_physical_space: View = View.Empty();
  110. container_physical_space: View = View.Empty();
  111. row_measurer: DOMWidthMeasurer<TraceTreeNode<TraceTree.NodeValue>> =
  112. new DOMWidthMeasurer();
  113. indicator_label_measurer: DOMWidthMeasurer<TraceTree['indicators'][0]> =
  114. new DOMWidthMeasurer();
  115. text_measurer: TextMeasurer = new TextMeasurer();
  116. resize_observer: ResizeObserver | null = null;
  117. list: List | null = null;
  118. // HTML refs that we need to keep track of such
  119. // that rendering can be done programmatically
  120. divider: HTMLElement | null = null;
  121. container: HTMLElement | null = null;
  122. indicator_container: HTMLElement | null = null;
  123. indicators: ({indicator: TraceTree['indicators'][0]; ref: HTMLElement} | undefined)[] =
  124. [];
  125. span_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  126. span_text: ({ref: HTMLElement; space: [number, number]; text: string} | undefined)[] =
  127. [];
  128. // Holds the span to px matrix so we dont keep recalculating it
  129. span_to_px: mat3 = mat3.create();
  130. row_depth_padding: number = 22;
  131. // Column configuration
  132. columns: {
  133. list: ViewColumn;
  134. span_list: ViewColumn;
  135. };
  136. constructor(columns: {
  137. list: Pick<ViewColumn, 'width'>;
  138. span_list: Pick<ViewColumn, 'width'>;
  139. }) {
  140. this.columns = {
  141. list: {...columns.list, column_nodes: [], column_refs: [], translate: [0, 0]},
  142. span_list: {
  143. ...columns.span_list,
  144. column_nodes: [],
  145. column_refs: [],
  146. translate: [0, 0],
  147. },
  148. };
  149. this.onDividerMouseDown = this.onDividerMouseDown.bind(this);
  150. this.onDividerMouseUp = this.onDividerMouseUp.bind(this);
  151. this.onDividerMouseMove = this.onDividerMouseMove.bind(this);
  152. this.onSyncedScrollbarScroll = this.onSyncedScrollbarScroll.bind(this);
  153. this.onWheelZoom = this.onWheelZoom.bind(this);
  154. }
  155. initializeTraceSpace(space: [x: number, y: number, width: number, height: number]) {
  156. this.to_origin = space[0];
  157. this.trace_space = new View(0, 0, space[2], space[3]);
  158. this.trace_view = new View(0, 0, space[2], space[3]);
  159. this.recomputeSpanToPxMatrix();
  160. }
  161. initializePhysicalSpace(width: number, height: number) {
  162. this.container_physical_space = new View(0, 0, width, height);
  163. this.trace_physical_space = new View(
  164. 0,
  165. 0,
  166. width * this.columns.span_list.width,
  167. height
  168. );
  169. this.recomputeSpanToPxMatrix();
  170. }
  171. onContainerRef(container: HTMLElement | null) {
  172. if (container) {
  173. this.initialize(container);
  174. } else {
  175. this.teardown();
  176. }
  177. }
  178. dividerStartVec: [number, number] | null = null;
  179. previousDividerClientVec: [number, number] | null = null;
  180. onDividerMouseDown(event: MouseEvent) {
  181. if (!this.container) {
  182. return;
  183. }
  184. this.dividerStartVec = [event.clientX, event.clientY];
  185. this.previousDividerClientVec = [event.clientX, event.clientY];
  186. this.container.style.userSelect = 'none';
  187. this.container.addEventListener('mouseup', this.onDividerMouseUp, {passive: true});
  188. this.container.addEventListener('mousemove', this.onDividerMouseMove, {
  189. passive: true,
  190. });
  191. }
  192. onDividerMouseUp(event: MouseEvent) {
  193. if (!this.container || !this.dividerStartVec) {
  194. return;
  195. }
  196. const distance = event.clientX - this.dividerStartVec[0];
  197. const distancePercentage = distance / this.container_physical_space.width;
  198. this.columns.list.width = this.columns.list.width + distancePercentage;
  199. this.columns.span_list.width = this.columns.span_list.width - distancePercentage;
  200. this.container.style.userSelect = 'auto';
  201. this.dividerStartVec = null;
  202. this.previousDividerClientVec = null;
  203. this.container.removeEventListener('mouseup', this.onDividerMouseUp);
  204. this.container.removeEventListener('mousemove', this.onDividerMouseMove);
  205. }
  206. onDividerMouseMove(event: MouseEvent) {
  207. if (!this.dividerStartVec || !this.divider || !this.previousDividerClientVec) {
  208. return;
  209. }
  210. const distance = event.clientX - this.dividerStartVec[0];
  211. const distancePercentage = distance / this.container_physical_space.width;
  212. this.trace_physical_space.width =
  213. (this.columns.span_list.width - distancePercentage) *
  214. this.container_physical_space.width;
  215. const physical_distance = this.previousDividerClientVec[0] - event.clientX;
  216. const config_distance_pct = physical_distance / this.trace_physical_space.width;
  217. const config_distance = this.trace_view.width * config_distance_pct;
  218. this.setTraceView({
  219. x: this.trace_view.x - config_distance,
  220. width: this.trace_view.width + config_distance,
  221. });
  222. this.draw({
  223. list: this.columns.list.width + distancePercentage,
  224. span_list: this.columns.span_list.width - distancePercentage,
  225. });
  226. this.previousDividerClientVec = [event.clientX, event.clientY];
  227. }
  228. registerList(list: List | null) {
  229. this.list = list;
  230. }
  231. registerIndicatorContainerRef(ref: HTMLElement | null) {
  232. if (ref) {
  233. ref.style.width = this.columns.span_list.width * 100 + '%';
  234. }
  235. this.indicator_container = ref;
  236. }
  237. registerDividerRef(ref: HTMLElement | null) {
  238. if (!ref) {
  239. if (this.divider) {
  240. this.divider.removeEventListener('mousedown', this.onDividerMouseDown);
  241. }
  242. this.divider = null;
  243. return;
  244. }
  245. this.divider = ref;
  246. this.divider.style.width = `${DIVIDER_WIDTH}px`;
  247. ref.addEventListener('mousedown', this.onDividerMouseDown, {passive: true});
  248. }
  249. registerSpanBarRef(ref: HTMLElement | null, space: [number, number], index: number) {
  250. this.span_bars[index] = ref ? {ref, space} : undefined;
  251. }
  252. registerSpanBarTextRef(
  253. ref: HTMLElement | null,
  254. text: string,
  255. space: [number, number],
  256. index: number
  257. ) {
  258. this.span_text[index] = ref ? {ref, text, space} : undefined;
  259. }
  260. registerColumnRef(
  261. column: string,
  262. ref: HTMLElement | null,
  263. index: number,
  264. node: TraceTreeNode<any>
  265. ) {
  266. if (!this.columns[column]) {
  267. throw new TypeError('Invalid column');
  268. }
  269. if (typeof index !== 'number' || isNaN(index)) {
  270. throw new TypeError('Invalid index');
  271. }
  272. if (column === 'list') {
  273. const element = this.columns[column].column_refs[index];
  274. if (ref === undefined && element) {
  275. element.removeEventListener('wheel', this.onSyncedScrollbarScroll);
  276. } else if (ref) {
  277. const scrollableElement = ref.children[0];
  278. if (scrollableElement) {
  279. this.row_measurer.measure(node, scrollableElement as HTMLElement);
  280. ref.addEventListener('wheel', this.onSyncedScrollbarScroll, {passive: true});
  281. }
  282. }
  283. }
  284. if (column === 'span_list') {
  285. const element = this.columns[column].column_refs[index];
  286. if (ref === undefined && element) {
  287. element.removeEventListener('wheel', this.onWheelZoom);
  288. } else if (ref) {
  289. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  290. }
  291. }
  292. this.columns[column].column_refs[index] = ref ?? undefined;
  293. this.columns[column].column_nodes[index] = node ?? undefined;
  294. }
  295. registerIndicatorRef(
  296. ref: HTMLElement | null,
  297. index: number,
  298. indicator: TraceTree['indicators'][0]
  299. ) {
  300. if (!ref) {
  301. const element = this.indicators[index]?.ref;
  302. if (element) {
  303. element.removeEventListener('wheel', this.onWheelZoom);
  304. }
  305. this.indicators[index] = undefined;
  306. } else {
  307. this.indicators[index] = {ref, indicator};
  308. }
  309. if (ref) {
  310. const label = ref.children[0] as HTMLElement | undefined;
  311. if (label) {
  312. this.indicator_label_measurer.measure(indicator, label);
  313. }
  314. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  315. ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(
  316. indicator.start
  317. )}px)`;
  318. }
  319. }
  320. getConfigSpaceCursor(cursor: {x: number; y: number}): [number, number] {
  321. const left_percentage = cursor.x / this.trace_physical_space.width;
  322. const left_view = left_percentage * this.trace_view.width;
  323. return [this.trace_view.x + left_view, 0];
  324. }
  325. onWheelZoom(event: WheelEvent) {
  326. if (event.metaKey) {
  327. event.preventDefault();
  328. if (!this.onWheelEndRaf) {
  329. this.onWheelStart();
  330. this.enqueueOnWheelEndRaf();
  331. return;
  332. }
  333. const scale = 1 - event.deltaY * 0.01 * -1;
  334. const configSpaceCursor = this.getConfigSpaceCursor({
  335. x: event.offsetX,
  336. y: event.offsetY,
  337. });
  338. const center = vec2.fromValues(configSpaceCursor[0], 0);
  339. const centerScaleMatrix = mat3.create();
  340. mat3.fromTranslation(centerScaleMatrix, center);
  341. mat3.scale(centerScaleMatrix, centerScaleMatrix, vec2.fromValues(scale, 1));
  342. mat3.translate(
  343. centerScaleMatrix,
  344. centerScaleMatrix,
  345. vec2.fromValues(-center[0], 0)
  346. );
  347. const newView = this.trace_view.transform(centerScaleMatrix);
  348. this.setTraceView({
  349. x: newView[0],
  350. width: newView[2],
  351. });
  352. this.draw();
  353. } else {
  354. const physical_delta_pct = event.deltaX / this.trace_physical_space.width;
  355. const view_delta = physical_delta_pct * this.trace_view.width;
  356. this.setTraceView({
  357. x: this.trace_view.x + view_delta,
  358. });
  359. this.draw();
  360. }
  361. }
  362. zoomIntoSpaceRaf: number | null = null;
  363. onZoomIntoSpace(space: [number, number]) {
  364. const distance_x = space[0] - this.to_origin - this.trace_view.x;
  365. const distance_width = this.trace_view.width - space[1];
  366. const start_x = this.trace_view.x;
  367. const start_width = this.trace_view.width;
  368. const start = performance.now();
  369. const rafCallback = (now: number) => {
  370. const elapsed = now - start;
  371. const progress = elapsed / 300;
  372. const eased = easeOutSine(progress);
  373. const x = start_x + distance_x * eased;
  374. const width = start_width - distance_width * eased;
  375. this.setTraceView({x, width});
  376. this.draw();
  377. if (progress < 1) {
  378. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  379. } else {
  380. this.zoomIntoSpaceRaf = null;
  381. this.setTraceView({x: space[0] - this.to_origin, width: space[1]});
  382. this.draw();
  383. }
  384. };
  385. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  386. }
  387. onWheelEndRaf: number | null = null;
  388. enqueueOnWheelEndRaf() {
  389. if (this.onWheelEndRaf !== null) {
  390. window.cancelAnimationFrame(this.onWheelEndRaf);
  391. }
  392. const start = performance.now();
  393. const rafCallback = (now: number) => {
  394. const elapsed = now - start;
  395. if (elapsed > 16) {
  396. this.onWheelEnd();
  397. } else {
  398. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  399. }
  400. };
  401. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  402. }
  403. onWheelStart() {
  404. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  405. const span_list = this.columns.span_list.column_refs[i];
  406. if (span_list?.children?.[0]) {
  407. (span_list.children[0] as HTMLElement).style.pointerEvents = 'none';
  408. }
  409. const span_text = this.span_text[i];
  410. if (span_text) {
  411. span_text.ref.style.pointerEvents = 'none';
  412. }
  413. }
  414. for (let i = 0; i < this.indicators.length; i++) {
  415. const indicator = this.indicators[i];
  416. if (indicator?.ref) {
  417. indicator.ref.style.pointerEvents = 'none';
  418. }
  419. }
  420. }
  421. onWheelEnd() {
  422. this.onWheelEndRaf = null;
  423. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  424. const span_list = this.columns.span_list.column_refs[i];
  425. if (span_list?.children?.[0]) {
  426. (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto';
  427. }
  428. const span_text = this.span_text[i];
  429. if (span_text) {
  430. span_text.ref.style.pointerEvents = 'auto';
  431. }
  432. }
  433. for (let i = 0; i < this.indicators.length; i++) {
  434. const indicator = this.indicators[i];
  435. if (indicator?.ref) {
  436. indicator.ref.style.pointerEvents = 'auto';
  437. }
  438. }
  439. }
  440. setTraceView(view: {width?: number; x?: number}) {
  441. const x = view.x ?? this.trace_view.x;
  442. const width = view.width ?? this.trace_view.width;
  443. this.trace_view.x = clamp(x, 0, this.trace_space.width - width);
  444. this.trace_view.width = clamp(width, 0, this.trace_space.width - this.trace_view.x);
  445. this.recomputeSpanToPxMatrix();
  446. }
  447. scrollSyncRaf: number | null = null;
  448. onSyncedScrollbarScroll(event: WheelEvent) {
  449. if (this.bringRowIntoViewAnimation !== null) {
  450. window.cancelAnimationFrame(this.bringRowIntoViewAnimation);
  451. this.bringRowIntoViewAnimation = null;
  452. }
  453. this.enqueueOnScrollEndOutOfBoundsCheck();
  454. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  455. this.columns.list.translate[0] = clamp(
  456. this.columns.list.translate[0] - event.deltaX,
  457. -(this.row_measurer.max - columnWidth + 16), // 16px margin so we dont scroll right to the last px
  458. 0
  459. );
  460. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  461. const list = this.columns.list.column_refs[i];
  462. if (list?.children?.[0]) {
  463. (list.children[0] as HTMLElement).style.transform =
  464. `translateX(${this.columns.list.translate[0]}px)`;
  465. }
  466. }
  467. // Eventually sync the column translation to the container
  468. if (this.scrollSyncRaf) {
  469. window.cancelAnimationFrame(this.scrollSyncRaf);
  470. }
  471. this.scrollSyncRaf = window.requestAnimationFrame(() => {
  472. // @TODO if user is outside of the container, scroll the container to the left
  473. this.container?.style.setProperty(
  474. '--column-translate-x',
  475. this.columns.list.translate[0] + 'px'
  476. );
  477. });
  478. }
  479. scrollEndSyncRaf: number | null = null;
  480. enqueueOnScrollEndOutOfBoundsCheck() {
  481. if (this.scrollEndSyncRaf !== null) {
  482. window.cancelAnimationFrame(this.scrollEndSyncRaf);
  483. }
  484. const start = performance.now();
  485. const rafCallback = (now: number) => {
  486. const elapsed = now - start;
  487. if (elapsed > 300) {
  488. this.onScrollEndOutOfBoundsCheck();
  489. } else {
  490. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  491. }
  492. };
  493. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  494. }
  495. onScrollEndOutOfBoundsCheck() {
  496. this.scrollEndSyncRaf = null;
  497. const translation = this.columns.list.translate[0];
  498. let min = Number.POSITIVE_INFINITY;
  499. let max = Number.NEGATIVE_INFINITY;
  500. let innerMostNode: TraceTreeNode<any> | undefined;
  501. const offset = this.list?.Grid?.props.overscanRowCount ?? 0;
  502. const renderCount = this.columns.span_list.column_refs.length;
  503. for (let i = offset + 1; i < renderCount - offset; i++) {
  504. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  505. if (width === undefined) {
  506. // this is unlikely to happen, but we should trigger a sync measure event if it does
  507. continue;
  508. }
  509. min = Math.min(min, width);
  510. max = Math.max(max, width);
  511. innerMostNode =
  512. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  513. ? this.columns.list.column_nodes[i]
  514. : innerMostNode;
  515. }
  516. if (innerMostNode) {
  517. if (translation + max < 0) {
  518. this.scrollRowIntoViewHorizontally(innerMostNode);
  519. } else if (
  520. translation + innerMostNode.depth * this.row_depth_padding >
  521. this.columns.list.width * this.container_physical_space.width
  522. ) {
  523. this.scrollRowIntoViewHorizontally(innerMostNode);
  524. }
  525. }
  526. }
  527. scrollRowIntoViewHorizontally(node: TraceTreeNode<any>, duration: number = 600) {
  528. const VISUAL_OFFSET = this.row_depth_padding / 2;
  529. const target = Math.min(-node.depth * this.row_depth_padding + VISUAL_OFFSET, 0);
  530. this.animateScrollColumnTo(target, duration);
  531. }
  532. bringRowIntoViewAnimation: number | null = null;
  533. animateScrollColumnTo(x: number, duration: number) {
  534. const start = performance.now();
  535. const startPosition = this.columns.list.translate[0];
  536. const distance = x - startPosition;
  537. const animate = (now: number) => {
  538. const elapsed = now - start;
  539. const progress = duration > 0 ? elapsed / duration : 1;
  540. const eased = easeOutSine(progress);
  541. const pos = startPosition + distance * eased;
  542. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  543. const list = this.columns.list.column_refs[i];
  544. if (list?.children?.[0]) {
  545. (list.children[0] as HTMLElement).style.transform = `translateX(${pos}px)`;
  546. }
  547. }
  548. if (progress < 1) {
  549. this.columns.list.translate[0] = pos;
  550. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  551. } else {
  552. this.columns.list.translate[0] = x;
  553. }
  554. };
  555. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  556. }
  557. initialize(container: HTMLElement) {
  558. if (this.container !== container && this.resize_observer !== null) {
  559. this.teardown();
  560. }
  561. this.container = container;
  562. this.container.addEventListener('wheel', onPreventBackForwardNavigation, {
  563. passive: false,
  564. });
  565. this.resize_observer = new ResizeObserver(entries => {
  566. const entry = entries[0];
  567. if (!entry) {
  568. throw new Error('ResizeObserver entry is undefined');
  569. }
  570. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  571. this.draw();
  572. });
  573. this.resize_observer.observe(container);
  574. }
  575. recomputeSpanToPxMatrix() {
  576. const traceViewToSpace = this.trace_space.between(this.trace_view);
  577. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  578. this.span_to_px = mat3.multiply(
  579. this.span_to_px,
  580. traceViewToSpace,
  581. tracePhysicalToView
  582. );
  583. }
  584. computeSpanCSSMatrixTransform(
  585. space: [number, number]
  586. ): [number, number, number, number, number, number] {
  587. const scale = space[1] / this.trace_view.width;
  588. return [
  589. Math.max(scale, (1 * this.span_to_px[0]) / this.trace_view.width),
  590. 0,
  591. 0,
  592. 1,
  593. (space[0] - this.to_origin) / this.span_to_px[0] -
  594. this.trace_view.x / this.span_to_px[0],
  595. 0,
  596. ];
  597. }
  598. scrollToPath(
  599. tree: TraceTree,
  600. scrollQueue: TraceTree.NodePath[],
  601. rerender: () => void,
  602. {api, organization}: {api: Client; organization: Organization}
  603. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  604. const segments = [...scrollQueue];
  605. const list = this.list;
  606. if (!list) {
  607. return Promise.resolve(null);
  608. }
  609. if (segments.length === 1 && segments[0] === 'trace:root') {
  610. rerender();
  611. list.scrollToRow(0);
  612. return Promise.resolve({index: 0, node: tree.root.children[0]});
  613. }
  614. // Keep parent reference as we traverse the tree so that we can only
  615. // perform searching in the current level and not the entire tree
  616. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  617. const scrollToRow = async (): Promise<{
  618. index: number;
  619. node: TraceTreeNode<TraceTree.NodeValue>;
  620. } | null | null> => {
  621. const path = segments.pop();
  622. const current = findInTreeFromSegment(parent, path!);
  623. if (!current) {
  624. Sentry.captureMessage('Failed to scroll to node in trace tree');
  625. return null;
  626. }
  627. // Reassing the parent to the current node
  628. parent = current;
  629. if (isTransactionNode(current)) {
  630. const nextSegment = segments[segments.length - 1];
  631. if (
  632. nextSegment?.startsWith('span:') ||
  633. nextSegment?.startsWith('ag:') ||
  634. nextSegment?.startsWith('ms:')
  635. ) {
  636. await tree.zoomIn(current, true, {
  637. api,
  638. organization,
  639. });
  640. return scrollToRow();
  641. }
  642. }
  643. if (isAutogroupedNode(current) && segments.length > 0) {
  644. tree.expand(current, true);
  645. return scrollToRow();
  646. }
  647. if (segments.length > 0) {
  648. return scrollToRow();
  649. }
  650. // We are at the last path segment (the node that the user clicked on)
  651. // and we should scroll the view to this node.
  652. const index = tree.list.findIndex(node => node === current);
  653. if (index === -1) {
  654. throw new Error("Couldn't find node in list");
  655. }
  656. rerender();
  657. list.scrollToRow(index);
  658. return {index, node: current};
  659. };
  660. return scrollToRow();
  661. }
  662. computeTransformXFromTimestamp(timestamp: number): number {
  663. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  664. }
  665. computeSpanTextPlacement(span_space: [number, number], text: string): [number, number] {
  666. const TEXT_PADDING = 2;
  667. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  668. const width = this.text_measurer.measure(text);
  669. // precomput all anchor points aot, so we make the control flow more readable.
  670. // this wastes some cycles, but it's not a big deal as computers are fast when
  671. // it comes to simple arithmetic.
  672. const right_outside =
  673. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  674. const right_inside =
  675. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  676. width -
  677. TEXT_PADDING;
  678. const left_outside =
  679. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  680. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  681. const window_right =
  682. this.computeTransformXFromTimestamp(
  683. this.to_origin + this.trace_view.left + this.trace_view.width
  684. ) -
  685. width -
  686. TEXT_PADDING;
  687. const window_left =
  688. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  689. TEXT_PADDING;
  690. const view_left = this.trace_view.x;
  691. const view_right = view_left + this.trace_view.width;
  692. const span_left = span_space[0] - this.to_origin;
  693. const span_right = span_left + span_space[1];
  694. const space_right = view_right - span_right;
  695. const space_left = span_left - view_left;
  696. // Span is completely outside of the view on the left side
  697. if (span_right < this.trace_view.x) {
  698. return anchor_left ? [1, right_inside] : [0, right_outside];
  699. }
  700. // Span is completely outside of the view on the right side
  701. if (span_left > this.trace_view.right) {
  702. return anchor_left ? [0, left_outside] : [1, left_inside];
  703. }
  704. // Span "spans" the entire view
  705. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  706. return anchor_left ? [1, window_left] : [1, window_right];
  707. }
  708. const full_span_px_width = span_space[1] / this.span_to_px[0];
  709. if (anchor_left) {
  710. // While we have space on the left, place the text there
  711. if (space_left > 0) {
  712. return [0, left_outside];
  713. }
  714. const distance = span_right - this.trace_view.left;
  715. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  716. // If the text fits inside the visible portion of the span, anchor it to the left
  717. // side of the window so that it is visible while the user pans the view
  718. if (visible_width - TEXT_PADDING >= width) {
  719. return [1, window_left];
  720. }
  721. // If the text doesnt fit inside the visible portion of the span,
  722. // anchor it to the inside right place in the span.
  723. return [1, right_inside];
  724. }
  725. // While we have space on the right, place the text there
  726. if (space_right > 0) {
  727. return [0, right_outside];
  728. }
  729. // If text fits inside the span
  730. if (full_span_px_width > width) {
  731. const distance = span_right - this.trace_view.right;
  732. const visible_width =
  733. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  734. // If the text fits inside the visible portion of the span, anchor it to the right
  735. // side of the window so that it is visible while the user pans the view
  736. if (visible_width - TEXT_PADDING >= width) {
  737. return [1, window_right];
  738. }
  739. // If the text doesnt fit inside the visible portion of the span,
  740. // anchor it to the inside left of the span
  741. return [1, left_inside];
  742. }
  743. return [0, right_outside];
  744. }
  745. draw(options: {list?: number; span_list?: number} = {}) {
  746. const list_width = options.list ?? this.columns.list.width;
  747. const span_list_width = options.span_list ?? this.columns.span_list.width;
  748. if (this.divider) {
  749. this.divider.style.transform = `translateX(${
  750. list_width * this.container_physical_space.width - DIVIDER_WIDTH / 2 - 1
  751. }px)`;
  752. }
  753. if (this.indicator_container) {
  754. this.indicator_container.style.width = span_list_width * 100 + '%';
  755. }
  756. const listWidth = list_width * 100 + '%';
  757. const spanWidth = span_list_width * 100 + '%';
  758. // JavaScript "arrays" are nice in the sense that they are really just dicts,
  759. // allowing us to store negative indices. This sometimes happens as the list
  760. // virtualizes the rows and we end up with a negative index as they are being
  761. // rendered off screen.
  762. const overscroll = this.list?.props.overscanRowCount ?? 0;
  763. const start = -overscroll;
  764. const end = this.columns.list.column_refs.length + overscroll;
  765. for (let i = start; i < end; i++) {
  766. while (this.span_bars[i] === undefined && i < end) i++;
  767. const list = this.columns.list.column_refs[i];
  768. if (list) list.style.width = listWidth;
  769. const span = this.columns.span_list.column_refs[i];
  770. if (span) span.style.width = spanWidth;
  771. const span_bar = this.span_bars[i];
  772. if (span_bar) {
  773. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  774. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  775. }
  776. const span_text = this.span_text[i];
  777. if (span_text) {
  778. const [inside, text_transform] = this.computeSpanTextPlacement(
  779. span_text.space,
  780. span_text.text
  781. );
  782. if (text_transform === null) {
  783. continue;
  784. }
  785. span_text.ref.style.color = inside ? 'white' : '';
  786. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  787. }
  788. }
  789. let start_indicator = 0;
  790. let end_indicator = this.indicators.length;
  791. while (start_indicator < this.indicators.length - 1) {
  792. const indicator = this.indicators[start_indicator];
  793. if (!indicator?.indicator) {
  794. start_indicator++;
  795. continue;
  796. }
  797. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  798. start_indicator++;
  799. continue;
  800. }
  801. break;
  802. }
  803. while (end_indicator > start_indicator) {
  804. const last_indicator = this.indicators[end_indicator - 1];
  805. if (!last_indicator) {
  806. end_indicator--;
  807. continue;
  808. }
  809. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  810. end_indicator--;
  811. continue;
  812. }
  813. break;
  814. }
  815. start_indicator = Math.max(0, start_indicator - 1);
  816. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  817. for (let i = 0; i < this.indicators.length; i++) {
  818. const entry = this.indicators[i];
  819. if (!entry) {
  820. continue;
  821. }
  822. if (i < start_indicator || i > end_indicator) {
  823. entry.ref.style.opacity = '0';
  824. continue;
  825. }
  826. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  827. const label = entry.ref.children[0] as HTMLElement | undefined;
  828. const indicator_max = this.trace_physical_space.width + 1;
  829. const indicator_min = -1;
  830. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  831. const clamped_transform = clamp(transform, -1, indicator_max);
  832. if (label_width === undefined) {
  833. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  834. continue;
  835. }
  836. if (label) {
  837. const PADDING = 2;
  838. const label_window_left = PADDING;
  839. const label_window_right = -label_width - PADDING;
  840. if (transform < -1) {
  841. label.style.transform = `translateX(${label_window_left}px)`;
  842. } else if (transform >= indicator_max) {
  843. label.style.transform = `translateX(${label_window_right}px)`;
  844. } else {
  845. const space_left = transform - PADDING - label_width / 2;
  846. const space_right = transform + label_width / 2;
  847. if (space_left < 0) {
  848. const left = -label_width / 2 + Math.abs(space_left);
  849. label.style.transform = `translateX(${left - 1}px)`;
  850. } else if (space_right > this.trace_physical_space.width) {
  851. const right =
  852. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  853. label.style.transform = `translateX(${right}px)`;
  854. } else {
  855. label.style.transform = `translateX(${-label_width / 2}px)`;
  856. }
  857. }
  858. }
  859. entry.ref.style.opacity = '1';
  860. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  861. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  862. }
  863. }
  864. teardown() {
  865. if (this.container) {
  866. this.container.removeEventListener('wheel', onPreventBackForwardNavigation);
  867. }
  868. if (this.resize_observer) {
  869. this.resize_observer.disconnect();
  870. }
  871. }
  872. }
  873. // The backing cache should be a proper LRU cache,
  874. // so we dont end up storing an infinite amount of elements
  875. class DOMWidthMeasurer<T> {
  876. cache: Map<T, number> = new Map();
  877. elements: HTMLElement[] = [];
  878. queue: [T, HTMLElement][] = [];
  879. drainRaf: number | null = null;
  880. max: number = 0;
  881. constructor() {
  882. this.drain = this.drain.bind(this);
  883. }
  884. enqueueMeasure(node: T, element: HTMLElement) {
  885. if (this.cache.has(node)) {
  886. return;
  887. }
  888. this.queue.push([node, element]);
  889. if (this.drainRaf !== null) {
  890. window.cancelAnimationFrame(this.drainRaf);
  891. }
  892. this.drainRaf = window.requestAnimationFrame(this.drain);
  893. }
  894. drain() {
  895. for (const [node, element] of this.queue) {
  896. this.measure(node, element);
  897. }
  898. }
  899. measure(node: T, element: HTMLElement): number {
  900. const cache = this.cache.get(node);
  901. if (cache !== undefined) {
  902. return cache;
  903. }
  904. const width = element.getBoundingClientRect().width;
  905. if (width > this.max) {
  906. this.max = width;
  907. }
  908. this.cache.set(node, width);
  909. return width;
  910. }
  911. }
  912. // The backing cache should be a proper LRU cache,
  913. // so we dont end up storing an infinite amount of elements
  914. class TextMeasurer {
  915. queue: string[] = [];
  916. drainRaf: number | null = null;
  917. cache: Map<string, number> = new Map();
  918. ctx: CanvasRenderingContext2D;
  919. number: number = 0;
  920. dot: number = 0;
  921. duration: Record<string, number> = {};
  922. constructor() {
  923. this.drain = this.drain.bind(this);
  924. const canvas = document.createElement('canvas');
  925. const ctx = canvas.getContext('2d');
  926. if (!ctx) {
  927. throw new Error('Canvas 2d context is not available');
  928. }
  929. canvas.width = 50 * window.devicePixelRatio ?? 1;
  930. canvas.height = 50 * window.devicePixelRatio ?? 1;
  931. this.ctx = ctx;
  932. ctx.font = '11px' + theme.text.family;
  933. this.dot = this.ctx.measureText('.').width;
  934. for (let i = 0; i < 10; i++) {
  935. const measurement = this.ctx.measureText(i.toString());
  936. this.number = Math.max(this.number, measurement.width);
  937. }
  938. for (const duration of ['ns', 'ms', 's', 'm', 'h', 'd']) {
  939. this.duration[duration] = this.ctx.measureText(duration).width;
  940. }
  941. }
  942. drain() {
  943. for (const string of this.queue) {
  944. this.measure(string);
  945. }
  946. }
  947. computeStringLength(string: string): number {
  948. let width = 0;
  949. for (let i = 0; i < string.length; i++) {
  950. switch (string[i]) {
  951. case '.':
  952. width += this.dot;
  953. break;
  954. case '0':
  955. case '1':
  956. case '2':
  957. case '3':
  958. case '4':
  959. case '5':
  960. case '6':
  961. case '7':
  962. case '8':
  963. case '9':
  964. width += this.number;
  965. break;
  966. default:
  967. const remaining = string.slice(i);
  968. if (this.duration[remaining]) {
  969. width += this.duration[remaining];
  970. return width;
  971. }
  972. }
  973. }
  974. return width;
  975. }
  976. measure(string: string): number {
  977. const cached_width = this.cache.get(string);
  978. if (cached_width !== undefined) {
  979. return cached_width;
  980. }
  981. const width = this.computeStringLength(string);
  982. this.cache.set(string, width);
  983. return width;
  984. }
  985. }
  986. function findInTreeFromSegment(
  987. start: TraceTreeNode<TraceTree.NodeValue>,
  988. segment: TraceTree.NodePath
  989. ): TraceTreeNode<TraceTree.NodeValue> | null {
  990. const [type, id] = segment.split(':');
  991. if (!type || !id) {
  992. throw new TypeError('Node path must be in the format of `type:id`');
  993. }
  994. return TraceTreeNode.Find(start, node => {
  995. if (type === 'txn' && isTransactionNode(node)) {
  996. return node.value.event_id === id;
  997. }
  998. if (type === 'span' && isSpanNode(node)) {
  999. return node.value.span_id === id;
  1000. }
  1001. if (type === 'ag' && isAutogroupedNode(node)) {
  1002. if (isParentAutogroupedNode(node)) {
  1003. return node.head.value.span_id === id || node.tail.value.span_id === id;
  1004. }
  1005. if (isSiblingAutogroupedNode(node)) {
  1006. const child = node.children[0];
  1007. if (isSpanNode(child)) {
  1008. return child.value.span_id === id;
  1009. }
  1010. }
  1011. }
  1012. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1013. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1014. }
  1015. if (type === 'error' && isTraceErrorNode(node)) {
  1016. return node.value.event_id === id;
  1017. }
  1018. return false;
  1019. });
  1020. }