virtualizedViewManager.tsx 59 KB

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