index.tsx 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. import type React from 'react';
  2. import {
  3. Fragment,
  4. useCallback,
  5. useEffect,
  6. useLayoutEffect,
  7. useMemo,
  8. useReducer,
  9. useRef,
  10. useState,
  11. } from 'react';
  12. import {flushSync} from 'react-dom';
  13. import styled from '@emotion/styled';
  14. import * as Sentry from '@sentry/react';
  15. import * as qs from 'query-string';
  16. import {Button} from 'sentry/components/button';
  17. import useFeedbackWidget from 'sentry/components/feedback/widget/useFeedbackWidget';
  18. import LoadingIndicator from 'sentry/components/loadingIndicator';
  19. import NoProjectMessage from 'sentry/components/noProjectMessage';
  20. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  21. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  22. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  23. import {t} from 'sentry/locale';
  24. import {space} from 'sentry/styles/space';
  25. import type {EventTransaction} from 'sentry/types/event';
  26. import type {Organization} from 'sentry/types/organization';
  27. import {trackAnalytics} from 'sentry/utils/analytics';
  28. import {browserHistory} from 'sentry/utils/browserHistory';
  29. import EventView from 'sentry/utils/discover/eventView';
  30. import type {TraceSplitResults} from 'sentry/utils/performance/quickTrace/types';
  31. import {
  32. cancelAnimationTimeout,
  33. requestAnimationTimeout,
  34. } from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  35. import type {UseApiQueryResult} from 'sentry/utils/queryClient';
  36. import {decodeScalar} from 'sentry/utils/queryString';
  37. import type RequestError from 'sentry/utils/requestError/requestError';
  38. import {capitalize} from 'sentry/utils/string/capitalize';
  39. import useApi from 'sentry/utils/useApi';
  40. import type {DispatchingReducerMiddleware} from 'sentry/utils/useDispatchingReducer';
  41. import useOrganization from 'sentry/utils/useOrganization';
  42. import {useParams} from 'sentry/utils/useParams';
  43. import useProjects from 'sentry/utils/useProjects';
  44. import {traceAnalytics} from 'sentry/views/performance/newTraceDetails/traceAnalytics';
  45. import {
  46. type ViewManagerScrollAnchor,
  47. VirtualizedViewManager,
  48. } from 'sentry/views/performance/newTraceDetails/traceRenderers/virtualizedViewManager';
  49. import {
  50. searchInTraceTreeText,
  51. searchInTraceTreeTokens,
  52. } from 'sentry/views/performance/newTraceDetails/traceSearch/traceSearchEvaluator';
  53. import {parseTraceSearch} from 'sentry/views/performance/newTraceDetails/traceSearch/traceTokenConverter';
  54. import {TraceShortcuts} from 'sentry/views/performance/newTraceDetails/traceShortcutsModal';
  55. import {
  56. TraceStateProvider,
  57. useTraceState,
  58. useTraceStateDispatch,
  59. useTraceStateEmitter,
  60. } from 'sentry/views/performance/newTraceDetails/traceState/traceStateProvider';
  61. import type {ReplayRecord} from 'sentry/views/replays/types';
  62. import {useTrace} from './traceApi/useTrace';
  63. import {type TraceMetaQueryResults, useTraceMeta} from './traceApi/useTraceMeta';
  64. import {useTraceRootEvent} from './traceApi/useTraceRootEvent';
  65. import {TraceDrawer} from './traceDrawer/traceDrawer';
  66. import {TraceTree, type TraceTreeNode} from './traceModels/traceTree';
  67. import {TraceSearchInput} from './traceSearch/traceSearchInput';
  68. import {
  69. DEFAULT_TRACE_VIEW_PREFERENCES,
  70. loadTraceViewPreferences,
  71. } from './traceState/tracePreferences';
  72. import {isTraceNode} from './guards';
  73. import {Trace} from './trace';
  74. import {TraceMetadataHeader} from './traceMetadataHeader';
  75. import type {TraceReducer, TraceReducerState} from './traceState';
  76. import {TraceType} from './traceType';
  77. import {TraceUXChangeAlert} from './traceUXChangeBanner';
  78. import {useTraceQueryParamStateSync} from './useTraceQueryParamStateSync';
  79. function decodeScrollQueue(maybePath: unknown): TraceTree.NodePath[] | null {
  80. if (Array.isArray(maybePath)) {
  81. return maybePath;
  82. }
  83. if (typeof maybePath === 'string') {
  84. return [maybePath as TraceTree.NodePath];
  85. }
  86. return null;
  87. }
  88. function logTraceMetadata(tree: TraceTree, organization: Organization) {
  89. switch (tree.shape) {
  90. case TraceType.BROKEN_SUBTRACES:
  91. case TraceType.EMPTY_TRACE:
  92. case TraceType.MULTIPLE_ROOTS:
  93. case TraceType.ONE_ROOT:
  94. case TraceType.NO_ROOT:
  95. case TraceType.ONLY_ERRORS:
  96. case TraceType.BROWSER_MULTIPLE_ROOTS:
  97. traceAnalytics.trackTraceMetadata(tree, organization);
  98. break;
  99. default: {
  100. Sentry.captureMessage('Unknown trace type');
  101. }
  102. }
  103. }
  104. export function TraceView() {
  105. const params = useParams<{traceSlug?: string}>();
  106. const organization = useOrganization();
  107. const traceSlug = useMemo(() => {
  108. const slug = params.traceSlug?.trim() ?? '';
  109. // null and undefined are not valid trace slugs, but they can be passed
  110. // in the URL and need to check for their string coerced values.
  111. if (!slug || slug === 'null' || slug === 'undefined') {
  112. Sentry.withScope(scope => {
  113. scope.setFingerprint(['trace-null-slug']);
  114. Sentry.captureMessage(`Trace slug is empty`);
  115. });
  116. }
  117. return slug;
  118. }, [params.traceSlug]);
  119. const queryParams = useMemo(() => {
  120. const normalizedParams = normalizeDateTimeParams(qs.parse(location.search), {
  121. allowAbsolutePageDatetime: true,
  122. });
  123. const start = decodeScalar(normalizedParams.start);
  124. const timestamp = decodeScalar(normalizedParams.timestamp);
  125. const end = decodeScalar(normalizedParams.end);
  126. const statsPeriod = decodeScalar(normalizedParams.statsPeriod);
  127. return {start, end, statsPeriod, timestamp, useSpans: 1};
  128. }, []);
  129. const traceEventView = useMemo(() => {
  130. const {start, end, statsPeriod, timestamp} = queryParams;
  131. let startTimeStamp = start;
  132. let endTimeStamp = end;
  133. // If timestamp exists in the query params, we want to use it to set the start and end time
  134. // with a buffer of 1.5 days, for retrieving events belonging to the trace.
  135. if (timestamp) {
  136. const parsedTimeStamp = Number(timestamp);
  137. if (isNaN(parsedTimeStamp)) {
  138. throw new Error('Invalid timestamp');
  139. }
  140. const buffer = 36 * 60 * 60 * 1000; // 1.5 days in milliseconds
  141. const dateFromTimestamp = new Date(parsedTimeStamp * 1000);
  142. startTimeStamp = new Date(dateFromTimestamp.getTime() - buffer).toISOString();
  143. endTimeStamp = new Date(dateFromTimestamp.getTime() + buffer).toISOString();
  144. }
  145. return EventView.fromSavedQuery({
  146. id: undefined,
  147. name: `Events with Trace ID ${traceSlug}`,
  148. fields: ['title', 'event.type', 'project', 'timestamp'],
  149. orderby: '-timestamp',
  150. query: `trace:${traceSlug}`,
  151. projects: [ALL_ACCESS_PROJECTS],
  152. version: 2,
  153. start: startTimeStamp,
  154. end: endTimeStamp,
  155. range: !(startTimeStamp || endTimeStamp) ? statsPeriod : undefined,
  156. });
  157. }, [queryParams, traceSlug]);
  158. const trace = useTrace();
  159. const meta = useTraceMeta([traceSlug]);
  160. const rootEvent = useTraceRootEvent(trace.data ?? null);
  161. const preferences = useMemo(
  162. () =>
  163. loadTraceViewPreferences('trace-view-preferences') ||
  164. DEFAULT_TRACE_VIEW_PREFERENCES,
  165. []
  166. );
  167. return (
  168. <SentryDocumentTitle
  169. title={`${t('Trace Details')} - ${traceSlug}`}
  170. orgSlug={organization.slug}
  171. >
  172. <TraceStateProvider
  173. initialPreferences={preferences}
  174. preferencesStorageKey="trace-view-preferences"
  175. >
  176. <NoProjectMessage organization={organization}>
  177. <TraceExternalLayout>
  178. <TraceUXChangeAlert />
  179. <TraceMetadataHeader
  180. organization={organization}
  181. projectID={rootEvent?.data?.projectID ?? ''}
  182. title={rootEvent?.data?.title ?? ''}
  183. traceSlug={traceSlug}
  184. traceEventView={traceEventView}
  185. />
  186. <TraceInnerLayout>
  187. <TraceViewWaterfall
  188. status={trace.status}
  189. trace={trace.data ?? null}
  190. traceSlug={traceSlug}
  191. organization={organization}
  192. traceEventView={traceEventView}
  193. metaResults={meta}
  194. rootEvent={rootEvent}
  195. replayRecord={null}
  196. source="performance"
  197. />
  198. </TraceInnerLayout>
  199. </TraceExternalLayout>
  200. </NoProjectMessage>
  201. </TraceStateProvider>
  202. </SentryDocumentTitle>
  203. );
  204. }
  205. const TRACE_TAB: TraceReducerState['tabs']['tabs'][0] = {
  206. node: 'trace',
  207. label: t('Trace'),
  208. };
  209. const VITALS_TAB: TraceReducerState['tabs']['tabs'][0] = {
  210. node: 'vitals',
  211. label: t('Vitals'),
  212. };
  213. type TraceViewWaterfallProps = {
  214. metaResults: TraceMetaQueryResults;
  215. organization: Organization;
  216. replayRecord: ReplayRecord | null;
  217. rootEvent: UseApiQueryResult<EventTransaction, RequestError>;
  218. source: string;
  219. status: UseApiQueryResult<any, any>['status'];
  220. trace: TraceSplitResults<TraceTree.Transaction> | null;
  221. traceEventView: EventView;
  222. traceSlug: string;
  223. };
  224. export function TraceViewWaterfall(props: TraceViewWaterfallProps) {
  225. const api = useApi();
  226. const {projects} = useProjects();
  227. const organization = useOrganization();
  228. const loadingTraceRef = useRef<TraceTree | null>(null);
  229. const [forceRender, rerender] = useReducer(x => (x + 1) % Number.MAX_SAFE_INTEGER, 0);
  230. const traceState = useTraceState();
  231. const traceDispatch = useTraceStateDispatch();
  232. const traceStateEmitter = useTraceStateEmitter();
  233. const forceRerender = useCallback(() => {
  234. flushSync(rerender);
  235. }, []);
  236. useEffect(() => {
  237. trackAnalytics('performance_views.trace_view_v1_page_load', {
  238. organization: props.organization,
  239. source: props.source,
  240. });
  241. }, [props.organization, props.source]);
  242. const initializedRef = useRef(false);
  243. const scrollQueueRef = useRef<
  244. {eventId?: string; path?: TraceTree.NodePath[]} | null | undefined
  245. >(undefined);
  246. if (scrollQueueRef.current === undefined) {
  247. const queryParams = qs.parse(location.search);
  248. const maybeQueue = decodeScrollQueue(queryParams.node);
  249. if (maybeQueue || queryParams.eventId) {
  250. scrollQueueRef.current = {
  251. eventId: queryParams.eventId as string,
  252. path: maybeQueue as TraceTreeNode<TraceTree.NodeValue>['path'],
  253. };
  254. } else {
  255. scrollQueueRef.current = null;
  256. }
  257. }
  258. const previouslyFocusedNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  259. null
  260. );
  261. const previouslyScrolledToNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  262. null
  263. );
  264. const tree = useMemo(() => {
  265. if (props.status === 'error') {
  266. const errorTree = TraceTree.Error(
  267. {
  268. project_slug: projects?.[0]?.slug ?? '',
  269. event_id: props.traceSlug,
  270. },
  271. loadingTraceRef.current
  272. );
  273. return errorTree;
  274. }
  275. if (
  276. props.trace?.transactions.length === 0 &&
  277. props.trace?.orphan_errors.length === 0
  278. ) {
  279. return TraceTree.Empty();
  280. }
  281. if (props.status === 'loading') {
  282. const loadingTrace =
  283. loadingTraceRef.current ??
  284. TraceTree.Loading(
  285. {
  286. project_slug: projects?.[0]?.slug ?? '',
  287. event_id: props.traceSlug,
  288. },
  289. loadingTraceRef.current
  290. );
  291. loadingTraceRef.current = loadingTrace;
  292. return loadingTrace;
  293. }
  294. if (props.trace) {
  295. return TraceTree.FromTrace(props.trace, props.replayRecord);
  296. }
  297. throw new Error('Invalid trace state');
  298. }, [props.traceSlug, props.trace, props.status, projects, props.replayRecord]);
  299. // Assign the trace state to a ref so we can access it without re-rendering
  300. const traceStateRef = useRef<TraceReducerState>(traceState);
  301. traceStateRef.current = traceState;
  302. // Initialize the view manager right after the state reducer
  303. const viewManager = useMemo(() => {
  304. return new VirtualizedViewManager({
  305. list: {width: traceState.preferences.list.width},
  306. span_list: {width: 1 - traceState.preferences.list.width},
  307. });
  308. // We only care about initial state when we initialize the view manager
  309. // eslint-disable-next-line react-hooks/exhaustive-deps
  310. }, []);
  311. // Initialize the tabs reducer when the tree initializes
  312. useLayoutEffect(() => {
  313. return traceDispatch({
  314. type: 'set roving count',
  315. items: tree.list.length - 1,
  316. });
  317. }, [tree.list.length, traceDispatch]);
  318. // Initialize the tabs reducer when the tree initializes
  319. useLayoutEffect(() => {
  320. if (tree.type !== 'trace') {
  321. return;
  322. }
  323. const newTabs = [TRACE_TAB];
  324. if (tree.vitals.size > 0) {
  325. const types = Array.from(tree.vital_types.values());
  326. const label = types.length > 1 ? t('Vitals') : capitalize(types[0]) + ' Vitals';
  327. newTabs.push({
  328. ...VITALS_TAB,
  329. label,
  330. });
  331. }
  332. if (tree.profiled_events.size > 0) {
  333. newTabs.push({
  334. node: 'profiles',
  335. label: 'Profiles',
  336. });
  337. }
  338. traceDispatch({
  339. type: 'initialize tabs reducer',
  340. payload: {
  341. current_tab: traceStateRef?.current?.tabs?.tabs?.[0],
  342. tabs: newTabs,
  343. last_clicked_tab: null,
  344. },
  345. });
  346. // We only want to update the tabs when the tree changes
  347. // eslint-disable-next-line react-hooks/exhaustive-deps
  348. }, [tree]);
  349. const searchingRaf = useRef<{id: number | null} | null>(null);
  350. const onTraceSearch = useCallback(
  351. (
  352. query: string,
  353. activeNode: TraceTreeNode<TraceTree.NodeValue> | null,
  354. behavior: 'track result' | 'persist'
  355. ) => {
  356. if (searchingRaf.current?.id) {
  357. window.cancelAnimationFrame(searchingRaf.current.id);
  358. }
  359. function done([matches, lookup, activeNodeSearchResult]) {
  360. // If the previous node is still in the results set, we want to keep it
  361. if (activeNodeSearchResult) {
  362. traceDispatch({
  363. type: 'set results',
  364. results: matches,
  365. resultsLookup: lookup,
  366. resultIteratorIndex: activeNodeSearchResult?.resultIteratorIndex,
  367. resultIndex: activeNodeSearchResult?.resultIndex,
  368. previousNode: activeNodeSearchResult,
  369. node: activeNode,
  370. });
  371. return;
  372. }
  373. if (activeNode && behavior === 'persist') {
  374. traceDispatch({
  375. type: 'set results',
  376. results: matches,
  377. resultsLookup: lookup,
  378. resultIteratorIndex: undefined,
  379. resultIndex: undefined,
  380. previousNode: activeNodeSearchResult,
  381. node: activeNode,
  382. });
  383. return;
  384. }
  385. const resultIndex: number | undefined = matches?.[0]?.index;
  386. const resultIteratorIndex: number | undefined = matches?.[0] ? 0 : undefined;
  387. const node: TraceTreeNode<TraceTree.NodeValue> | null = matches?.[0]?.value;
  388. traceDispatch({
  389. type: 'set results',
  390. results: matches,
  391. resultsLookup: lookup,
  392. resultIteratorIndex: resultIteratorIndex,
  393. resultIndex: resultIndex,
  394. previousNode: activeNodeSearchResult,
  395. node,
  396. });
  397. }
  398. const tokens = parseTraceSearch(query);
  399. if (tokens) {
  400. searchingRaf.current = searchInTraceTreeTokens(tree, tokens, activeNode, done);
  401. } else {
  402. searchingRaf.current = searchInTraceTreeText(tree, query, activeNode, done);
  403. }
  404. },
  405. [traceDispatch, tree]
  406. );
  407. // We need to heavily debounce query string updates because the rest of the app is so slow
  408. // to rerender that it causes the search to drop frames on every keystroke...
  409. const QUERY_STRING_STATE_DEBOUNCE = 300;
  410. const queryStringAnimationTimeoutRef = useRef<{id: number} | null>(null);
  411. const setRowAsFocused = useCallback(
  412. (
  413. node: TraceTreeNode<TraceTree.NodeValue> | null,
  414. event: React.MouseEvent<HTMLElement> | null,
  415. resultsLookup: Map<TraceTreeNode<TraceTree.NodeValue>, number>,
  416. index: number | null,
  417. debounce: number = QUERY_STRING_STATE_DEBOUNCE
  418. ) => {
  419. // sync query string with the clicked node
  420. if (node) {
  421. if (queryStringAnimationTimeoutRef.current) {
  422. cancelAnimationTimeout(queryStringAnimationTimeoutRef.current);
  423. }
  424. queryStringAnimationTimeoutRef.current = requestAnimationTimeout(() => {
  425. const currentQueryStringPath = qs.parse(location.search).node;
  426. const nextNodePath = node.path;
  427. // Updating the query string with the same path is problematic because it causes
  428. // the entire sentry app to rerender, which is enough to cause jank and drop frames
  429. if (JSON.stringify(currentQueryStringPath) === JSON.stringify(nextNodePath)) {
  430. return;
  431. }
  432. const {eventId: _eventId, ...query} = qs.parse(location.search);
  433. browserHistory.replace({
  434. pathname: location.pathname,
  435. query: {
  436. ...query,
  437. node: nextNodePath,
  438. },
  439. });
  440. queryStringAnimationTimeoutRef.current = null;
  441. }, debounce);
  442. if (resultsLookup.has(node) && typeof index === 'number') {
  443. traceDispatch({
  444. type: 'set search iterator index',
  445. resultIndex: index,
  446. resultIteratorIndex: resultsLookup.get(node)!,
  447. });
  448. }
  449. if (isTraceNode(node)) {
  450. traceDispatch({type: 'activate tab', payload: TRACE_TAB.node});
  451. return;
  452. }
  453. traceDispatch({
  454. type: 'activate tab',
  455. payload: node,
  456. pin_previous: event?.metaKey,
  457. });
  458. }
  459. },
  460. [traceDispatch]
  461. );
  462. const onRowClick = useCallback(
  463. (
  464. node: TraceTreeNode<TraceTree.NodeValue>,
  465. event: React.MouseEvent<HTMLElement>,
  466. index: number
  467. ) => {
  468. trackAnalytics('trace.trace_layout.span_row_click', {
  469. organization,
  470. num_children: node.children.length,
  471. project_platform:
  472. projects.find(p => p.slug === node.metadata.project_slug)?.platform || 'other',
  473. });
  474. if (traceStateRef.current.preferences.drawer.minimized) {
  475. traceDispatch({type: 'minimize drawer', payload: false});
  476. }
  477. setRowAsFocused(node, event, traceStateRef.current.search.resultsLookup, null, 0);
  478. if (traceStateRef.current.search.resultsLookup.has(node)) {
  479. const idx = traceStateRef.current.search.resultsLookup.get(node)!;
  480. traceDispatch({
  481. type: 'set search iterator index',
  482. resultIndex: index,
  483. resultIteratorIndex: idx,
  484. });
  485. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  486. traceDispatch({type: 'clear search iterator index'});
  487. }
  488. traceDispatch({
  489. type: 'set roving index',
  490. action_source: 'click',
  491. index,
  492. node,
  493. });
  494. },
  495. [setRowAsFocused, traceDispatch, organization, projects]
  496. );
  497. const scrollRowIntoView = useCallback(
  498. (
  499. node: TraceTreeNode<TraceTree.NodeValue>,
  500. index: number,
  501. anchor?: ViewManagerScrollAnchor,
  502. force?: boolean
  503. ) => {
  504. // Last node we scrolled to is the same as the node we want to scroll to
  505. if (previouslyScrolledToNodeRef.current === node && !force) {
  506. return;
  507. }
  508. // Always scroll to the row vertically
  509. viewManager.scrollToRow(index, anchor);
  510. previouslyScrolledToNodeRef.current = node;
  511. // If the row had not yet been measured, then enqueue a listener for when
  512. // the row is rendered and measured. This ensures that horizontal scroll
  513. // accurately narrows zooms to the start of the node as the new width will be updated
  514. if (!viewManager.row_measurer.cache.has(node)) {
  515. viewManager.row_measurer.once('row measure end', () => {
  516. if (!viewManager.isOutsideOfViewOnKeyDown(node)) {
  517. return;
  518. }
  519. viewManager.scrollRowIntoViewHorizontally(node, 0, 48, 'measured');
  520. });
  521. } else {
  522. if (!viewManager.isOutsideOfViewOnKeyDown(node)) {
  523. return;
  524. }
  525. viewManager.scrollRowIntoViewHorizontally(node, 0, 48, 'measured');
  526. }
  527. },
  528. [viewManager]
  529. );
  530. const onTabScrollToNode = useCallback(
  531. (node: TraceTreeNode<TraceTree.NodeValue>) => {
  532. if (node === null) {
  533. return;
  534. }
  535. // We call expandToNode because we want to ensure that the node is
  536. // visible and may not have been collapsed/hidden by the user
  537. TraceTree.ExpandToPath(tree, node.path, forceRerender, {
  538. api,
  539. organization: props.organization,
  540. }).then(maybeNode => {
  541. if (maybeNode) {
  542. previouslyFocusedNodeRef.current = null;
  543. scrollRowIntoView(maybeNode.node, maybeNode.index, 'center if outside', true);
  544. traceDispatch({
  545. type: 'set roving index',
  546. node: maybeNode.node,
  547. index: maybeNode.index,
  548. action_source: 'click',
  549. });
  550. setRowAsFocused(
  551. maybeNode.node,
  552. null,
  553. traceStateRef.current.search.resultsLookup,
  554. null,
  555. 0
  556. );
  557. if (traceStateRef.current.search.resultsLookup.has(maybeNode.node)) {
  558. traceDispatch({
  559. type: 'set search iterator index',
  560. resultIndex: maybeNode.index,
  561. resultIteratorIndex: traceStateRef.current.search.resultsLookup.get(
  562. maybeNode.node
  563. )!,
  564. });
  565. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  566. traceDispatch({type: 'clear search iterator index'});
  567. }
  568. }
  569. });
  570. },
  571. [
  572. api,
  573. props.organization,
  574. setRowAsFocused,
  575. scrollRowIntoView,
  576. tree,
  577. traceDispatch,
  578. forceRerender,
  579. ]
  580. );
  581. // Unlike onTabScrollToNode, this function does not set the node as the current
  582. // focused node, but rather scrolls the node into view and sets the roving index to the node.
  583. const onScrollToNode = useCallback(
  584. (node: TraceTreeNode<TraceTree.NodeValue>) => {
  585. TraceTree.ExpandToPath(tree, node.path, forceRerender, {
  586. api,
  587. organization: props.organization,
  588. }).then(maybeNode => {
  589. if (maybeNode) {
  590. previouslyFocusedNodeRef.current = null;
  591. scrollRowIntoView(maybeNode.node, maybeNode.index, 'center if outside', true);
  592. traceDispatch({
  593. type: 'set roving index',
  594. node: maybeNode.node,
  595. index: maybeNode.index,
  596. action_source: 'click',
  597. });
  598. if (traceStateRef.current.search.resultsLookup.has(maybeNode.node)) {
  599. traceDispatch({
  600. type: 'set search iterator index',
  601. resultIndex: maybeNode.index,
  602. resultIteratorIndex: traceStateRef.current.search.resultsLookup.get(
  603. maybeNode.node
  604. )!,
  605. });
  606. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  607. traceDispatch({type: 'clear search iterator index'});
  608. }
  609. }
  610. });
  611. },
  612. [api, props.organization, scrollRowIntoView, tree, traceDispatch, forceRerender]
  613. );
  614. // Callback that is invoked when the trace loads and reaches its initialied state,
  615. // that is when the trace tree data and any data that the trace depends on is loaded,
  616. // but the trace is not yet rendered in the view.
  617. const onTraceLoad = useCallback(
  618. (
  619. _trace: TraceTree,
  620. nodeToScrollTo: TraceTreeNode<TraceTree.NodeValue> | null,
  621. indexOfNodeToScrollTo: number | null
  622. ) => {
  623. scrollQueueRef.current = null;
  624. const query = qs.parse(location.search);
  625. if (query.fov && typeof query.fov === 'string') {
  626. viewManager.maybeInitializeTraceViewFromQS(query.fov);
  627. }
  628. if (nodeToScrollTo !== null && indexOfNodeToScrollTo !== null) {
  629. viewManager.scrollToRow(indexOfNodeToScrollTo, 'center');
  630. // At load time, we want to scroll the row into view, but we need to ensure
  631. // that the row had been measured first, else we can exceed the bounds of the container.
  632. scrollRowIntoView(nodeToScrollTo, indexOfNodeToScrollTo, 'center');
  633. setRowAsFocused(
  634. nodeToScrollTo,
  635. null,
  636. traceStateRef.current.search.resultsLookup,
  637. indexOfNodeToScrollTo
  638. );
  639. traceDispatch({
  640. type: 'set roving index',
  641. node: nodeToScrollTo,
  642. index: indexOfNodeToScrollTo,
  643. action_source: 'load',
  644. });
  645. }
  646. if (traceStateRef.current.search.query) {
  647. onTraceSearch(traceStateRef.current.search.query, nodeToScrollTo, 'persist');
  648. }
  649. },
  650. [setRowAsFocused, traceDispatch, onTraceSearch, scrollRowIntoView, viewManager]
  651. );
  652. // Setup the middleware for the trace reducer
  653. useLayoutEffect(() => {
  654. const beforeTraceNextStateDispatch: DispatchingReducerMiddleware<
  655. typeof TraceReducer
  656. >['before next state'] = (prevState, nextState, action) => {
  657. // This effect is responsible fo syncing the keyboard interactions with the search results,
  658. // we observe the changes to the roving tab index and search results and react by syncing the state.
  659. const {node: nextRovingNode, index: nextRovingTabIndex} = nextState.rovingTabIndex;
  660. const {resultIndex: nextSearchResultIndex} = nextState.search;
  661. if (
  662. nextRovingNode &&
  663. action.type === 'set roving index' &&
  664. action.action_source !== 'click' &&
  665. typeof nextRovingTabIndex === 'number' &&
  666. prevState.rovingTabIndex.node !== nextRovingNode
  667. ) {
  668. // When the roving tabIndex updates mark the node as focused and sync search results
  669. setRowAsFocused(
  670. nextRovingNode,
  671. null,
  672. nextState.search.resultsLookup,
  673. nextRovingTabIndex
  674. );
  675. if (action.type === 'set roving index' && action.action_source === 'keyboard') {
  676. scrollRowIntoView(nextRovingNode, nextRovingTabIndex, undefined);
  677. }
  678. if (nextState.search.resultsLookup.has(nextRovingNode)) {
  679. const idx = nextState.search.resultsLookup.get(nextRovingNode)!;
  680. traceDispatch({
  681. type: 'set search iterator index',
  682. resultIndex: nextRovingTabIndex,
  683. resultIteratorIndex: idx,
  684. });
  685. } else if (nextState.search.resultIteratorIndex !== null) {
  686. traceDispatch({type: 'clear search iterator index'});
  687. }
  688. } else if (
  689. typeof nextSearchResultIndex === 'number' &&
  690. prevState.search.resultIndex !== nextSearchResultIndex &&
  691. action.type !== 'set search iterator index'
  692. ) {
  693. // If the search result index changes, mark the node as focused and scroll it into view
  694. const nextNode = tree.list[nextSearchResultIndex];
  695. setRowAsFocused(
  696. nextNode,
  697. null,
  698. nextState.search.resultsLookup,
  699. nextSearchResultIndex
  700. );
  701. scrollRowIntoView(nextNode, nextSearchResultIndex, 'center if outside');
  702. }
  703. };
  704. traceStateEmitter.on('before next state', beforeTraceNextStateDispatch);
  705. return () => {
  706. traceStateEmitter.off('before next state', beforeTraceNextStateDispatch);
  707. };
  708. }, [
  709. tree,
  710. onTraceSearch,
  711. traceStateEmitter,
  712. traceDispatch,
  713. setRowAsFocused,
  714. scrollRowIntoView,
  715. ]);
  716. // Setup the middleware for the view manager and store the list width as a preference
  717. useLayoutEffect(() => {
  718. function onDividerResizeEnd(list_width: number) {
  719. traceDispatch({
  720. type: 'set list width',
  721. payload: list_width,
  722. });
  723. }
  724. viewManager.on('divider resize end', onDividerResizeEnd);
  725. return () => {
  726. viewManager.off('divider resize end', onDividerResizeEnd);
  727. };
  728. }, [viewManager, traceDispatch]);
  729. // Sync part of the state with the URL
  730. const traceQueryStateSync = useMemo(() => {
  731. return {search: traceState.search.query};
  732. }, [traceState.search.query]);
  733. useTraceQueryParamStateSync(traceQueryStateSync);
  734. const [traceGridRef, setTraceGridRef] = useState<HTMLElement | null>(null);
  735. // Memoized because it requires tree traversal
  736. const shape = useMemo(() => tree.shape, [tree]);
  737. useEffect(() => {
  738. if (tree.type !== 'trace') {
  739. return;
  740. }
  741. logTraceMetadata(tree, props.organization);
  742. }, [tree, props.organization]);
  743. useLayoutEffect(() => {
  744. if (!tree.root?.space || tree.type !== 'trace') {
  745. return undefined;
  746. }
  747. viewManager.initializeTraceSpace([tree.root.space[0], 0, tree.root.space[1], 1]);
  748. // Whenever the timeline changes, update the trace space
  749. const onTraceTimelineChange = (s: [number, number]) => {
  750. viewManager.updateTraceSpace(s[0], s[1]);
  751. };
  752. tree.on('trace timeline change', onTraceTimelineChange);
  753. return () => {
  754. tree.off('trace timeline change', onTraceTimelineChange);
  755. };
  756. }, [viewManager, tree]);
  757. return (
  758. <Fragment>
  759. <TraceToolbar>
  760. <TraceSearchInput onTraceSearch={onTraceSearch} organization={organization} />
  761. <TraceResetZoomButton
  762. viewManager={viewManager}
  763. organization={props.organization}
  764. />
  765. <TraceShortcuts />
  766. </TraceToolbar>
  767. <TraceGrid layout={traceState.preferences.layout} ref={setTraceGridRef}>
  768. <Trace
  769. trace={tree}
  770. rerender={rerender}
  771. trace_id={props.traceSlug}
  772. scrollQueueRef={scrollQueueRef}
  773. initializedRef={initializedRef}
  774. onRowClick={onRowClick}
  775. onTraceLoad={onTraceLoad}
  776. onTraceSearch={onTraceSearch}
  777. previouslyFocusedNodeRef={previouslyFocusedNodeRef}
  778. manager={viewManager}
  779. forceRerender={forceRender}
  780. />
  781. {tree.type === 'error' ? (
  782. <TraceError />
  783. ) : tree.type === 'empty' ? (
  784. <TraceEmpty />
  785. ) : tree.type === 'loading' ||
  786. (scrollQueueRef.current && tree.type !== 'trace') ? (
  787. <TraceLoading />
  788. ) : null}
  789. <TraceDrawer
  790. replayRecord={props.replayRecord}
  791. metaResults={props.metaResults}
  792. traceType={shape}
  793. trace={tree}
  794. traceGridRef={traceGridRef}
  795. traces={props.trace}
  796. manager={viewManager}
  797. onTabScrollToNode={onTabScrollToNode}
  798. onScrollToNode={onScrollToNode}
  799. rootEventResults={props.rootEvent}
  800. traceEventView={props.traceEventView}
  801. />
  802. </TraceGrid>
  803. </Fragment>
  804. );
  805. }
  806. function TraceResetZoomButton(props: {
  807. organization: Organization;
  808. viewManager: VirtualizedViewManager;
  809. }) {
  810. const onResetZoom = useCallback(() => {
  811. traceAnalytics.trackResetZoom(props.organization);
  812. props.viewManager.resetZoom();
  813. }, [props.viewManager, props.organization]);
  814. return (
  815. <ResetZoomButton
  816. size="xs"
  817. onClick={onResetZoom}
  818. ref={props.viewManager.registerResetZoomRef}
  819. >
  820. {t('Reset Zoom')}
  821. </ResetZoomButton>
  822. );
  823. }
  824. const ResetZoomButton = styled(Button)`
  825. transition: opacity 0.2s 0.5s ease-in-out;
  826. &[disabled] {
  827. cursor: not-allowed;
  828. opacity: 0.65;
  829. }
  830. `;
  831. const TraceExternalLayout = styled('div')`
  832. display: flex;
  833. flex-direction: column;
  834. flex: 1 1 100%;
  835. ~ footer {
  836. display: none;
  837. }
  838. `;
  839. const TraceInnerLayout = styled('div')`
  840. display: flex;
  841. flex-direction: column;
  842. flex: 1 1 100%;
  843. padding: ${space(2)};
  844. background-color: ${p => p.theme.background};
  845. --info: ${p => p.theme.purple400};
  846. --warning: ${p => p.theme.yellow300};
  847. --error: ${p => p.theme.error};
  848. --fatal: ${p => p.theme.error};
  849. --default: ${p => p.theme.gray300};
  850. --unknown: ${p => p.theme.gray300};
  851. --profile: ${p => p.theme.purple300};
  852. --autogrouped: ${p => p.theme.blue300};
  853. --performance-issue: ${p => p.theme.blue300};
  854. `;
  855. const TraceToolbar = styled('div')`
  856. flex-grow: 0;
  857. display: grid;
  858. grid-template-columns: 1fr min-content min-content;
  859. gap: ${space(1)};
  860. `;
  861. const TraceGrid = styled('div')<{
  862. layout: 'drawer bottom' | 'drawer left' | 'drawer right';
  863. }>`
  864. border: 1px solid ${p => p.theme.border};
  865. flex: 1 1 100%;
  866. display: grid;
  867. border-radius: ${p => p.theme.borderRadius};
  868. overflow: hidden;
  869. position: relative;
  870. /* false positive for grid layout */
  871. /* stylelint-disable */
  872. grid-template-areas: ${p =>
  873. p.layout === 'drawer bottom'
  874. ? `
  875. 'trace'
  876. 'drawer'
  877. `
  878. : p.layout === 'drawer left'
  879. ? `'drawer trace'`
  880. : `'trace drawer'`};
  881. grid-template-columns: ${p =>
  882. p.layout === 'drawer bottom'
  883. ? '1fr'
  884. : p.layout === 'drawer left'
  885. ? 'min-content 1fr'
  886. : '1fr min-content'};
  887. grid-template-rows: 1fr auto;
  888. `;
  889. const LoadingContainer = styled('div')<{animate: boolean; error?: boolean}>`
  890. display: flex;
  891. justify-content: center;
  892. align-items: center;
  893. flex-direction: column;
  894. left: 50%;
  895. top: 50%;
  896. position: absolute;
  897. height: auto;
  898. font-size: ${p => p.theme.fontSizeMedium};
  899. color: ${p => p.theme.gray300};
  900. z-index: 30;
  901. padding: 24px;
  902. background-color: ${p => p.theme.background};
  903. border-radius: ${p => p.theme.borderRadius};
  904. border: 1px solid ${p => p.theme.border};
  905. transform-origin: 50% 50%;
  906. transform: translate(-50%, -50%);
  907. animation: ${p =>
  908. p.animate
  909. ? `${p.error ? 'showLoadingContainerShake' : 'showLoadingContainer'} 300ms cubic-bezier(0.61, 1, 0.88, 1) forwards`
  910. : 'none'};
  911. @keyframes showLoadingContainer {
  912. from {
  913. opacity: 0.6;
  914. transform: scale(0.99) translate(-50%, -50%);
  915. }
  916. to {
  917. opacity: 1;
  918. transform: scale(1) translate(-50%, -50%);
  919. }
  920. }
  921. @keyframes showLoadingContainerShake {
  922. 0% {
  923. transform: translate(-50%, -50%);
  924. }
  925. 25% {
  926. transform: translate(-51%, -50%);
  927. }
  928. 75% {
  929. transform: translate(-49%, -50%);
  930. }
  931. 100% {
  932. transform: translate(-50%, -50%);
  933. }
  934. }
  935. `;
  936. function TraceLoading() {
  937. return (
  938. // Dont flash the animation on load because it's annoying
  939. <LoadingContainer animate={false}>
  940. <NoMarginIndicator size={24}>
  941. <div>{t('Assembling the trace')}</div>
  942. </NoMarginIndicator>
  943. </LoadingContainer>
  944. );
  945. }
  946. function TraceError() {
  947. const linkref = useRef<HTMLAnchorElement>(null);
  948. const feedback = useFeedbackWidget({buttonRef: linkref});
  949. useEffect(() => {
  950. traceAnalytics.trackFailedToFetchTraceState();
  951. }, []);
  952. return (
  953. <LoadingContainer animate error>
  954. <div>{t('Ughhhhh, we failed to load your trace...')}</div>
  955. <div>
  956. {t('Seeing this often? Send us ')}
  957. {feedback ? (
  958. <a href="#" ref={linkref}>
  959. {t('feedback')}
  960. </a>
  961. ) : (
  962. <a href="mailto:support@sentry.io?subject=Trace%20fails%20to%20load">
  963. {t('feedback')}
  964. </a>
  965. )}
  966. </div>
  967. </LoadingContainer>
  968. );
  969. }
  970. function TraceEmpty() {
  971. const linkref = useRef<HTMLAnchorElement>(null);
  972. const feedback = useFeedbackWidget({buttonRef: linkref});
  973. useEffect(() => {
  974. traceAnalytics.trackEmptyTraceState();
  975. }, []);
  976. return (
  977. <LoadingContainer animate>
  978. <div>{t('This trace does not contain any data?!')}</div>
  979. <div>
  980. {t('Seeing this often? Send us ')}
  981. {feedback ? (
  982. <a href="#" ref={linkref}>
  983. {t('feedback')}
  984. </a>
  985. ) : (
  986. <a href="mailto:support@sentry.io?subject=Trace%20does%20not%20contain%20data">
  987. {t('feedback')}
  988. </a>
  989. )}
  990. </div>
  991. </LoadingContainer>
  992. );
  993. }
  994. const NoMarginIndicator = styled(LoadingIndicator)`
  995. margin: 0;
  996. `;