index.tsx 33 KB

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