index.tsx 30 KB

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