virtualizedViewManager.tsx 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. import {useLayoutEffect, useRef, useState} from 'react';
  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 {getDuration} from 'sentry/utils/formatters';
  7. import clamp from 'sentry/utils/number/clamp';
  8. import {requestAnimationTimeout} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  9. import {lightTheme as theme} from 'sentry/utils/theme';
  10. import {
  11. isAutogroupedNode,
  12. isMissingInstrumentationNode,
  13. isParentAutogroupedNode,
  14. isSiblingAutogroupedNode,
  15. isSpanNode,
  16. isTraceErrorNode,
  17. isTransactionNode,
  18. } from 'sentry/views/performance/newTraceDetails/guards';
  19. import {
  20. type TraceTree,
  21. TraceTreeNode,
  22. } from 'sentry/views/performance/newTraceDetails/traceTree';
  23. const DIVIDER_WIDTH = 6;
  24. function easeOutSine(x: number): number {
  25. return Math.sin((x * Math.PI) / 2);
  26. }
  27. type ViewColumn = {
  28. column_nodes: TraceTreeNode<TraceTree.NodeValue>[];
  29. column_refs: (HTMLElement | undefined)[];
  30. translate: [number, number];
  31. width: number;
  32. };
  33. class View {
  34. public x: number;
  35. public y: number;
  36. public width: number;
  37. public height: number;
  38. constructor(x: number, y: number, width: number, height: number) {
  39. this.x = x;
  40. this.y = y;
  41. this.width = width;
  42. this.height = height;
  43. }
  44. static From(view: View): View {
  45. return new View(view.x, view.y, view.width, view.height);
  46. }
  47. static Empty(): View {
  48. return new View(0, 0, 1000, 1);
  49. }
  50. serialize() {
  51. return [this.x, this.y, this.width, this.height];
  52. }
  53. between(to: View): mat3 {
  54. return mat3.fromValues(
  55. to.width / this.width,
  56. 0,
  57. 0,
  58. to.height / this.height,
  59. 0,
  60. 0,
  61. to.x - this.x * (to.width / this.width),
  62. to.y - this.y * (to.height / this.height),
  63. 1
  64. );
  65. }
  66. transform(mat: mat3): [number, number, number, number] {
  67. const x = this.x * mat[0] + this.y * mat[3] + mat[6];
  68. const y = this.x * mat[1] + this.y * mat[4] + mat[7];
  69. const width = this.width * mat[0] + this.height * mat[3];
  70. const height = this.width * mat[1] + this.height * mat[4];
  71. return [x, y, width, height];
  72. }
  73. get center() {
  74. return this.x + this.width / 2;
  75. }
  76. get left() {
  77. return this.x;
  78. }
  79. get right() {
  80. return this.x + this.width;
  81. }
  82. get top() {
  83. return this.y;
  84. }
  85. get bottom() {
  86. return this.y + this.height;
  87. }
  88. }
  89. export function computeTimelineIntervals(
  90. view: View,
  91. targetInterval: number,
  92. results: (number | undefined)[]
  93. ): void {
  94. const minInterval = Math.pow(10, Math.floor(Math.log10(targetInterval)));
  95. let interval = minInterval;
  96. if (targetInterval / interval > 5) {
  97. interval *= 5;
  98. } else if (targetInterval / interval > 2) {
  99. interval *= 2;
  100. }
  101. let x = Math.ceil(view.x / interval) * interval;
  102. let idx = -1;
  103. if (x > 0) {
  104. x -= interval;
  105. }
  106. while (x <= view.right) {
  107. results[++idx] = x;
  108. x += interval;
  109. }
  110. while (idx < results.length - 1 && results[idx + 1] !== undefined) {
  111. results[++idx] = undefined;
  112. }
  113. }
  114. /**
  115. * Tracks the state of the virtualized view and manages the resizing of the columns.
  116. * Children components should call the appropriate register*Ref methods to register their
  117. * HTML elements.
  118. */
  119. export class VirtualizedViewManager {
  120. // Represents the space of the entire trace, for example
  121. // a trace starting at 0 and ending at 1000 would have a space of [0, 1000]
  122. to_origin: number = 0;
  123. trace_space: View = View.Empty();
  124. // The view defines what the user is currently looking at, it is a subset
  125. // of the trace space. For example, if the user is currently looking at the
  126. // trace from 500 to 1000, the view would be represented by [x, width] = [500, 500]
  127. trace_view: View = View.Empty();
  128. // Represents the pixel space of the entire trace - this is the container
  129. // that we render to. For example, if the container is 1000px wide, the
  130. // pixel space would be [0, 1000]
  131. trace_physical_space: View = View.Empty();
  132. container_physical_space: View = View.Empty();
  133. row_measurer: DOMWidthMeasurer<TraceTreeNode<TraceTree.NodeValue>> =
  134. new DOMWidthMeasurer();
  135. indicator_label_measurer: DOMWidthMeasurer<TraceTree['indicators'][0]> =
  136. new DOMWidthMeasurer();
  137. text_measurer: TextMeasurer = new TextMeasurer();
  138. resize_observer: ResizeObserver | null = null;
  139. list: VirtualizedList | null = null;
  140. isScrolling: boolean = false;
  141. start_virtualized_index: number = 0;
  142. // HTML refs that we need to keep track of such
  143. // that rendering can be done programmatically
  144. divider: HTMLElement | null = null;
  145. container: HTMLElement | null = null;
  146. indicator_container: HTMLElement | null = null;
  147. intervals: number[] = [];
  148. interval_bars = new Array(10).fill(0);
  149. indicators: ({indicator: TraceTree['indicators'][0]; ref: HTMLElement} | undefined)[] =
  150. [];
  151. timeline_indicators: (HTMLElement | undefined)[] = [];
  152. span_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  153. invisible_bars: ({ref: HTMLElement; space: [number, number]} | undefined)[] = [];
  154. span_arrows: (
  155. | {
  156. position: 0 | 1;
  157. ref: HTMLElement;
  158. space: [number, number];
  159. visible: boolean;
  160. }
  161. | undefined
  162. )[] = [];
  163. span_text: ({ref: HTMLElement; space: [number, number]; text: string} | undefined)[] =
  164. [];
  165. // Holds the span to px matrix so we dont keep recalculating it
  166. span_to_px: mat3 = mat3.create();
  167. row_depth_padding: number = 22;
  168. // Column configuration
  169. columns: {
  170. list: ViewColumn;
  171. span_list: ViewColumn;
  172. };
  173. constructor(columns: {
  174. list: Pick<ViewColumn, 'width'>;
  175. span_list: Pick<ViewColumn, 'width'>;
  176. }) {
  177. this.columns = {
  178. list: {...columns.list, column_nodes: [], column_refs: [], translate: [0, 0]},
  179. span_list: {
  180. ...columns.span_list,
  181. column_nodes: [],
  182. column_refs: [],
  183. translate: [0, 0],
  184. },
  185. };
  186. this.onDividerMouseDown = this.onDividerMouseDown.bind(this);
  187. this.onDividerMouseUp = this.onDividerMouseUp.bind(this);
  188. this.onDividerMouseMove = this.onDividerMouseMove.bind(this);
  189. this.onSyncedScrollbarScroll = this.onSyncedScrollbarScroll.bind(this);
  190. this.onWheelZoom = this.onWheelZoom.bind(this);
  191. }
  192. initializeTraceSpace(space: [x: number, y: number, width: number, height: number]) {
  193. this.to_origin = space[0];
  194. this.trace_space = new View(0, 0, space[2], space[3]);
  195. this.trace_view = new View(0, 0, space[2], space[3]);
  196. this.recomputeTimelineIntervals();
  197. this.recomputeSpanToPxMatrix();
  198. }
  199. initializePhysicalSpace(width: number, height: number) {
  200. this.container_physical_space = new View(0, 0, width, height);
  201. this.trace_physical_space = new View(
  202. 0,
  203. 0,
  204. width * this.columns.span_list.width,
  205. height
  206. );
  207. this.recomputeTimelineIntervals();
  208. this.recomputeSpanToPxMatrix();
  209. }
  210. onContainerRef(container: HTMLElement | null) {
  211. if (container) {
  212. this.initialize(container);
  213. } else {
  214. this.teardown();
  215. }
  216. }
  217. dividerScale: 1 | undefined = undefined;
  218. dividerStartVec: [number, number] | null = null;
  219. previousDividerClientVec: [number, number] | null = null;
  220. onDividerMouseDown(event: MouseEvent) {
  221. if (!this.container) {
  222. return;
  223. }
  224. this.dividerScale = this.trace_view.width === this.trace_space.width ? 1 : undefined;
  225. this.dividerStartVec = [event.clientX, event.clientY];
  226. this.previousDividerClientVec = [event.clientX, event.clientY];
  227. this.container.style.userSelect = 'none';
  228. this.container.addEventListener('mouseup', this.onDividerMouseUp, {passive: true});
  229. this.container.addEventListener('mousemove', this.onDividerMouseMove, {
  230. passive: true,
  231. });
  232. }
  233. onDividerMouseUp(event: MouseEvent) {
  234. if (!this.container || !this.dividerStartVec) {
  235. return;
  236. }
  237. this.dividerScale = undefined;
  238. const distance = event.clientX - this.dividerStartVec[0];
  239. const distancePercentage = distance / this.container_physical_space.width;
  240. this.columns.list.width = this.columns.list.width + distancePercentage;
  241. this.columns.span_list.width = this.columns.span_list.width - distancePercentage;
  242. this.container.style.userSelect = 'auto';
  243. this.dividerStartVec = null;
  244. this.previousDividerClientVec = null;
  245. this.enqueueOnScrollEndOutOfBoundsCheck();
  246. this.container.removeEventListener('mouseup', this.onDividerMouseUp);
  247. this.container.removeEventListener('mousemove', this.onDividerMouseMove);
  248. }
  249. onDividerMouseMove(event: MouseEvent) {
  250. if (!this.dividerStartVec || !this.divider || !this.previousDividerClientVec) {
  251. return;
  252. }
  253. const distance = event.clientX - this.dividerStartVec[0];
  254. const distancePercentage = distance / this.container_physical_space.width;
  255. this.trace_physical_space.width =
  256. (this.columns.span_list.width - distancePercentage) *
  257. this.container_physical_space.width;
  258. const physical_distance = this.previousDividerClientVec[0] - event.clientX;
  259. const config_distance_pct = physical_distance / this.trace_physical_space.width;
  260. const config_distance = this.trace_view.width * config_distance_pct;
  261. if (this.dividerScale) {
  262. // just recompute the draw matrix and let the view scale itself
  263. this.recomputeSpanToPxMatrix();
  264. } else {
  265. this.setTraceView({
  266. x: this.trace_view.x - config_distance,
  267. width: this.trace_view.width + config_distance,
  268. });
  269. }
  270. this.draw({
  271. list: this.columns.list.width + distancePercentage,
  272. span_list: this.columns.span_list.width - distancePercentage,
  273. });
  274. this.previousDividerClientVec = [event.clientX, event.clientY];
  275. }
  276. registerList(list: VirtualizedList | null) {
  277. this.list = list;
  278. }
  279. registerIndicatorContainerRef(ref: HTMLElement | null) {
  280. if (ref) {
  281. ref.style.width = this.columns.span_list.width * 100 + '%';
  282. }
  283. this.indicator_container = ref;
  284. }
  285. registerDividerRef(ref: HTMLElement | null) {
  286. if (!ref) {
  287. if (this.divider) {
  288. this.divider.removeEventListener('mousedown', this.onDividerMouseDown);
  289. }
  290. this.divider = null;
  291. return;
  292. }
  293. this.divider = ref;
  294. this.divider.style.width = `${DIVIDER_WIDTH}px`;
  295. ref.addEventListener('mousedown', this.onDividerMouseDown, {passive: true});
  296. }
  297. registerSpanBarRef(ref: HTMLElement | null, space: [number, number], index: number) {
  298. this.span_bars[index] = ref ? {ref, space} : undefined;
  299. }
  300. registerInvisibleBarRef(
  301. ref: HTMLElement | null,
  302. space: [number, number],
  303. index: number
  304. ) {
  305. this.invisible_bars[index] = ref ? {ref, space} : undefined;
  306. }
  307. registerArrowRef(ref: HTMLElement | null, space: [number, number], index: number) {
  308. this.span_arrows[index] = ref ? {ref, space, visible: false, position: 0} : undefined;
  309. }
  310. registerSpanBarTextRef(
  311. ref: HTMLElement | null,
  312. text: string,
  313. space: [number, number],
  314. index: number
  315. ) {
  316. this.span_text[index] = ref ? {ref, text, space} : undefined;
  317. }
  318. registerColumnRef(
  319. column: string,
  320. ref: HTMLElement | null,
  321. index: number,
  322. node: TraceTreeNode<any>
  323. ) {
  324. if (column === 'list') {
  325. const element = this.columns[column].column_refs[index];
  326. if (ref === undefined && element) {
  327. element.removeEventListener('wheel', this.onSyncedScrollbarScroll);
  328. } else if (ref) {
  329. const scrollableElement = ref.children[0] as HTMLElement | undefined;
  330. if (scrollableElement) {
  331. scrollableElement.style.transform = `translateX(${this.columns.list.translate[0]}px)`;
  332. this.row_measurer.measure(node, scrollableElement as HTMLElement);
  333. ref.addEventListener('wheel', this.onSyncedScrollbarScroll, {passive: true});
  334. }
  335. }
  336. }
  337. if (column === 'span_list') {
  338. const element = this.columns[column].column_refs[index];
  339. if (ref === undefined && element) {
  340. element.removeEventListener('wheel', this.onWheelZoom);
  341. } else if (ref) {
  342. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  343. }
  344. }
  345. this.columns[column].column_refs[index] = ref ?? undefined;
  346. this.columns[column].column_nodes[index] = node ?? undefined;
  347. }
  348. registerIndicatorRef(
  349. ref: HTMLElement | null,
  350. index: number,
  351. indicator: TraceTree['indicators'][0]
  352. ) {
  353. if (!ref) {
  354. const element = this.indicators[index]?.ref;
  355. if (element) {
  356. element.removeEventListener('wheel', this.onWheelZoom);
  357. }
  358. this.indicators[index] = undefined;
  359. } else {
  360. this.indicators[index] = {ref, indicator};
  361. }
  362. if (ref) {
  363. const label = ref.children[0] as HTMLElement | undefined;
  364. if (label) {
  365. this.indicator_label_measurer.measure(indicator, label);
  366. }
  367. ref.addEventListener('wheel', this.onWheelZoom, {passive: false});
  368. ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(
  369. indicator.start
  370. )}px)`;
  371. }
  372. }
  373. registerTimelineIndicatorRef(ref: HTMLElement | null, index: number) {
  374. if (ref) {
  375. this.timeline_indicators[index] = ref;
  376. } else {
  377. this.timeline_indicators[index] = undefined;
  378. }
  379. }
  380. getConfigSpaceCursor(cursor: {x: number; y: number}): [number, number] {
  381. const left_percentage = cursor.x / this.trace_physical_space.width;
  382. const left_view = left_percentage * this.trace_view.width;
  383. return [this.trace_view.x + left_view, 0];
  384. }
  385. onWheelZoom(event: WheelEvent) {
  386. if (event.metaKey) {
  387. event.preventDefault();
  388. if (!this.onWheelEndRaf) {
  389. this.onWheelStart();
  390. this.enqueueOnWheelEndRaf();
  391. return;
  392. }
  393. const scale = 1 - event.deltaY * 0.01 * -1;
  394. const configSpaceCursor = this.getConfigSpaceCursor({
  395. x: event.offsetX,
  396. y: event.offsetY,
  397. });
  398. const center = vec2.fromValues(configSpaceCursor[0], 0);
  399. const centerScaleMatrix = mat3.create();
  400. mat3.fromTranslation(centerScaleMatrix, center);
  401. mat3.scale(centerScaleMatrix, centerScaleMatrix, vec2.fromValues(scale, 1));
  402. mat3.translate(
  403. centerScaleMatrix,
  404. centerScaleMatrix,
  405. vec2.fromValues(-center[0], 0)
  406. );
  407. const newView = this.trace_view.transform(centerScaleMatrix);
  408. this.setTraceView({
  409. x: newView[0],
  410. width: newView[2],
  411. });
  412. } else {
  413. const physical_delta_pct = event.deltaX / this.trace_physical_space.width;
  414. const view_delta = physical_delta_pct * this.trace_view.width;
  415. this.setTraceView({
  416. x: this.trace_view.x + view_delta,
  417. });
  418. }
  419. this.draw();
  420. }
  421. zoomIntoSpaceRaf: number | null = null;
  422. onBringRowIntoView(space: [number, number]) {
  423. if (this.zoomIntoSpaceRaf !== null) {
  424. window.cancelAnimationFrame(this.zoomIntoSpaceRaf);
  425. this.zoomIntoSpaceRaf = null;
  426. }
  427. if (space[0] - this.to_origin > this.trace_view.x) {
  428. this.onZoomIntoSpace([
  429. space[0] + space[1] / 2 - this.trace_view.width / 2,
  430. this.trace_view.width,
  431. ]);
  432. } else if (space[0] - this.to_origin < this.trace_view.x) {
  433. this.onZoomIntoSpace([
  434. space[0] + space[1] / 2 - this.trace_view.width / 2,
  435. this.trace_view.width,
  436. ]);
  437. }
  438. }
  439. onZoomIntoSpace(space: [number, number]) {
  440. if (space[1] <= 0) {
  441. // @TODO implement scrolling to 0 width spaces
  442. return;
  443. }
  444. const distance_x = space[0] - this.to_origin - this.trace_view.x;
  445. const distance_width = this.trace_view.width - space[1];
  446. const start_x = this.trace_view.x;
  447. const start_width = this.trace_view.width;
  448. const start = performance.now();
  449. const rafCallback = (now: number) => {
  450. const elapsed = now - start;
  451. const progress = elapsed / 300;
  452. const eased = easeOutSine(progress);
  453. const x = start_x + distance_x * eased;
  454. const width = start_width - distance_width * eased;
  455. this.setTraceView({x, width});
  456. this.draw();
  457. if (progress < 1) {
  458. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  459. } else {
  460. this.zoomIntoSpaceRaf = null;
  461. this.setTraceView({x: space[0] - this.to_origin, width: space[1]});
  462. this.draw();
  463. }
  464. };
  465. this.zoomIntoSpaceRaf = window.requestAnimationFrame(rafCallback);
  466. }
  467. onWheelEndRaf: number | null = null;
  468. enqueueOnWheelEndRaf() {
  469. if (this.onWheelEndRaf !== null) {
  470. window.cancelAnimationFrame(this.onWheelEndRaf);
  471. }
  472. const start = performance.now();
  473. const rafCallback = (now: number) => {
  474. const elapsed = now - start;
  475. if (elapsed > 150) {
  476. this.onWheelEnd();
  477. } else {
  478. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  479. }
  480. };
  481. this.onWheelEndRaf = window.requestAnimationFrame(rafCallback);
  482. }
  483. onWheelStart() {
  484. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  485. const span_list = this.columns.span_list.column_refs[i];
  486. if (span_list?.children?.[0]) {
  487. (span_list.children[0] as HTMLElement).style.pointerEvents = 'none';
  488. }
  489. const span_text = this.span_text[i];
  490. if (span_text) {
  491. span_text.ref.style.pointerEvents = 'none';
  492. }
  493. }
  494. for (let i = 0; i < this.indicators.length; i++) {
  495. const indicator = this.indicators[i];
  496. if (indicator?.ref) {
  497. indicator.ref.style.pointerEvents = 'none';
  498. }
  499. }
  500. }
  501. onWheelEnd() {
  502. this.onWheelEndRaf = null;
  503. for (let i = 0; i < this.columns.span_list.column_refs.length; i++) {
  504. const span_list = this.columns.span_list.column_refs[i];
  505. if (span_list?.children?.[0]) {
  506. (span_list.children[0] as HTMLElement).style.pointerEvents = 'auto';
  507. }
  508. const span_text = this.span_text[i];
  509. if (span_text) {
  510. span_text.ref.style.pointerEvents = 'auto';
  511. }
  512. }
  513. for (let i = 0; i < this.indicators.length; i++) {
  514. const indicator = this.indicators[i];
  515. if (indicator?.ref) {
  516. indicator.ref.style.pointerEvents = 'auto';
  517. }
  518. }
  519. }
  520. setTraceView(view: {width?: number; x?: number}) {
  521. const x = view.x ?? this.trace_view.x;
  522. const width = view.width ?? this.trace_view.width;
  523. this.trace_view.x = clamp(x, 0, this.trace_space.width - width);
  524. this.trace_view.width = clamp(width, 0, this.trace_space.width - this.trace_view.x);
  525. this.recomputeTimelineIntervals();
  526. this.recomputeSpanToPxMatrix();
  527. }
  528. scrollSyncRaf: number | null = null;
  529. onSyncedScrollbarScroll(event: WheelEvent) {
  530. if (this.isScrolling) {
  531. return;
  532. }
  533. if (this.bringRowIntoViewAnimation !== null) {
  534. window.cancelAnimationFrame(this.bringRowIntoViewAnimation);
  535. this.bringRowIntoViewAnimation = null;
  536. }
  537. this.enqueueOnScrollEndOutOfBoundsCheck();
  538. const columnWidth = this.columns.list.width * this.container_physical_space.width;
  539. this.columns.list.translate[0] = clamp(
  540. this.columns.list.translate[0] - event.deltaX,
  541. -(this.row_measurer.max - columnWidth + 16), // 16px margin so we dont scroll right to the last px
  542. 0
  543. );
  544. if (this.scrollSyncRaf) {
  545. window.cancelAnimationFrame(this.scrollSyncRaf);
  546. }
  547. this.scrollSyncRaf = window.requestAnimationFrame(() => {
  548. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  549. const list = this.columns.list.column_refs[i];
  550. if (list?.children?.[0]) {
  551. (list.children[0] as HTMLElement).style.transform =
  552. `translateX(${this.columns.list.translate[0]}px)`;
  553. }
  554. }
  555. });
  556. }
  557. scrollEndSyncRaf: number | null = null;
  558. enqueueOnScrollEndOutOfBoundsCheck() {
  559. if (this.scrollEndSyncRaf !== null) {
  560. window.cancelAnimationFrame(this.scrollEndSyncRaf);
  561. }
  562. const start = performance.now();
  563. const rafCallback = (now: number) => {
  564. const elapsed = now - start;
  565. if (elapsed > 300) {
  566. this.onScrollEndOutOfBoundsCheck();
  567. } else {
  568. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  569. }
  570. };
  571. this.scrollEndSyncRaf = window.requestAnimationFrame(rafCallback);
  572. }
  573. onScrollEndOutOfBoundsCheck() {
  574. this.scrollEndSyncRaf = null;
  575. const translation = this.columns.list.translate[0];
  576. let min = Number.POSITIVE_INFINITY;
  577. let max = Number.NEGATIVE_INFINITY;
  578. let innerMostNode: TraceTreeNode<any> | undefined;
  579. for (let i = 5; i < this.columns.span_list.column_refs.length - 5; i++) {
  580. const width = this.row_measurer.cache.get(this.columns.list.column_nodes[i]);
  581. if (width === undefined) {
  582. // this is unlikely to happen, but we should trigger a sync measure event if it does
  583. continue;
  584. }
  585. min = Math.min(min, width);
  586. max = Math.max(max, width);
  587. innerMostNode =
  588. !innerMostNode || this.columns.list.column_nodes[i].depth < innerMostNode.depth
  589. ? this.columns.list.column_nodes[i]
  590. : innerMostNode;
  591. }
  592. if (innerMostNode) {
  593. if (translation + max < 0) {
  594. this.scrollRowIntoViewHorizontally(innerMostNode);
  595. } else if (
  596. translation + innerMostNode.depth * this.row_depth_padding >
  597. this.columns.list.width * this.container_physical_space.width
  598. ) {
  599. this.scrollRowIntoViewHorizontally(innerMostNode);
  600. }
  601. }
  602. }
  603. scrollRowIntoViewHorizontally(node: TraceTreeNode<any>, duration: number = 600) {
  604. const VISUAL_OFFSET = this.row_depth_padding / 2;
  605. const target = Math.min(-node.depth * this.row_depth_padding + VISUAL_OFFSET, 0);
  606. this.animateScrollColumnTo(target, duration);
  607. }
  608. bringRowIntoViewAnimation: number | null = null;
  609. animateScrollColumnTo(x: number, duration: number) {
  610. const start = performance.now();
  611. const startPosition = this.columns.list.translate[0];
  612. const distance = x - startPosition;
  613. const animate = (now: number) => {
  614. const elapsed = now - start;
  615. const progress = duration > 0 ? elapsed / duration : 1;
  616. const eased = easeOutSine(progress);
  617. const pos = startPosition + distance * eased;
  618. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  619. const list = this.columns.list.column_refs[i];
  620. if (list?.children?.[0]) {
  621. (list.children[0] as HTMLElement).style.transform = `translateX(${pos}px)`;
  622. }
  623. }
  624. if (progress < 1) {
  625. this.columns.list.translate[0] = pos;
  626. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  627. } else {
  628. this.columns.list.translate[0] = x;
  629. }
  630. };
  631. this.bringRowIntoViewAnimation = window.requestAnimationFrame(animate);
  632. }
  633. initialize(container: HTMLElement) {
  634. if (this.container !== container && this.resize_observer !== null) {
  635. this.teardown();
  636. }
  637. this.container = container;
  638. this.resize_observer = new ResizeObserver(entries => {
  639. const entry = entries[0];
  640. if (!entry) {
  641. throw new Error('ResizeObserver entry is undefined');
  642. }
  643. this.initializePhysicalSpace(entry.contentRect.width, entry.contentRect.height);
  644. this.draw();
  645. });
  646. this.resize_observer.observe(container);
  647. }
  648. recomputeSpanToPxMatrix() {
  649. const traceViewToSpace = this.trace_space.between(this.trace_view);
  650. const tracePhysicalToView = this.trace_physical_space.between(this.trace_space);
  651. this.span_to_px = mat3.multiply(
  652. this.span_to_px,
  653. traceViewToSpace,
  654. tracePhysicalToView
  655. );
  656. }
  657. recomputeTimelineIntervals() {
  658. const tracePhysicalToView = this.trace_physical_space.between(this.trace_view);
  659. const time_at_100 =
  660. tracePhysicalToView[0] * (100 * window.devicePixelRatio) +
  661. tracePhysicalToView[6] -
  662. this.trace_view.x;
  663. computeTimelineIntervals(this.trace_view, time_at_100, this.intervals);
  664. }
  665. readonly span_matrix: [number, number, number, number, number, number] = [
  666. 1, 0, 0, 1, 0, 0,
  667. ];
  668. computeSpanCSSMatrixTransform(
  669. space: [number, number]
  670. ): [number, number, number, number, number, number] {
  671. const scale = space[1] / this.trace_view.width;
  672. this.span_matrix[0] = Math.max(
  673. scale,
  674. (1 * this.span_to_px[0]) / this.trace_view.width
  675. );
  676. this.span_matrix[3] = 1;
  677. this.span_matrix[4] =
  678. (space[0] - this.to_origin) / this.span_to_px[0] -
  679. this.trace_view.x / this.span_to_px[0];
  680. return this.span_matrix;
  681. }
  682. scrollToPath(
  683. tree: TraceTree,
  684. scrollQueue: TraceTree.NodePath[],
  685. rerender: () => void,
  686. {api, organization}: {api: Client; organization: Organization}
  687. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  688. const segments = [...scrollQueue];
  689. const list = this.list;
  690. if (!list) {
  691. return Promise.resolve(null);
  692. }
  693. if (segments.length === 1 && segments[0] === 'trace:root') {
  694. rerender();
  695. list.scrollToRow(0);
  696. return Promise.resolve({index: 0, node: tree.root.children[0]});
  697. }
  698. // Keep parent reference as we traverse the tree so that we can only
  699. // perform searching in the current level and not the entire tree
  700. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  701. const scrollToRow = async (): Promise<{
  702. index: number;
  703. node: TraceTreeNode<TraceTree.NodeValue>;
  704. } | null | null> => {
  705. const path = segments.pop();
  706. const current = findInTreeFromSegment(parent, path!);
  707. if (!current) {
  708. Sentry.captureMessage('Failed to scroll to node in trace tree');
  709. return null;
  710. }
  711. // Reassing the parent to the current node
  712. parent = current;
  713. if (isTransactionNode(current)) {
  714. const nextSegment = segments[segments.length - 1];
  715. if (
  716. nextSegment?.startsWith('span:') ||
  717. nextSegment?.startsWith('ag:') ||
  718. nextSegment?.startsWith('ms:')
  719. ) {
  720. await tree.zoomIn(current, true, {
  721. api,
  722. organization,
  723. });
  724. return scrollToRow();
  725. }
  726. }
  727. if (isAutogroupedNode(current) && segments.length > 0) {
  728. tree.expand(current, true);
  729. return scrollToRow();
  730. }
  731. if (segments.length > 0) {
  732. return scrollToRow();
  733. }
  734. // We are at the last path segment (the node that the user clicked on)
  735. // and we should scroll the view to this node.
  736. const index = tree.list.findIndex(node => node === current);
  737. if (index === -1) {
  738. throw new Error("Couldn't find node in list");
  739. }
  740. rerender();
  741. list.scrollToRow(index);
  742. return {index, node: current};
  743. };
  744. return scrollToRow();
  745. }
  746. computeTransformXFromTimestamp(timestamp: number): number {
  747. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  748. }
  749. computeSpanTextPlacement(span_space: [number, number], text: string): [number, number] {
  750. const TEXT_PADDING = 2;
  751. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  752. const width = this.text_measurer.measure(text);
  753. // precomput all anchor points aot, so we make the control flow more readable.
  754. // this wastes some cycles, but it's not a big deal as computers are fast when
  755. // it comes to simple arithmetic.
  756. const right_outside =
  757. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  758. const right_inside =
  759. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  760. width -
  761. TEXT_PADDING;
  762. const left_outside =
  763. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  764. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  765. const window_right =
  766. this.computeTransformXFromTimestamp(
  767. this.to_origin + this.trace_view.left + this.trace_view.width
  768. ) -
  769. width -
  770. TEXT_PADDING;
  771. const window_left =
  772. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  773. TEXT_PADDING;
  774. const view_left = this.trace_view.x;
  775. const view_right = view_left + this.trace_view.width;
  776. const span_left = span_space[0] - this.to_origin;
  777. const span_right = span_left + span_space[1];
  778. const space_right = view_right - span_right;
  779. const space_left = span_left - view_left;
  780. // Span is completely outside of the view on the left side
  781. if (span_right < this.trace_view.x) {
  782. return anchor_left ? [1, right_inside] : [0, right_outside];
  783. }
  784. // Span is completely outside of the view on the right side
  785. if (span_left > this.trace_view.right) {
  786. return anchor_left ? [0, left_outside] : [1, left_inside];
  787. }
  788. // Span "spans" the entire view
  789. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  790. return anchor_left ? [1, window_left] : [1, window_right];
  791. }
  792. const full_span_px_width = span_space[1] / this.span_to_px[0];
  793. if (anchor_left) {
  794. // While we have space on the left, place the text there
  795. if (space_left > 0) {
  796. return [0, left_outside];
  797. }
  798. const distance = span_right - this.trace_view.left;
  799. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  800. // If the text fits inside the visible portion of the span, anchor it to the left
  801. // side of the window so that it is visible while the user pans the view
  802. if (visible_width - TEXT_PADDING >= width) {
  803. return [1, window_left];
  804. }
  805. // If the text doesnt fit inside the visible portion of the span,
  806. // anchor it to the inside right place in the span.
  807. return [1, right_inside];
  808. }
  809. // While we have space on the right, place the text there
  810. if (space_right > 0) {
  811. return [0, right_outside];
  812. }
  813. // If text fits inside the span
  814. if (full_span_px_width > width) {
  815. const distance = span_right - this.trace_view.right;
  816. const visible_width =
  817. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  818. // If the text fits inside the visible portion of the span, anchor it to the right
  819. // side of the window so that it is visible while the user pans the view
  820. if (visible_width - TEXT_PADDING >= width) {
  821. return [1, window_right];
  822. }
  823. // If the text doesnt fit inside the visible portion of the span,
  824. // anchor it to the inside left of the span
  825. return [1, left_inside];
  826. }
  827. return [0, right_outside];
  828. }
  829. draw(options: {list?: number; span_list?: number} = {}) {
  830. const list_width = options.list ?? this.columns.list.width;
  831. const span_list_width = options.span_list ?? this.columns.span_list.width;
  832. if (this.divider) {
  833. this.divider.style.transform = `translateX(${
  834. list_width * this.container_physical_space.width - DIVIDER_WIDTH / 2 - 1
  835. }px)`;
  836. }
  837. if (this.indicator_container) {
  838. this.indicator_container.style.width = span_list_width * 100 + '%';
  839. }
  840. const listWidth = list_width * 100 + '%';
  841. const spanWidth = span_list_width * 100 + '%';
  842. // JavaScript "arrays" are nice in the sense that they are really just dicts,
  843. // allowing us to store negative indices. This sometimes happens as the list
  844. // virtualizes the rows and we end up with a negative index as they are being
  845. // rendered off screen.
  846. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  847. while (this.span_bars[i] === undefined && i < this.columns.list.column_refs.length)
  848. i++;
  849. const list = this.columns.list.column_refs[i];
  850. if (list) list.style.width = listWidth;
  851. const span = this.columns.span_list.column_refs[i];
  852. if (span) span.style.width = spanWidth;
  853. const span_bar = this.span_bars[i];
  854. const span_arrow = this.span_arrows[i];
  855. if (span_bar) {
  856. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  857. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  858. }
  859. const span_text = this.span_text[i];
  860. if (span_text) {
  861. const [inside, text_transform] = this.computeSpanTextPlacement(
  862. span_text.space,
  863. span_text.text
  864. );
  865. if (text_transform === null) {
  866. continue;
  867. }
  868. span_text.ref.style.color = inside ? 'white' : '';
  869. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  870. if (span_arrow && span_bar) {
  871. const outside_left =
  872. span_bar.space[0] - this.to_origin + span_bar.space[1] < this.trace_view.x;
  873. const outside_right =
  874. span_bar.space[0] - this.to_origin > this.trace_view.right;
  875. const visible = outside_left || outside_right;
  876. if (visible !== span_arrow.visible) {
  877. span_arrow.visible = visible;
  878. span_arrow.position = outside_left ? 0 : 1;
  879. if (visible) {
  880. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  881. } else {
  882. span_arrow.ref.className = 'TraceArrow';
  883. }
  884. }
  885. }
  886. }
  887. }
  888. for (let i = 0; i < this.invisible_bars.length; i++) {
  889. const invisible_bar = this.invisible_bars[i];
  890. if (invisible_bar) {
  891. invisible_bar.ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(invisible_bar.space[0])}px)`;
  892. }
  893. }
  894. let start_indicator = 0;
  895. let end_indicator = this.indicators.length;
  896. while (start_indicator < this.indicators.length - 1) {
  897. const indicator = this.indicators[start_indicator];
  898. if (!indicator?.indicator) {
  899. start_indicator++;
  900. continue;
  901. }
  902. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  903. start_indicator++;
  904. continue;
  905. }
  906. break;
  907. }
  908. while (end_indicator > start_indicator) {
  909. const last_indicator = this.indicators[end_indicator - 1];
  910. if (!last_indicator) {
  911. end_indicator--;
  912. continue;
  913. }
  914. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  915. end_indicator--;
  916. continue;
  917. }
  918. break;
  919. }
  920. start_indicator = Math.max(0, start_indicator - 1);
  921. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  922. for (let i = 0; i < this.indicators.length; i++) {
  923. const entry = this.indicators[i];
  924. if (!entry) {
  925. continue;
  926. }
  927. if (i < start_indicator || i > end_indicator) {
  928. entry.ref.style.opacity = '0';
  929. continue;
  930. }
  931. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  932. const label = entry.ref.children[0] as HTMLElement | undefined;
  933. const indicator_max = this.trace_physical_space.width + 1;
  934. const indicator_min = -1;
  935. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  936. const clamped_transform = clamp(transform, -1, indicator_max);
  937. if (label_width === undefined) {
  938. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  939. continue;
  940. }
  941. if (label) {
  942. const PADDING = 2;
  943. const label_window_left = PADDING;
  944. const label_window_right = -label_width - PADDING;
  945. if (transform < -1) {
  946. label.style.transform = `translateX(${label_window_left}px)`;
  947. } else if (transform >= indicator_max) {
  948. label.style.transform = `translateX(${label_window_right}px)`;
  949. } else {
  950. const space_left = transform - PADDING - label_width / 2;
  951. const space_right = transform + label_width / 2;
  952. if (space_left < 0) {
  953. const left = -label_width / 2 + Math.abs(space_left);
  954. label.style.transform = `translateX(${left - 1}px)`;
  955. } else if (space_right > this.trace_physical_space.width) {
  956. const right =
  957. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  958. label.style.transform = `translateX(${right}px)`;
  959. } else {
  960. label.style.transform = `translateX(${-label_width / 2}px)`;
  961. }
  962. }
  963. }
  964. entry.ref.style.opacity = '1';
  965. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  966. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  967. }
  968. for (let i = 0; i < this.timeline_indicators.length; i++) {
  969. const indicator = this.timeline_indicators[i];
  970. const interval = this.intervals[i];
  971. if (indicator) {
  972. if (interval === undefined) {
  973. indicator.style.opacity = '0';
  974. continue;
  975. }
  976. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  977. indicator.style.opacity = '1';
  978. indicator.style.transform = `translateX(${placement}px)`;
  979. const label = indicator.children[0] as HTMLElement | undefined;
  980. if (label) {
  981. label.textContent = getDuration(interval / 1000, 2, true);
  982. }
  983. }
  984. }
  985. }
  986. teardown() {
  987. if (this.resize_observer) {
  988. this.resize_observer.disconnect();
  989. }
  990. }
  991. }
  992. // The backing cache should be a proper LRU cache,
  993. // so we dont end up storing an infinite amount of elements
  994. class DOMWidthMeasurer<T> {
  995. cache: Map<T, number> = new Map();
  996. elements: HTMLElement[] = [];
  997. queue: [T, HTMLElement][] = [];
  998. drainRaf: number | null = null;
  999. max: number = 0;
  1000. constructor() {
  1001. this.drain = this.drain.bind(this);
  1002. }
  1003. enqueueMeasure(node: T, element: HTMLElement) {
  1004. if (this.cache.has(node)) {
  1005. return;
  1006. }
  1007. this.queue.push([node, element]);
  1008. if (this.drainRaf !== null) {
  1009. window.cancelAnimationFrame(this.drainRaf);
  1010. }
  1011. this.drainRaf = window.requestAnimationFrame(this.drain);
  1012. }
  1013. drain() {
  1014. for (const [node, element] of this.queue) {
  1015. this.measure(node, element);
  1016. }
  1017. }
  1018. measure(node: T, element: HTMLElement): number {
  1019. const cache = this.cache.get(node);
  1020. if (cache !== undefined) {
  1021. return cache;
  1022. }
  1023. const width = element.getBoundingClientRect().width;
  1024. if (width > this.max) {
  1025. this.max = width;
  1026. }
  1027. this.cache.set(node, width);
  1028. return width;
  1029. }
  1030. }
  1031. // The backing cache should be a proper LRU cache,
  1032. // so we dont end up storing an infinite amount of elements
  1033. class TextMeasurer {
  1034. queue: string[] = [];
  1035. drainRaf: number | null = null;
  1036. cache: Map<string, number> = new Map();
  1037. ctx: CanvasRenderingContext2D;
  1038. number: number = 0;
  1039. dot: number = 0;
  1040. duration: Record<string, number> = {};
  1041. constructor() {
  1042. this.drain = this.drain.bind(this);
  1043. const canvas = document.createElement('canvas');
  1044. const ctx = canvas.getContext('2d');
  1045. if (!ctx) {
  1046. throw new Error('Canvas 2d context is not available');
  1047. }
  1048. canvas.width = 50 * window.devicePixelRatio ?? 1;
  1049. canvas.height = 50 * window.devicePixelRatio ?? 1;
  1050. this.ctx = ctx;
  1051. ctx.font = '11px' + theme.text.family;
  1052. this.dot = this.ctx.measureText('.').width;
  1053. for (let i = 0; i < 10; i++) {
  1054. const measurement = this.ctx.measureText(i.toString());
  1055. this.number = Math.max(this.number, measurement.width);
  1056. }
  1057. for (const duration of ['ns', 'ms', 's', 'm', 'h', 'd']) {
  1058. this.duration[duration] = this.ctx.measureText(duration).width;
  1059. }
  1060. }
  1061. drain() {
  1062. for (const string of this.queue) {
  1063. this.measure(string);
  1064. }
  1065. }
  1066. computeStringLength(string: string): number {
  1067. let width = 0;
  1068. for (let i = 0; i < string.length; i++) {
  1069. switch (string[i]) {
  1070. case '.':
  1071. width += this.dot;
  1072. break;
  1073. case '0':
  1074. case '1':
  1075. case '2':
  1076. case '3':
  1077. case '4':
  1078. case '5':
  1079. case '6':
  1080. case '7':
  1081. case '8':
  1082. case '9':
  1083. width += this.number;
  1084. break;
  1085. default:
  1086. const remaining = string.slice(i);
  1087. if (this.duration[remaining]) {
  1088. width += this.duration[remaining];
  1089. return width;
  1090. }
  1091. }
  1092. }
  1093. return width;
  1094. }
  1095. measure(string: string): number {
  1096. const cached_width = this.cache.get(string);
  1097. if (cached_width !== undefined) {
  1098. return cached_width;
  1099. }
  1100. const width = this.computeStringLength(string);
  1101. this.cache.set(string, width);
  1102. return width;
  1103. }
  1104. }
  1105. export class VirtualizedList {
  1106. container: HTMLElement | null = null;
  1107. scrollHeight: number = 0;
  1108. scrollTop: number = 0;
  1109. scrollToRow(index: number, rowHeight: number = 24) {
  1110. if (!this.container) {
  1111. return;
  1112. }
  1113. const top = this.container.scrollTop;
  1114. const height = this.scrollHeight;
  1115. const position = index * rowHeight;
  1116. if (position < top) {
  1117. // above view
  1118. } else if (position > top + height) {
  1119. // under view
  1120. } else {
  1121. return;
  1122. }
  1123. this.container.scrollTop = index * rowHeight;
  1124. }
  1125. }
  1126. interface UseVirtualizedListProps {
  1127. container: HTMLElement | null;
  1128. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1129. manager: VirtualizedViewManager;
  1130. render: (item: VirtualizedRow) => React.ReactNode;
  1131. }
  1132. interface UseVirtualizedListResult {
  1133. list: VirtualizedList;
  1134. rendered: React.ReactNode[];
  1135. virtualized: VirtualizedRow[];
  1136. }
  1137. export const useVirtualizedList = (
  1138. props: UseVirtualizedListProps
  1139. ): UseVirtualizedListResult => {
  1140. const list = useRef<VirtualizedList | null>();
  1141. const scrollTopRef = useRef<number>(0);
  1142. const scrollHeightRef = useRef<number>(0);
  1143. const scrollContainerRef = useRef<HTMLElement | null>(null);
  1144. const renderCache = useRef<Map<number, React.ReactNode>>();
  1145. const styleCache = useRef<Map<number, React.CSSProperties>>();
  1146. const resizeObserverRef = useRef<ResizeObserver | null>(null);
  1147. if (!styleCache.current) {
  1148. styleCache.current = new Map();
  1149. }
  1150. if (!renderCache.current) {
  1151. renderCache.current = new Map();
  1152. }
  1153. const [items, setItems] = useState<{
  1154. rendered: React.ReactNode[];
  1155. virtualized: VirtualizedRow[];
  1156. }>({rendered: [], virtualized: []});
  1157. if (!list.current) {
  1158. list.current = new VirtualizedList();
  1159. props.manager.registerList(list.current);
  1160. }
  1161. const renderRef = useRef<(item: VirtualizedRow) => React.ReactNode>(props.render);
  1162. renderRef.current = props.render;
  1163. const itemsRef = useRef<ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>>(props.items);
  1164. itemsRef.current = props.items;
  1165. const managerRef = useRef<VirtualizedViewManager>(props.manager);
  1166. managerRef.current = props.manager;
  1167. useLayoutEffect(() => {
  1168. if (!props.container) {
  1169. return;
  1170. }
  1171. const scrollContainer = props.container.children[0] as HTMLElement | null;
  1172. if (!scrollContainer) {
  1173. throw new Error(
  1174. 'Virtualized list container has to render a scroll container as its first child.'
  1175. );
  1176. }
  1177. }, [props.container, props.items.length]);
  1178. useLayoutEffect(() => {
  1179. if (!props.container || !list.current) {
  1180. return;
  1181. }
  1182. list.current.container = props.container;
  1183. if (resizeObserverRef.current) {
  1184. resizeObserverRef.current.disconnect();
  1185. }
  1186. const resizeObserver = new ResizeObserver(elements => {
  1187. // We only care about changes to the height of the scroll container,
  1188. // if it has not changed then do not update the scroll height.
  1189. styleCache.current?.clear();
  1190. renderCache.current?.clear();
  1191. scrollHeightRef.current = elements[0].contentRect.height;
  1192. console.log('resize', elements);
  1193. if (list.current) {
  1194. list.current.scrollHeight = scrollHeightRef.current;
  1195. }
  1196. const recomputedItems = findRenderedItems({
  1197. scrollTop: scrollTopRef.current,
  1198. items: itemsRef.current,
  1199. overscroll: 5,
  1200. rowHeight: 24,
  1201. scrollHeight: scrollHeightRef.current,
  1202. styleCache: styleCache.current!,
  1203. renderCache: renderCache.current!,
  1204. render: renderRef.current,
  1205. manager: managerRef.current,
  1206. });
  1207. setItems(recomputedItems);
  1208. });
  1209. resizeObserver.observe(props.container);
  1210. resizeObserverRef.current = resizeObserver;
  1211. }, [props.container]);
  1212. const rafId = useRef<number | null>(null);
  1213. const pointerEventsRaf = useRef<{id: number} | null>(null);
  1214. useLayoutEffect(() => {
  1215. if (!list.current || !props.container) {
  1216. return undefined;
  1217. }
  1218. if (props.container && !scrollContainerRef.current) {
  1219. scrollContainerRef.current = props.container.children[0] as HTMLElement | null;
  1220. }
  1221. props.container.style.height = '100%';
  1222. props.container.style.overflow = 'auto';
  1223. props.container.style.position = 'relative';
  1224. props.container.style.willChange = 'transform';
  1225. props.container.style.overscrollBehavior = 'none';
  1226. scrollContainerRef.current!.style.overflow = 'hidden';
  1227. scrollContainerRef.current!.style.position = 'relative';
  1228. scrollContainerRef.current!.style.willChange = 'transform';
  1229. scrollContainerRef.current!.style.height = `${props.items.length * 24}px`;
  1230. const onScroll = event => {
  1231. if (!list.current) {
  1232. return;
  1233. }
  1234. if (rafId.current !== null) {
  1235. window.cancelAnimationFrame(rafId.current);
  1236. }
  1237. managerRef.current.isScrolling = true;
  1238. rafId.current = window.requestAnimationFrame(() => {
  1239. scrollTopRef.current = Math.max(0, event.target?.scrollTop ?? 0);
  1240. const recomputedItems = findRenderedItems({
  1241. scrollTop: scrollTopRef.current,
  1242. items: props.items,
  1243. overscroll: 5,
  1244. rowHeight: 24,
  1245. scrollHeight: scrollHeightRef.current,
  1246. styleCache: styleCache.current!,
  1247. renderCache: renderCache.current!,
  1248. render: renderRef.current,
  1249. manager: managerRef.current,
  1250. });
  1251. setItems(recomputedItems);
  1252. });
  1253. if (!pointerEventsRaf.current && scrollContainerRef.current) {
  1254. scrollContainerRef.current.style.pointerEvents = 'none';
  1255. }
  1256. if (pointerEventsRaf.current) {
  1257. window.cancelAnimationFrame(pointerEventsRaf.current.id);
  1258. }
  1259. pointerEventsRaf.current = requestAnimationTimeout(() => {
  1260. styleCache.current?.clear();
  1261. renderCache.current?.clear();
  1262. managerRef.current.isScrolling = false;
  1263. const recomputedItems = findRenderedItems({
  1264. scrollTop: scrollTopRef.current,
  1265. items: props.items,
  1266. overscroll: 5,
  1267. rowHeight: 24,
  1268. scrollHeight: scrollHeightRef.current,
  1269. styleCache: styleCache.current!,
  1270. renderCache: renderCache.current!,
  1271. render: renderRef.current,
  1272. manager: managerRef.current,
  1273. });
  1274. setItems(recomputedItems);
  1275. if (list.current && scrollContainerRef.current) {
  1276. scrollContainerRef.current.style.pointerEvents = 'auto';
  1277. pointerEventsRaf.current = null;
  1278. }
  1279. }, 150);
  1280. };
  1281. props.container.addEventListener('scroll', onScroll, {passive: false});
  1282. return () => {
  1283. props.container?.removeEventListener('scroll', onScroll);
  1284. };
  1285. }, [props.container, props.items, props.items.length]);
  1286. useLayoutEffect(() => {
  1287. if (!list.current || !styleCache.current || !renderCache.current) {
  1288. return;
  1289. }
  1290. styleCache.current.clear();
  1291. renderCache.current.clear();
  1292. const recomputedItems = findRenderedItems({
  1293. scrollTop: scrollTopRef.current,
  1294. items: props.items,
  1295. overscroll: 5,
  1296. rowHeight: 24,
  1297. scrollHeight: scrollHeightRef.current,
  1298. styleCache: styleCache.current!,
  1299. renderCache: renderCache.current,
  1300. render: renderRef.current,
  1301. manager: managerRef.current,
  1302. });
  1303. setItems(recomputedItems);
  1304. }, [props.items, props.items.length, props.render]);
  1305. return {
  1306. virtualized: items.virtualized,
  1307. rendered: items.rendered,
  1308. list: list.current!,
  1309. };
  1310. };
  1311. export interface VirtualizedRow {
  1312. index: number;
  1313. item: TraceTreeNode<TraceTree.NodeValue>;
  1314. key: number;
  1315. style: React.CSSProperties;
  1316. }
  1317. function findRenderedItems({
  1318. items,
  1319. overscroll,
  1320. rowHeight,
  1321. scrollHeight,
  1322. scrollTop,
  1323. styleCache,
  1324. renderCache,
  1325. render,
  1326. manager,
  1327. }: {
  1328. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1329. manager: VirtualizedViewManager;
  1330. overscroll: number;
  1331. render: (arg: VirtualizedRow) => React.ReactNode;
  1332. renderCache: Map<number, React.ReactNode>;
  1333. rowHeight: number;
  1334. scrollHeight: number;
  1335. scrollTop: number;
  1336. styleCache: Map<number, React.CSSProperties>;
  1337. }): {rendered: React.ReactNode[]; virtualized: VirtualizedRow[]} {
  1338. // This is overscroll height for single direction, when computing the total,
  1339. // we need to multiply this by 2 because we overscroll in both directions.
  1340. const OVERSCROLL_HEIGHT = overscroll * rowHeight;
  1341. const virtualized: VirtualizedRow[] = [];
  1342. const rendered: React.ReactNode[] = [];
  1343. // Clamp viewport to scrollHeight bounds [0, length * rowHeight] because some browsers may fire
  1344. // scrollTop with negative values when the user scrolls up past the top of the list (overscroll behavior)
  1345. const viewport = {
  1346. top: Math.max(scrollTop - OVERSCROLL_HEIGHT, 0),
  1347. bottom: Math.min(
  1348. scrollTop + scrollHeight + OVERSCROLL_HEIGHT,
  1349. items.length * rowHeight
  1350. ),
  1351. };
  1352. // Points to the position inside the visible array
  1353. let visibleItemIndex = 0;
  1354. // Points to the currently iterated item
  1355. let indexPointer = findOptimisticStartIndex({
  1356. items,
  1357. viewport,
  1358. scrollTop,
  1359. rowHeight,
  1360. overscroll,
  1361. });
  1362. manager.start_virtualized_index = indexPointer;
  1363. // Max number of visible items in our list
  1364. const MAX_VISIBLE_ITEMS = Math.ceil((scrollHeight + OVERSCROLL_HEIGHT * 2) / rowHeight);
  1365. const ALL_ITEMS = items.length;
  1366. // While number of visible items is less than max visible items, and we haven't reached the end of the list
  1367. while (visibleItemIndex < MAX_VISIBLE_ITEMS && indexPointer < ALL_ITEMS) {
  1368. const elementTop = indexPointer * rowHeight;
  1369. const elementBottom = elementTop + rowHeight;
  1370. // An element is inside a viewport if the top of the element is below the top of the viewport
  1371. // and the bottom of the element is above the bottom of the viewport
  1372. if (elementTop >= viewport.top && elementBottom <= viewport.bottom) {
  1373. let style = styleCache.get(indexPointer);
  1374. if (!style) {
  1375. style = {position: 'absolute', top: elementTop};
  1376. styleCache.set(indexPointer, style);
  1377. }
  1378. const virtualizedRow: VirtualizedRow = {
  1379. key: indexPointer,
  1380. style,
  1381. index: indexPointer,
  1382. item: items[indexPointer],
  1383. };
  1384. virtualized[visibleItemIndex] = virtualizedRow;
  1385. const renderedRow = renderCache.get(indexPointer) || render(virtualizedRow);
  1386. rendered[visibleItemIndex] = renderedRow;
  1387. renderCache.set(indexPointer, renderedRow);
  1388. visibleItemIndex++;
  1389. }
  1390. indexPointer++;
  1391. }
  1392. return {rendered, virtualized};
  1393. }
  1394. export function findOptimisticStartIndex({
  1395. items,
  1396. overscroll,
  1397. rowHeight,
  1398. scrollTop,
  1399. viewport,
  1400. }: {
  1401. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1402. overscroll: number;
  1403. rowHeight: number;
  1404. scrollTop: number;
  1405. viewport: {bottom: number; top: number};
  1406. }): number {
  1407. if (!items.length || viewport.top === 0) {
  1408. return 0;
  1409. }
  1410. return Math.max(Math.floor(scrollTop / rowHeight) - overscroll, 0);
  1411. }
  1412. function findInTreeFromSegment(
  1413. start: TraceTreeNode<TraceTree.NodeValue>,
  1414. segment: TraceTree.NodePath
  1415. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1416. const [type, id] = segment.split(':');
  1417. if (!type || !id) {
  1418. throw new TypeError('Node path must be in the format of `type:id`');
  1419. }
  1420. return TraceTreeNode.Find(start, node => {
  1421. if (type === 'txn' && isTransactionNode(node)) {
  1422. return node.value.event_id === id;
  1423. }
  1424. if (type === 'span' && isSpanNode(node)) {
  1425. return node.value.span_id === id;
  1426. }
  1427. if (type === 'ag' && isAutogroupedNode(node)) {
  1428. if (isParentAutogroupedNode(node)) {
  1429. return node.head.value.span_id === id || node.tail.value.span_id === id;
  1430. }
  1431. if (isSiblingAutogroupedNode(node)) {
  1432. const child = node.children[0];
  1433. if (isSpanNode(child)) {
  1434. return child.value.span_id === id;
  1435. }
  1436. }
  1437. }
  1438. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1439. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1440. }
  1441. if (type === 'error' && isTraceErrorNode(node)) {
  1442. return node.value.event_id === id;
  1443. }
  1444. return false;
  1445. });
  1446. }