virtualizedViewManager.tsx 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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. rerender();
  1009. throw new Error(`Couldn't find node in list ${scrollQueue.join(',')}`);
  1010. }
  1011. rerender();
  1012. this.scrollToRow(index);
  1013. return {index, node: current};
  1014. };
  1015. return scrollToRow();
  1016. }
  1017. scrollToRow(index: number) {
  1018. if (!this.list) {
  1019. return;
  1020. }
  1021. this.list.scrollToRow(index);
  1022. }
  1023. computeTransformXFromTimestamp(timestamp: number): number {
  1024. return (timestamp - this.to_origin - this.trace_view.x) / this.span_to_px[0];
  1025. }
  1026. computeSpanTextPlacement(span_space: [number, number], text: string): [number, number] {
  1027. const TEXT_PADDING = 2;
  1028. const anchor_left = span_space[0] > this.to_origin + this.trace_space.width * 0.8;
  1029. const width = this.text_measurer.measure(text);
  1030. // precompute all anchor points aot, so we make the control flow more readable.
  1031. // this wastes some cycles, but it's not a big deal as computers are fast when
  1032. // it comes to simple arithmetic.
  1033. const right_outside =
  1034. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) + TEXT_PADDING;
  1035. const right_inside =
  1036. this.computeTransformXFromTimestamp(span_space[0] + span_space[1]) -
  1037. width -
  1038. TEXT_PADDING;
  1039. const left_outside =
  1040. this.computeTransformXFromTimestamp(span_space[0]) - TEXT_PADDING - width;
  1041. const left_inside = this.computeTransformXFromTimestamp(span_space[0]) + TEXT_PADDING;
  1042. const window_right =
  1043. this.computeTransformXFromTimestamp(
  1044. this.to_origin + this.trace_view.left + this.trace_view.width
  1045. ) -
  1046. width -
  1047. TEXT_PADDING;
  1048. const window_left =
  1049. this.computeTransformXFromTimestamp(this.to_origin + this.trace_view.left) +
  1050. TEXT_PADDING;
  1051. const view_left = this.trace_view.x;
  1052. const view_right = view_left + this.trace_view.width;
  1053. const span_left = span_space[0] - this.to_origin;
  1054. const span_right = span_left + span_space[1];
  1055. const space_right = view_right - span_right;
  1056. const space_left = span_left - view_left;
  1057. // Span is completely outside of the view on the left side
  1058. if (span_right < this.trace_view.x) {
  1059. return anchor_left ? [1, right_inside] : [0, right_outside];
  1060. }
  1061. // Span is completely outside of the view on the right side
  1062. if (span_left > this.trace_view.right) {
  1063. return anchor_left ? [0, left_outside] : [1, left_inside];
  1064. }
  1065. // Span "spans" the entire view
  1066. if (span_left <= this.trace_view.x && span_right >= this.trace_view.right) {
  1067. return anchor_left ? [1, window_left] : [1, window_right];
  1068. }
  1069. const full_span_px_width = span_space[1] / this.span_to_px[0];
  1070. if (anchor_left) {
  1071. // While we have space on the left, place the text there
  1072. if (space_left > 0) {
  1073. return [0, left_outside];
  1074. }
  1075. const distance = span_right - this.trace_view.left;
  1076. const visible_width = distance / this.span_to_px[0] - TEXT_PADDING;
  1077. // If the text fits inside the visible portion of the span, anchor it to the left
  1078. // side of the window so that it is visible while the user pans the view
  1079. if (visible_width - TEXT_PADDING >= width) {
  1080. return [1, window_left];
  1081. }
  1082. // If the text doesnt fit inside the visible portion of the span,
  1083. // anchor it to the inside right place in the span.
  1084. return [1, right_inside];
  1085. }
  1086. // While we have space on the right, place the text there
  1087. if (space_right > 0) {
  1088. if (
  1089. // If the right edge of the span is within 10% to the right edge of the space,
  1090. // try and fit the text inside the span if possible. In case the span is too short
  1091. // to fit the text, anchor_left case above will take care of anchoring it to the left
  1092. // of the view.
  1093. // Note: the accurate way for us to determine if the text fits to the right side
  1094. // of the view would have been to compute the scaling matrix for a non zoomed view at 0,0
  1095. // origin and check if it fits into the distance of space right edge - span right edge. In practice
  1096. // however, it seems that a magical number works just fine.
  1097. span_right > this.trace_space.right * 0.9 &&
  1098. space_right / this.span_to_px[0] < width
  1099. ) {
  1100. return [1, right_inside];
  1101. }
  1102. return [0, right_outside];
  1103. }
  1104. // If text fits inside the span
  1105. if (full_span_px_width > width) {
  1106. const distance = span_right - this.trace_view.right;
  1107. const visible_width =
  1108. (span_space[1] - distance) / this.span_to_px[0] - TEXT_PADDING;
  1109. // If the text fits inside the visible portion of the span, anchor it to the right
  1110. // side of the window so that it is visible while the user pans the view
  1111. if (visible_width - TEXT_PADDING >= width) {
  1112. return [1, window_right];
  1113. }
  1114. // If the text doesnt fit inside the visible portion of the span,
  1115. // anchor it to the inside left of the span
  1116. return [1, left_inside];
  1117. }
  1118. return [0, right_outside];
  1119. }
  1120. draw(options: {list?: number; span_list?: number} = {}) {
  1121. const list_width = options.list ?? this.columns.list.width;
  1122. const span_list_width = options.span_list ?? this.columns.span_list.width;
  1123. if (this.divider) {
  1124. this.divider.style.setProperty(
  1125. '--translate-x',
  1126. // @ts-expect-error we set number value type on purpose
  1127. Math.round(
  1128. (list_width * (this.container_physical_space.width - this.scrollbar_width) -
  1129. DIVIDER_WIDTH / 2 -
  1130. 1) *
  1131. 10
  1132. ) / 10
  1133. );
  1134. }
  1135. if (this.indicator_container) {
  1136. const correction =
  1137. (this.scrollbar_width / this.container_physical_space.width) * span_list_width;
  1138. // @ts-expect-error we set number value type on purpose
  1139. this.indicator_container.style.setProperty('--translate-x', -this.scrollbar_width);
  1140. this.indicator_container.style.width = (span_list_width - correction) * 100 + '%';
  1141. }
  1142. if (this.container) {
  1143. this.container.style.setProperty(
  1144. '--list-column-width',
  1145. // @ts-expect-error we set number value type on purpose
  1146. Math.round(list_width * 1000) / 1000
  1147. );
  1148. this.container.style.setProperty(
  1149. '--span-column-width',
  1150. // @ts-expect-error we set number value type on purpose
  1151. Math.round(span_list_width * 1000) / 1000
  1152. );
  1153. }
  1154. for (let i = 0; i < this.columns.list.column_refs.length; i++) {
  1155. const span_bar = this.span_bars[i];
  1156. const span_arrow = this.span_arrows[i];
  1157. if (span_bar) {
  1158. const span_transform = this.computeSpanCSSMatrixTransform(span_bar.space);
  1159. span_bar.ref.style.transform = `matrix(${span_transform.join(',')}`;
  1160. span_bar.ref.style.setProperty(
  1161. '--inverse-span-scale',
  1162. 1 / span_transform[0] + ''
  1163. );
  1164. }
  1165. const span_text = this.span_text[i];
  1166. if (span_text) {
  1167. const [inside, text_transform] = this.computeSpanTextPlacement(
  1168. span_text.space,
  1169. span_text.text
  1170. );
  1171. if (text_transform === null) {
  1172. continue;
  1173. }
  1174. span_text.ref.style.color = inside ? 'white' : '';
  1175. span_text.ref.style.transform = `translateX(${text_transform}px)`;
  1176. if (span_arrow && span_bar) {
  1177. const outside_left =
  1178. span_bar.space[0] - this.to_origin + span_bar.space[1] < this.trace_view.x;
  1179. const outside_right =
  1180. span_bar.space[0] - this.to_origin > this.trace_view.right;
  1181. const visible = outside_left || outside_right;
  1182. if (visible !== span_arrow.visible) {
  1183. span_arrow.visible = visible;
  1184. span_arrow.position = outside_left ? 0 : 1;
  1185. if (visible) {
  1186. span_arrow.ref.className = `TraceArrow Visible ${span_arrow.position === 0 ? 'Left' : 'Right'}`;
  1187. } else {
  1188. span_arrow.ref.className = 'TraceArrow';
  1189. }
  1190. }
  1191. }
  1192. }
  1193. }
  1194. for (let i = 0; i < this.invisible_bars.length; i++) {
  1195. const invisible_bar = this.invisible_bars[i];
  1196. if (invisible_bar) {
  1197. invisible_bar.ref.style.transform = `translateX(${this.computeTransformXFromTimestamp(invisible_bar.space[0])}px)`;
  1198. }
  1199. }
  1200. let start_indicator = 0;
  1201. let end_indicator = this.indicators.length;
  1202. while (start_indicator < this.indicators.length - 1) {
  1203. const indicator = this.indicators[start_indicator];
  1204. if (!indicator?.indicator) {
  1205. start_indicator++;
  1206. continue;
  1207. }
  1208. if (indicator.indicator.start < this.to_origin + this.trace_view.left) {
  1209. start_indicator++;
  1210. continue;
  1211. }
  1212. break;
  1213. }
  1214. while (end_indicator > start_indicator) {
  1215. const last_indicator = this.indicators[end_indicator - 1];
  1216. if (!last_indicator) {
  1217. end_indicator--;
  1218. continue;
  1219. }
  1220. if (last_indicator.indicator.start > this.to_origin + this.trace_view.right) {
  1221. end_indicator--;
  1222. continue;
  1223. }
  1224. break;
  1225. }
  1226. start_indicator = Math.max(0, start_indicator - 1);
  1227. end_indicator = Math.min(this.indicators.length - 1, end_indicator);
  1228. for (let i = 0; i < this.indicators.length; i++) {
  1229. const entry = this.indicators[i];
  1230. if (!entry) {
  1231. continue;
  1232. }
  1233. if (i < start_indicator || i > end_indicator) {
  1234. entry.ref.style.opacity = '0';
  1235. continue;
  1236. }
  1237. const transform = this.computeTransformXFromTimestamp(entry.indicator.start);
  1238. const label = entry.ref.children[0] as HTMLElement | undefined;
  1239. const indicator_max = this.trace_physical_space.width + 1;
  1240. const indicator_min = -1;
  1241. const label_width = this.indicator_label_measurer.cache.get(entry.indicator);
  1242. const clamped_transform = clamp(transform, -1, indicator_max);
  1243. if (label_width === undefined) {
  1244. entry.ref.style.transform = `translate(${clamp(transform, indicator_min, indicator_max)}px, 0)`;
  1245. continue;
  1246. }
  1247. if (label) {
  1248. const PADDING = 2;
  1249. const label_window_left = PADDING;
  1250. const label_window_right = -label_width - PADDING;
  1251. if (transform < -1) {
  1252. label.style.transform = `translateX(${label_window_left}px)`;
  1253. } else if (transform >= indicator_max) {
  1254. label.style.transform = `translateX(${label_window_right}px)`;
  1255. } else {
  1256. const space_left = transform - PADDING - label_width / 2;
  1257. const space_right = transform + label_width / 2;
  1258. if (space_left < 0) {
  1259. const left = -label_width / 2 + Math.abs(space_left);
  1260. label.style.transform = `translateX(${left - 1}px)`;
  1261. } else if (space_right > this.trace_physical_space.width) {
  1262. const right =
  1263. -label_width / 2 - (space_right - this.trace_physical_space.width) - 1;
  1264. label.style.transform = `translateX(${right}px)`;
  1265. } else {
  1266. label.style.transform = `translateX(${-label_width / 2}px)`;
  1267. }
  1268. }
  1269. }
  1270. entry.ref.style.opacity = '1';
  1271. entry.ref.style.zIndex = i === start_indicator || i === end_indicator ? '1' : '2';
  1272. entry.ref.style.transform = `translate(${clamped_transform}px, 0)`;
  1273. }
  1274. // Renders timeline indicators and labels
  1275. for (let i = 0; i < this.timeline_indicators.length; i++) {
  1276. const indicator = this.timeline_indicators[i];
  1277. // Special case for when the timeline is empty - we want to show the first and last
  1278. // timeline indicators as 0ms instead of just a single 0ms indicator as it gives better
  1279. // context to the user that start and end are both 0ms. If we were to draw a single 0ms
  1280. // indicator, it leaves ambiguity for the user to think that the end might be missing
  1281. if (i === 0 && this.intervals[0] === 0 && this.intervals[1] === 0) {
  1282. const first = this.timeline_indicators[0];
  1283. const last = this.timeline_indicators[1];
  1284. if (first && last) {
  1285. first.style.opacity = '1';
  1286. last.style.opacity = '1';
  1287. first.style.transform = `translateX(0)`;
  1288. // 43 px offset is the width of a 0.00ms label, since we usually anchor the label to the right
  1289. // side of the indicator, we need to offset it by the width of the label to make it look like
  1290. // it is at the end of the timeline
  1291. last.style.transform = `translateX(${this.trace_physical_space.width - 43}px)`;
  1292. const firstLabel = first.children[0] as HTMLElement | undefined;
  1293. if (firstLabel) {
  1294. firstLabel.textContent = '0.00ms';
  1295. }
  1296. const lastLabel = last.children[0] as HTMLElement | undefined;
  1297. const lastLine = last.children[1] as HTMLElement | undefined;
  1298. if (lastLine && lastLabel) {
  1299. lastLabel.textContent = '0.00ms';
  1300. lastLine.style.opacity = '0';
  1301. i = 1;
  1302. }
  1303. continue;
  1304. }
  1305. }
  1306. if (indicator) {
  1307. const interval = this.intervals[i];
  1308. if (interval === undefined) {
  1309. indicator.style.opacity = '0';
  1310. continue;
  1311. }
  1312. const placement = this.computeTransformXFromTimestamp(this.to_origin + interval);
  1313. indicator.style.opacity = '1';
  1314. indicator.style.transform = `translateX(${placement}px)`;
  1315. const label = indicator.children[0] as HTMLElement | undefined;
  1316. const duration = getDuration(interval / 1000, 2, true);
  1317. if (label && label?.textContent !== duration) {
  1318. label.textContent = duration;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. teardown() {
  1324. this.row_measurer.off('max', this.onNewMaxRowWidth);
  1325. if (this.resize_observer) {
  1326. this.resize_observer.disconnect();
  1327. }
  1328. }
  1329. }
  1330. // The backing cache should be a proper LRU cache,
  1331. // so we dont end up storing an infinite amount of elements
  1332. class DOMWidthMeasurer<T> {
  1333. cache: Map<T, number> = new Map();
  1334. queue: [T, HTMLElement][] = [];
  1335. drainRaf: number | null = null;
  1336. max: number = 0;
  1337. constructor() {
  1338. this.drain = this.drain.bind(this);
  1339. }
  1340. listeners: Record<'max', Set<(max: number) => void>> = {
  1341. max: new Set(),
  1342. };
  1343. on(event: 'max', cb: (max: number) => void) {
  1344. this.listeners?.[event]?.add?.(cb);
  1345. }
  1346. off(event: 'max', cb: (max: number) => void) {
  1347. this.listeners?.[event]?.delete?.(cb);
  1348. }
  1349. dispatch(max: number) {
  1350. for (const listener of this.listeners.max) {
  1351. listener(max);
  1352. }
  1353. }
  1354. enqueueMeasure(node: T, element: HTMLElement) {
  1355. if (this.cache.has(node)) {
  1356. return;
  1357. }
  1358. this.queue.push([node, element]);
  1359. if (this.drainRaf !== null) {
  1360. window.cancelAnimationFrame(this.drainRaf);
  1361. }
  1362. this.drainRaf = window.requestAnimationFrame(this.drain);
  1363. }
  1364. drain() {
  1365. while (this.queue.length > 0) {
  1366. const next = this.queue.pop()!;
  1367. const width = this.measure(next[0], next[1]);
  1368. if (width > this.max) {
  1369. this.max = width;
  1370. this.dispatch(this.max);
  1371. }
  1372. }
  1373. }
  1374. measure(node: T, element: HTMLElement): number {
  1375. const cache = this.cache.get(node);
  1376. if (cache !== undefined) {
  1377. return cache;
  1378. }
  1379. const rect = element.getBoundingClientRect();
  1380. this.cache.set(node, rect.width);
  1381. return rect.width;
  1382. }
  1383. }
  1384. // The backing cache should be a proper LRU cache,
  1385. // so we dont end up storing an infinite amount of elements
  1386. class TextMeasurer {
  1387. queue: string[] = [];
  1388. drainRaf: number | null = null;
  1389. cache: Map<string, number> = new Map();
  1390. ctx: CanvasRenderingContext2D;
  1391. number: number = 0;
  1392. dot: number = 0;
  1393. duration: Record<string, number> = {};
  1394. constructor() {
  1395. this.drain = this.drain.bind(this);
  1396. const canvas = document.createElement('canvas');
  1397. const ctx = canvas.getContext('2d');
  1398. if (!ctx) {
  1399. throw new Error('Canvas 2d context is not available');
  1400. }
  1401. canvas.width = 50 * window.devicePixelRatio ?? 1;
  1402. canvas.height = 50 * window.devicePixelRatio ?? 1;
  1403. this.ctx = ctx;
  1404. ctx.font = '11px' + theme.text.family;
  1405. this.dot = this.ctx.measureText('.').width;
  1406. for (let i = 0; i < 10; i++) {
  1407. const measurement = this.ctx.measureText(i.toString());
  1408. this.number = Math.max(this.number, measurement.width);
  1409. }
  1410. for (const duration of ['ns', 'ms', 's', 'm', 'min', 'h', 'd']) {
  1411. this.duration[duration] = this.ctx.measureText(duration).width;
  1412. }
  1413. }
  1414. drain() {
  1415. for (const string of this.queue) {
  1416. this.measure(string);
  1417. }
  1418. }
  1419. computeStringLength(string: string): number {
  1420. let width = 0;
  1421. for (let i = 0; i < string.length; i++) {
  1422. switch (string[i]) {
  1423. case '.':
  1424. width += this.dot;
  1425. break;
  1426. case '0':
  1427. case '1':
  1428. case '2':
  1429. case '3':
  1430. case '4':
  1431. case '5':
  1432. case '6':
  1433. case '7':
  1434. case '8':
  1435. case '9':
  1436. width += this.number;
  1437. break;
  1438. default:
  1439. const remaining = string.slice(i);
  1440. if (this.duration[remaining]) {
  1441. width += this.duration[remaining];
  1442. return width;
  1443. }
  1444. }
  1445. }
  1446. return width;
  1447. }
  1448. measure(string: string): number {
  1449. const cached_width = this.cache.get(string);
  1450. if (cached_width !== undefined) {
  1451. return cached_width;
  1452. }
  1453. const width = this.computeStringLength(string);
  1454. this.cache.set(string, width);
  1455. return width;
  1456. }
  1457. }
  1458. export class VirtualizedList {
  1459. container: HTMLElement | null = null;
  1460. scrollHeight: number = 0;
  1461. scrollTop: number = 0;
  1462. scrollToRow(index: number, anchor?: 'top') {
  1463. if (!this.container) {
  1464. return;
  1465. }
  1466. if (anchor === 'top') {
  1467. this.container.scrollTop = index * 24;
  1468. return;
  1469. }
  1470. const position = index * 24;
  1471. const top = this.container.scrollTop;
  1472. const height = this.scrollHeight;
  1473. if (position < top) {
  1474. // Row is above the view
  1475. this.container.scrollTop = index * 24;
  1476. } else if (position > top + height) {
  1477. // Row is under the view
  1478. this.container.scrollTop = index * 24 - height + 24;
  1479. } else {
  1480. return;
  1481. }
  1482. }
  1483. }
  1484. function maybeToggleScrollbar(
  1485. container: HTMLElement,
  1486. containerHeight: number,
  1487. scrollHeight: number,
  1488. manager: VirtualizedViewManager
  1489. ) {
  1490. if (scrollHeight > containerHeight) {
  1491. container.style.overflowY = 'scroll';
  1492. container.style.scrollbarGutter = 'stable';
  1493. manager.onScrollbarWidthChange(container.offsetWidth - container.clientWidth);
  1494. } else {
  1495. container.style.overflowY = 'auto';
  1496. container.style.scrollbarGutter = 'auto';
  1497. manager.onScrollbarWidthChange(0);
  1498. }
  1499. }
  1500. interface UseVirtualizedListProps {
  1501. container: HTMLElement | null;
  1502. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1503. manager: VirtualizedViewManager;
  1504. render: (item: VirtualizedRow) => React.ReactNode;
  1505. }
  1506. interface UseVirtualizedListResult {
  1507. list: VirtualizedList;
  1508. rendered: React.ReactNode[];
  1509. virtualized: VirtualizedRow[];
  1510. }
  1511. export const useVirtualizedList = (
  1512. props: UseVirtualizedListProps
  1513. ): UseVirtualizedListResult => {
  1514. const list = useRef<VirtualizedList | null>();
  1515. const scrollTopRef = useRef<number>(0);
  1516. const scrollHeightRef = useRef<number>(0);
  1517. const scrollContainerRef = useRef<HTMLElement | null>(null);
  1518. const renderCache = useRef<Map<number, React.ReactNode>>();
  1519. const styleCache = useRef<Map<number, React.CSSProperties>>();
  1520. const resizeObserverRef = useRef<ResizeObserver | null>(null);
  1521. if (!styleCache.current) {
  1522. styleCache.current = new Map();
  1523. }
  1524. if (!renderCache.current) {
  1525. renderCache.current = new Map();
  1526. }
  1527. const [items, setItems] = useState<{
  1528. rendered: React.ReactNode[];
  1529. virtualized: VirtualizedRow[];
  1530. }>({rendered: [], virtualized: []});
  1531. if (!list.current) {
  1532. list.current = new VirtualizedList();
  1533. props.manager.registerList(list.current);
  1534. }
  1535. const renderRef = useRef<(item: VirtualizedRow) => React.ReactNode>(props.render);
  1536. renderRef.current = props.render;
  1537. const itemsRef = useRef<ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>>(props.items);
  1538. itemsRef.current = props.items;
  1539. const managerRef = useRef<VirtualizedViewManager>(props.manager);
  1540. managerRef.current = props.manager;
  1541. useLayoutEffect(() => {
  1542. if (!props.container) {
  1543. return;
  1544. }
  1545. const scrollContainer = props.container.children[0] as HTMLElement | null;
  1546. if (!scrollContainer) {
  1547. throw new Error(
  1548. 'Virtualized list container has to render a scroll container as its first child.'
  1549. );
  1550. }
  1551. }, [props.container, props.items.length]);
  1552. useLayoutEffect(() => {
  1553. if (!props.container || !list.current) {
  1554. return;
  1555. }
  1556. list.current.container = props.container;
  1557. if (resizeObserverRef.current) {
  1558. resizeObserverRef.current.disconnect();
  1559. }
  1560. const resizeObserver = new ResizeObserver(elements => {
  1561. // We only care about changes to the height of the scroll container,
  1562. // if it has not changed then do not update the scroll height.
  1563. styleCache.current?.clear();
  1564. renderCache.current?.clear();
  1565. scrollHeightRef.current = elements[0].contentRect.height;
  1566. if (list.current) {
  1567. list.current.scrollHeight = scrollHeightRef.current;
  1568. }
  1569. maybeToggleScrollbar(
  1570. elements[0].target as HTMLElement,
  1571. scrollHeightRef.current,
  1572. itemsRef.current.length * 24,
  1573. managerRef.current
  1574. );
  1575. const recomputedItems = findRenderedItems({
  1576. scrollTop: scrollTopRef.current,
  1577. items: itemsRef.current,
  1578. overscroll: 5,
  1579. rowHeight: 24,
  1580. scrollHeight: scrollHeightRef.current,
  1581. styleCache: styleCache.current!,
  1582. renderCache: renderCache.current!,
  1583. render: renderRef.current,
  1584. manager: managerRef.current,
  1585. });
  1586. setItems(recomputedItems);
  1587. });
  1588. resizeObserver.observe(props.container);
  1589. resizeObserverRef.current = resizeObserver;
  1590. }, [props.container]);
  1591. const rafId = useRef<number | null>(null);
  1592. const pointerEventsRaf = useRef<{id: number} | null>(null);
  1593. useLayoutEffect(() => {
  1594. if (!list.current || !props.container) {
  1595. return undefined;
  1596. }
  1597. if (props.container && !scrollContainerRef.current) {
  1598. scrollContainerRef.current = props.container.children[0] as HTMLElement | null;
  1599. }
  1600. props.container.style.height = '100%';
  1601. props.container.style.overflow = 'auto';
  1602. props.container.style.position = 'relative';
  1603. props.container.style.willChange = 'transform';
  1604. props.container.style.overscrollBehavior = 'none';
  1605. scrollContainerRef.current!.style.overflow = 'hidden';
  1606. scrollContainerRef.current!.style.position = 'relative';
  1607. scrollContainerRef.current!.style.willChange = 'transform';
  1608. scrollContainerRef.current!.style.height = `${props.items.length * 24}px`;
  1609. maybeToggleScrollbar(
  1610. props.container,
  1611. scrollHeightRef.current,
  1612. props.items.length * 24,
  1613. props.manager
  1614. );
  1615. const onScroll = event => {
  1616. if (!list.current) {
  1617. return;
  1618. }
  1619. if (rafId.current !== null) {
  1620. window.cancelAnimationFrame(rafId.current);
  1621. }
  1622. managerRef.current.isScrolling = true;
  1623. managerRef.current.enqueueOnScrollEndOutOfBoundsCheck();
  1624. rafId.current = window.requestAnimationFrame(() => {
  1625. scrollTopRef.current = Math.max(0, event.target?.scrollTop ?? 0);
  1626. const recomputedItems = findRenderedItems({
  1627. scrollTop: scrollTopRef.current,
  1628. items: props.items,
  1629. overscroll: 5,
  1630. rowHeight: 24,
  1631. scrollHeight: scrollHeightRef.current,
  1632. styleCache: styleCache.current!,
  1633. renderCache: renderCache.current!,
  1634. render: renderRef.current,
  1635. manager: managerRef.current,
  1636. });
  1637. setItems(recomputedItems);
  1638. });
  1639. if (!pointerEventsRaf.current && scrollContainerRef.current) {
  1640. scrollContainerRef.current.style.pointerEvents = 'none';
  1641. }
  1642. if (pointerEventsRaf.current) {
  1643. window.cancelAnimationFrame(pointerEventsRaf.current.id);
  1644. }
  1645. pointerEventsRaf.current = requestAnimationTimeout(() => {
  1646. styleCache.current?.clear();
  1647. renderCache.current?.clear();
  1648. managerRef.current.isScrolling = false;
  1649. const recomputedItems = findRenderedItems({
  1650. scrollTop: scrollTopRef.current,
  1651. items: props.items,
  1652. overscroll: 5,
  1653. rowHeight: 24,
  1654. scrollHeight: scrollHeightRef.current,
  1655. styleCache: styleCache.current!,
  1656. renderCache: renderCache.current!,
  1657. render: renderRef.current,
  1658. manager: managerRef.current,
  1659. });
  1660. setItems(recomputedItems);
  1661. if (list.current && scrollContainerRef.current) {
  1662. scrollContainerRef.current.style.pointerEvents = 'auto';
  1663. pointerEventsRaf.current = null;
  1664. }
  1665. }, 50);
  1666. };
  1667. props.container.addEventListener('scroll', onScroll, {passive: true});
  1668. return () => {
  1669. props.container?.removeEventListener('scroll', onScroll);
  1670. };
  1671. }, [props.container, props.items, props.items.length, props.manager]);
  1672. useLayoutEffect(() => {
  1673. if (!list.current || !styleCache.current || !renderCache.current) {
  1674. return;
  1675. }
  1676. styleCache.current.clear();
  1677. renderCache.current.clear();
  1678. const recomputedItems = findRenderedItems({
  1679. scrollTop: scrollTopRef.current,
  1680. items: props.items,
  1681. overscroll: 5,
  1682. rowHeight: 24,
  1683. scrollHeight: scrollHeightRef.current,
  1684. styleCache: styleCache.current!,
  1685. renderCache: renderCache.current,
  1686. render: renderRef.current,
  1687. manager: managerRef.current,
  1688. });
  1689. setItems(recomputedItems);
  1690. }, [props.items, props.items.length, props.render]);
  1691. return {
  1692. virtualized: items.virtualized,
  1693. rendered: items.rendered,
  1694. list: list.current!,
  1695. };
  1696. };
  1697. export interface VirtualizedRow {
  1698. index: number;
  1699. item: TraceTreeNode<TraceTree.NodeValue>;
  1700. key: number;
  1701. style: React.CSSProperties;
  1702. }
  1703. function findRenderedItems({
  1704. items,
  1705. overscroll,
  1706. rowHeight,
  1707. scrollHeight,
  1708. scrollTop,
  1709. styleCache,
  1710. renderCache,
  1711. render,
  1712. manager,
  1713. }: {
  1714. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1715. manager: VirtualizedViewManager;
  1716. overscroll: number;
  1717. render: (arg: VirtualizedRow) => React.ReactNode;
  1718. renderCache: Map<number, React.ReactNode>;
  1719. rowHeight: number;
  1720. scrollHeight: number;
  1721. scrollTop: number;
  1722. styleCache: Map<number, React.CSSProperties>;
  1723. }): {rendered: React.ReactNode[]; virtualized: VirtualizedRow[]} {
  1724. // This is overscroll height for single direction, when computing the total,
  1725. // we need to multiply this by 2 because we overscroll in both directions.
  1726. const OVERSCROLL_HEIGHT = overscroll * rowHeight;
  1727. const virtualized: VirtualizedRow[] = [];
  1728. const rendered: React.ReactNode[] = [];
  1729. // Clamp viewport to scrollHeight bounds [0, length * rowHeight] because some browsers may fire
  1730. // scrollTop with negative values when the user scrolls up past the top of the list (overscroll behavior)
  1731. const viewport = {
  1732. top: Math.max(scrollTop - OVERSCROLL_HEIGHT, 0),
  1733. bottom: Math.min(
  1734. scrollTop + scrollHeight + OVERSCROLL_HEIGHT,
  1735. items.length * rowHeight
  1736. ),
  1737. };
  1738. // Points to the position inside the visible array
  1739. let visibleItemIndex = 0;
  1740. // Points to the currently iterated item
  1741. let indexPointer = findOptimisticStartIndex({
  1742. items,
  1743. viewport,
  1744. scrollTop,
  1745. rowHeight,
  1746. overscroll,
  1747. });
  1748. manager.start_virtualized_index = indexPointer;
  1749. // Max number of visible items in our list
  1750. const MAX_VISIBLE_ITEMS = Math.ceil((scrollHeight + OVERSCROLL_HEIGHT * 2) / rowHeight);
  1751. const ALL_ITEMS = items.length;
  1752. // While number of visible items is less than max visible items, and we haven't reached the end of the list
  1753. while (visibleItemIndex < MAX_VISIBLE_ITEMS && indexPointer < ALL_ITEMS) {
  1754. const elementTop = indexPointer * rowHeight;
  1755. const elementBottom = elementTop + rowHeight;
  1756. // An element is inside a viewport if the top of the element is below the top of the viewport
  1757. // and the bottom of the element is above the bottom of the viewport
  1758. if (elementTop >= viewport.top && elementBottom <= viewport.bottom) {
  1759. let style = styleCache.get(indexPointer);
  1760. if (!style) {
  1761. style = {position: 'absolute', top: elementTop};
  1762. styleCache.set(indexPointer, style);
  1763. }
  1764. const virtualizedRow: VirtualizedRow = {
  1765. key: indexPointer,
  1766. style,
  1767. index: indexPointer,
  1768. item: items[indexPointer],
  1769. };
  1770. virtualized[visibleItemIndex] = virtualizedRow;
  1771. const renderedRow = renderCache.get(indexPointer) || render(virtualizedRow);
  1772. rendered[visibleItemIndex] = renderedRow;
  1773. renderCache.set(indexPointer, renderedRow);
  1774. visibleItemIndex++;
  1775. }
  1776. indexPointer++;
  1777. }
  1778. return {rendered, virtualized};
  1779. }
  1780. export function findOptimisticStartIndex({
  1781. items,
  1782. overscroll,
  1783. rowHeight,
  1784. scrollTop,
  1785. viewport,
  1786. }: {
  1787. items: ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>>;
  1788. overscroll: number;
  1789. rowHeight: number;
  1790. scrollTop: number;
  1791. viewport: {bottom: number; top: number};
  1792. }): number {
  1793. if (!items.length || viewport.top === 0) {
  1794. return 0;
  1795. }
  1796. return Math.max(Math.floor(scrollTop / rowHeight) - overscroll, 0);
  1797. }
  1798. function findInTreeFromSegment(
  1799. start: TraceTreeNode<TraceTree.NodeValue>,
  1800. segment: TraceTree.NodePath
  1801. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1802. const [type, id] = segment.split('-');
  1803. if (!type || !id) {
  1804. throw new TypeError('Node path must be in the format of `type-id`');
  1805. }
  1806. return TraceTreeNode.Find(start, node => {
  1807. if (type === 'txn' && isTransactionNode(node)) {
  1808. return node.value.event_id === id;
  1809. }
  1810. if (type === 'span' && isSpanNode(node)) {
  1811. return node.value.span_id === id;
  1812. }
  1813. if (type === 'ag' && isAutogroupedNode(node)) {
  1814. if (isParentAutogroupedNode(node)) {
  1815. return node.head.value.span_id === id || node.tail.value.span_id === id;
  1816. }
  1817. if (isSiblingAutogroupedNode(node)) {
  1818. const child = node.children[0];
  1819. if (isSpanNode(child)) {
  1820. return child.value.span_id === id;
  1821. }
  1822. }
  1823. }
  1824. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1825. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1826. }
  1827. if (type === 'error' && isTraceErrorNode(node)) {
  1828. return node.value.event_id === id;
  1829. }
  1830. if (type === 'empty' && isNoDataNode(node)) {
  1831. return true;
  1832. }
  1833. return false;
  1834. });
  1835. }
  1836. function hasEventWithEventId(
  1837. node: TraceTreeNode<TraceTree.NodeValue>,
  1838. eventId: string
  1839. ): boolean {
  1840. // Skip trace nodes since they accumulate all errors and performance issues
  1841. // in the trace and is not an event.
  1842. if (isTraceNode(node)) {
  1843. return false;
  1844. }
  1845. // Search in errors
  1846. if (node.errors.size > 0) {
  1847. for (const e of node.errors) {
  1848. if (e.event_id === eventId) {
  1849. return true;
  1850. }
  1851. }
  1852. }
  1853. // Search in performance issues
  1854. if (node.performance_issues.size > 0) {
  1855. for (const p of node.performance_issues) {
  1856. if (p.event_id === eventId) {
  1857. return true;
  1858. }
  1859. }
  1860. }
  1861. // Check if we are maybe looking for the profile_id
  1862. if (node.value && 'profile_id' in node.value && node.value.profile_id === eventId) {
  1863. return true;
  1864. }
  1865. return false;
  1866. }
  1867. function findInTreeByEventId(start: TraceTreeNode<TraceTree.NodeValue>, eventId: string) {
  1868. return TraceTreeNode.Find(start, node => {
  1869. if (isTransactionNode(node)) {
  1870. if (node.value.event_id === eventId) {
  1871. return true;
  1872. }
  1873. } else if (isSpanNode(node)) {
  1874. return node.value.span_id === eventId;
  1875. } else if (isTraceErrorNode(node)) {
  1876. return node.value.event_id === eventId;
  1877. }
  1878. return hasEventWithEventId(node, eventId);
  1879. });
  1880. }