virtualizedViewManager.tsx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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 > 150) {
  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. readonly span_matrix: [number, number, number, number, number, number] = [
  585. 1, 0, 0, 1, 0, 0,
  586. ];
  587. computeSpanCSSMatrixTransform(
  588. space: [number, number]
  589. ): [number, number, number, number, number, number] {
  590. const scale = space[1] / this.trace_view.width;
  591. this.span_matrix[0] = Math.max(
  592. scale,
  593. (1 * this.span_to_px[0]) / this.trace_view.width
  594. );
  595. this.span_matrix[3] = 1;
  596. this.span_matrix[4] =
  597. (space[0] - this.to_origin) / this.span_to_px[0] -
  598. this.trace_view.x / this.span_to_px[0];
  599. return this.span_matrix;
  600. }
  601. scrollToPath(
  602. tree: TraceTree,
  603. scrollQueue: TraceTree.NodePath[],
  604. rerender: () => void,
  605. {api, organization}: {api: Client; organization: Organization}
  606. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  607. const segments = [...scrollQueue];
  608. const list = this.list;
  609. if (!list) {
  610. return Promise.resolve(null);
  611. }
  612. if (segments.length === 1 && segments[0] === 'trace:root') {
  613. rerender();
  614. list.scrollToRow(0);
  615. return Promise.resolve({index: 0, node: tree.root.children[0]});
  616. }
  617. // Keep parent reference as we traverse the tree so that we can only
  618. // perform searching in the current level and not the entire tree
  619. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  620. const scrollToRow = async (): Promise<{
  621. index: number;
  622. node: TraceTreeNode<TraceTree.NodeValue>;
  623. } | null | null> => {
  624. const path = segments.pop();
  625. const current = findInTreeFromSegment(parent, path!);
  626. if (!current) {
  627. Sentry.captureMessage('Failed to scroll to node in trace tree');
  628. return null;
  629. }
  630. // Reassing the parent to the current node
  631. parent = current;
  632. if (isTransactionNode(current)) {
  633. const nextSegment = segments[segments.length - 1];
  634. if (
  635. nextSegment?.startsWith('span:') ||
  636. nextSegment?.startsWith('ag:') ||
  637. nextSegment?.startsWith('ms:')
  638. ) {
  639. await tree.zoomIn(current, true, {
  640. api,
  641. organization,
  642. });
  643. return scrollToRow();
  644. }
  645. }
  646. if (isAutogroupedNode(current) && segments.length > 0) {
  647. tree.expand(current, true);
  648. return scrollToRow();
  649. }
  650. if (segments.length > 0) {
  651. return scrollToRow();
  652. }
  653. // We are at the last path segment (the node that the user clicked on)
  654. // and we should scroll the view to this node.
  655. const index = tree.list.findIndex(node => node === current);
  656. if (index === -1) {
  657. throw new Error("Couldn't find node in list");
  658. }
  659. rerender();
  660. list.scrollToRow(index);
  661. return {index, node: current};
  662. };
  663. return scrollToRow();
  664. }
  665. computeTransformXFromTimestamp(timestamp: number): number {
  666. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  667. }
  668. computeSpanTextPlacement(span_space: [number, number], text: string): [number, number] {
  669. const TEXT_PADDING = 2;
  670. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  671. const width = this.text_measurer.measure(text);
  672. // precomput all anchor points aot, so we make the control flow more readable.
  673. // this wastes some cycles, but it's not a big deal as computers are fast when
  674. // it comes to simple arithmetic.
  675. const right_outside =
  676. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  677. const right_inside =
  678. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  679. width -
  680. TEXT_PADDING;
  681. const left_outside =
  682. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  683. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  684. const window_right =
  685. this.computeTransformXFromTimestamp(
  686. this.to_origin + this.trace_view.left + this.trace_view.width
  687. ) -
  688. width -
  689. TEXT_PADDING;
  690. const window_left =
  691. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  692. TEXT_PADDING;
  693. const view_left = this.trace_view.x;
  694. const view_right = view_left + this.trace_view.width;
  695. const span_left = span_space[0] - this.to_origin;
  696. const span_right = span_left + span_space[1];
  697. const space_right = view_right - span_right;
  698. const space_left = span_left - view_left;
  699. // Span is completely outside of the view on the left side
  700. if (span_right < this.trace_view.x) {
  701. return anchor_left ? [1, right_inside] : [0, right_outside];
  702. }
  703. // Span is completely outside of the view on the right side
  704. if (span_left > this.trace_view.right) {
  705. return anchor_left ? [0, left_outside] : [1, left_inside];
  706. }
  707. // Span "spans" the entire view
  708. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  709. return anchor_left ? [1, window_left] : [1, window_right];
  710. }
  711. const full_span_px_width = span_space[1] / this.span_to_px[0];
  712. if (anchor_left) {
  713. // While we have space on the left, place the text there
  714. if (space_left > 0) {
  715. return [0, left_outside];
  716. }
  717. const distance = span_right - this.trace_view.left;
  718. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  719. // If the text fits inside the visible portion of the span, anchor it to the left
  720. // side of the window so that it is visible while the user pans the view
  721. if (visible_width - TEXT_PADDING >= width) {
  722. return [1, window_left];
  723. }
  724. // If the text doesnt fit inside the visible portion of the span,
  725. // anchor it to the inside right place in the span.
  726. return [1, right_inside];
  727. }
  728. // While we have space on the right, place the text there
  729. if (space_right > 0) {
  730. return [0, right_outside];
  731. }
  732. // If text fits inside the span
  733. if (full_span_px_width > width) {
  734. const distance = span_right - this.trace_view.right;
  735. const visible_width =
  736. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  737. // If the text fits inside the visible portion of the span, anchor it to the right
  738. // side of the window so that it is visible while the user pans the view
  739. if (visible_width - TEXT_PADDING >= width) {
  740. return [1, window_right];
  741. }
  742. // If the text doesnt fit inside the visible portion of the span,
  743. // anchor it to the inside left of the span
  744. return [1, left_inside];
  745. }
  746. return [0, right_outside];
  747. }
  748. draw(options: {list?: number; span_list?: number} = {}) {
  749. const list_width = options.list ?? this.columns.list.width;
  750. const span_list_width = options.span_list ?? this.columns.span_list.width;
  751. if (this.divider) {
  752. this.divider.style.transform = `translateX(${
  753. list_width * this.container_physical_space.width - DIVIDER_WIDTH / 2 - 1
  754. }px)`;
  755. }
  756. if (this.indicator_container) {
  757. this.indicator_container.style.width = span_list_width * 100 + '%';
  758. }
  759. const listWidth = list_width * 100 + '%';
  760. const spanWidth = span_list_width * 100 + '%';
  761. // JavaScript "arrays" are nice in the sense that they are really just dicts,
  762. // allowing us to store negative indices. This sometimes happens as the list
  763. // virtualizes the rows and we end up with a negative index as they are being
  764. // rendered off screen.
  765. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  766. while (this.span_bars[i] === undefined && i < this.columns.list.column_refs.length)
  767. i++;
  768. const list = this.columns.list.column_refs[i];
  769. if (list) list.style.width = listWidth;
  770. const span = this.columns.span_list.column_refs[i];
  771. if (span) span.style.width = spanWidth;
  772. const span_bar = this.span_bars[i];
  773. if (span_bar) {
  774. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  775. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  776. }
  777. const span_text = this.span_text[i];
  778. if (span_text) {
  779. const [inside, text_transform] = this.computeSpanTextPlacement(
  780. span_text.space,
  781. span_text.text
  782. );
  783. if (text_transform === null) {
  784. continue;
  785. }
  786. span_text.ref.style.color = inside ? 'white' : '';
  787. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  788. }
  789. }
  790. let start_indicator = 0;
  791. let end_indicator = this.indicators.length;
  792. while (start_indicator < this.indicators.length - 1) {
  793. const indicator = this.indicators[start_indicator];
  794. if (!indicator?.indicator) {
  795. start_indicator++;
  796. continue;
  797. }
  798. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  799. start_indicator++;
  800. continue;
  801. }
  802. break;
  803. }
  804. while (end_indicator > start_indicator) {
  805. const last_indicator = this.indicators[end_indicator - 1];
  806. if (!last_indicator) {
  807. end_indicator--;
  808. continue;
  809. }
  810. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  811. end_indicator--;
  812. continue;
  813. }
  814. break;
  815. }
  816. start_indicator = Math.max(0, start_indicator - 1);
  817. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  818. for (let i = 0; i < this.indicators.length; i++) {
  819. const entry = this.indicators[i];
  820. if (!entry) {
  821. continue;
  822. }
  823. if (i < start_indicator || i > end_indicator) {
  824. entry.ref.style.opacity = '0';
  825. continue;
  826. }
  827. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  828. const label = entry.ref.children[0] as HTMLElement | undefined;
  829. const indicator_max = this.trace_physical_space.width + 1;
  830. const indicator_min = -1;
  831. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  832. const clamped_transform = clamp(transform, -1, indicator_max);
  833. if (label_width === undefined) {
  834. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  835. continue;
  836. }
  837. if (label) {
  838. const PADDING = 2;
  839. const label_window_left = PADDING;
  840. const label_window_right = -label_width - PADDING;
  841. if (transform < -1) {
  842. label.style.transform = `translateX(${label_window_left}px)`;
  843. } else if (transform >= indicator_max) {
  844. label.style.transform = `translateX(${label_window_right}px)`;
  845. } else {
  846. const space_left = transform - PADDING - label_width / 2;
  847. const space_right = transform + label_width / 2;
  848. if (space_left < 0) {
  849. const left = -label_width / 2 + Math.abs(space_left);
  850. label.style.transform = `translateX(${left - 1}px)`;
  851. } else if (space_right > this.trace_physical_space.width) {
  852. const right =
  853. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  854. label.style.transform = `translateX(${right}px)`;
  855. } else {
  856. label.style.transform = `translateX(${-label_width / 2}px)`;
  857. }
  858. }
  859. }
  860. entry.ref.style.opacity = '1';
  861. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  862. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  863. }
  864. }
  865. teardown() {
  866. if (this.container) {
  867. this.container.removeEventListener('wheel', onPreventBackForwardNavigation);
  868. }
  869. if (this.resize_observer) {
  870. this.resize_observer.disconnect();
  871. }
  872. }
  873. }
  874. // The backing cache should be a proper LRU cache,
  875. // so we dont end up storing an infinite amount of elements
  876. class DOMWidthMeasurer<T> {
  877. cache: Map<T, number> = new Map();
  878. elements: HTMLElement[] = [];
  879. queue: [T, HTMLElement][] = [];
  880. drainRaf: number | null = null;
  881. max: number = 0;
  882. constructor() {
  883. this.drain = this.drain.bind(this);
  884. }
  885. enqueueMeasure(node: T, element: HTMLElement) {
  886. if (this.cache.has(node)) {
  887. return;
  888. }
  889. this.queue.push([node, element]);
  890. if (this.drainRaf !== null) {
  891. window.cancelAnimationFrame(this.drainRaf);
  892. }
  893. this.drainRaf = window.requestAnimationFrame(this.drain);
  894. }
  895. drain() {
  896. for (const [node, element] of this.queue) {
  897. this.measure(node, element);
  898. }
  899. }
  900. measure(node: T, element: HTMLElement): number {
  901. const cache = this.cache.get(node);
  902. if (cache !== undefined) {
  903. return cache;
  904. }
  905. const width = element.getBoundingClientRect().width;
  906. if (width > this.max) {
  907. this.max = width;
  908. }
  909. this.cache.set(node, width);
  910. return width;
  911. }
  912. }
  913. // The backing cache should be a proper LRU cache,
  914. // so we dont end up storing an infinite amount of elements
  915. class TextMeasurer {
  916. queue: string[] = [];
  917. drainRaf: number | null = null;
  918. cache: Map<string, number> = new Map();
  919. ctx: CanvasRenderingContext2D;
  920. number: number = 0;
  921. dot: number = 0;
  922. duration: Record<string, number> = {};
  923. constructor() {
  924. this.drain = this.drain.bind(this);
  925. const canvas = document.createElement('canvas');
  926. const ctx = canvas.getContext('2d');
  927. if (!ctx) {
  928. throw new Error('Canvas 2d context is not available');
  929. }
  930. canvas.width = 50 * window.devicePixelRatio ?? 1;
  931. canvas.height = 50 * window.devicePixelRatio ?? 1;
  932. this.ctx = ctx;
  933. ctx.font = '11px' + theme.text.family;
  934. this.dot = this.ctx.measureText('.').width;
  935. for (let i = 0; i < 10; i++) {
  936. const measurement = this.ctx.measureText(i.toString());
  937. this.number = Math.max(this.number, measurement.width);
  938. }
  939. for (const duration of ['ns', 'ms', 's', 'm', 'h', 'd']) {
  940. this.duration[duration] = this.ctx.measureText(duration).width;
  941. }
  942. }
  943. drain() {
  944. for (const string of this.queue) {
  945. this.measure(string);
  946. }
  947. }
  948. computeStringLength(string: string): number {
  949. let width = 0;
  950. for (let i = 0; i < string.length; i++) {
  951. switch (string[i]) {
  952. case '.':
  953. width += this.dot;
  954. break;
  955. case '0':
  956. case '1':
  957. case '2':
  958. case '3':
  959. case '4':
  960. case '5':
  961. case '6':
  962. case '7':
  963. case '8':
  964. case '9':
  965. width += this.number;
  966. break;
  967. default:
  968. const remaining = string.slice(i);
  969. if (this.duration[remaining]) {
  970. width += this.duration[remaining];
  971. return width;
  972. }
  973. }
  974. }
  975. return width;
  976. }
  977. measure(string: string): number {
  978. const cached_width = this.cache.get(string);
  979. if (cached_width !== undefined) {
  980. return cached_width;
  981. }
  982. const width = this.computeStringLength(string);
  983. this.cache.set(string, width);
  984. return width;
  985. }
  986. }
  987. function findInTreeFromSegment(
  988. start: TraceTreeNode<TraceTree.NodeValue>,
  989. segment: TraceTree.NodePath
  990. ): TraceTreeNode<TraceTree.NodeValue> | null {
  991. const [type, id] = segment.split(':');
  992. if (!type || !id) {
  993. throw new TypeError('Node path must be in the format of `type:id`');
  994. }
  995. return TraceTreeNode.Find(start, node => {
  996. if (type === 'txn' && isTransactionNode(node)) {
  997. return node.value.event_id === id;
  998. }
  999. if (type === 'span' && isSpanNode(node)) {
  1000. return node.value.span_id === id;
  1001. }
  1002. if (type === 'ag' && isAutogroupedNode(node)) {
  1003. if (isParentAutogroupedNode(node)) {
  1004. return node.head.value.span_id === id || node.tail.value.span_id === id;
  1005. }
  1006. if (isSiblingAutogroupedNode(node)) {
  1007. const child = node.children[0];
  1008. if (isSpanNode(child)) {
  1009. return child.value.span_id === id;
  1010. }
  1011. }
  1012. }
  1013. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1014. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1015. }
  1016. if (type === 'error' && isTraceErrorNode(node)) {
  1017. return node.value.event_id === id;
  1018. }
  1019. return false;
  1020. });
  1021. }