virtualizedViewManager.tsx 67 KB

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