index.tsx 29 KB

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