virtualizedViewManager.tsx 28 KB

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