index.tsx 32 KB

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