index.tsx 32 KB

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