index.tsx 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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/traceShortcutsModal';
  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. <ResetZoomButton
  784. size="xs"
  785. onClick={onResetZoom}
  786. ref={props.viewManager.registerResetZoomRef}
  787. >
  788. {t('Reset Zoom')}
  789. </ResetZoomButton>
  790. );
  791. }
  792. const ResetZoomButton = styled(Button)`
  793. transition: opacity 0.2s 0.5s ease-in-out;
  794. &[disabled] {
  795. cursor: not-allowed;
  796. opacity: 0.65;
  797. }
  798. `;
  799. const TraceExternalLayout = styled('div')`
  800. display: flex;
  801. flex-direction: column;
  802. flex: 1 1 100%;
  803. ~ footer {
  804. display: none;
  805. }
  806. `;
  807. const TraceInnerLayout = styled('div')`
  808. display: flex;
  809. flex-direction: column;
  810. flex: 1 1 100%;
  811. padding: ${space(2)};
  812. background-color: ${p => p.theme.background};
  813. --info: ${p => p.theme.purple400};
  814. --warning: ${p => p.theme.yellow300};
  815. --error: ${p => p.theme.error};
  816. --fatal: ${p => p.theme.error};
  817. --default: ${p => p.theme.gray300};
  818. --unknown: ${p => p.theme.gray300};
  819. --profile: ${p => p.theme.purple300};
  820. --autogrouped: ${p => p.theme.blue300};
  821. --performance-issue: ${p => p.theme.blue300};
  822. `;
  823. const TraceToolbar = styled('div')`
  824. flex-grow: 0;
  825. display: grid;
  826. grid-template-columns: 1fr min-content min-content;
  827. gap: ${space(1)};
  828. `;
  829. const TraceGrid = styled('div')<{
  830. layout: 'drawer bottom' | 'drawer left' | 'drawer right';
  831. }>`
  832. box-shadow: 0 0 0 1px ${p => p.theme.border};
  833. flex: 1 1 100%;
  834. display: grid;
  835. border-radius: ${p => p.theme.borderRadius};
  836. overflow: hidden;
  837. position: relative;
  838. /* false positive for grid layout */
  839. /* stylelint-disable */
  840. grid-template-areas: ${p =>
  841. p.layout === 'drawer bottom'
  842. ? `
  843. 'trace'
  844. 'drawer'
  845. `
  846. : p.layout === 'drawer left'
  847. ? `'drawer trace'`
  848. : `'trace drawer'`};
  849. grid-template-columns: ${p =>
  850. p.layout === 'drawer bottom'
  851. ? '1fr'
  852. : p.layout === 'drawer left'
  853. ? 'min-content 1fr'
  854. : '1fr min-content'};
  855. grid-template-rows: 1fr auto;
  856. `;
  857. const LoadingContainer = styled('div')<{animate: boolean; error?: boolean}>`
  858. display: flex;
  859. justify-content: center;
  860. align-items: center;
  861. flex-direction: column;
  862. left: 50%;
  863. top: 50%;
  864. position: absolute;
  865. height: auto;
  866. font-size: ${p => p.theme.fontSizeMedium};
  867. color: ${p => p.theme.gray300};
  868. z-index: 30;
  869. padding: 24px;
  870. background-color: ${p => p.theme.background};
  871. border-radius: ${p => p.theme.borderRadius};
  872. border: 1px solid ${p => p.theme.border};
  873. transform-origin: 50% 50%;
  874. transform: translate(-50%, -50%);
  875. animation: ${p =>
  876. p.animate
  877. ? `${p.error ? 'showLoadingContainerShake' : 'showLoadingContainer'} 300ms cubic-bezier(0.61, 1, 0.88, 1) forwards`
  878. : 'none'};
  879. @keyframes showLoadingContainer {
  880. from {
  881. opacity: 0.6;
  882. transform: scale(0.99) translate(-50%, -50%);
  883. }
  884. to {
  885. opacity: 1;
  886. transform: scale(1) translate(-50%, -50%);
  887. }
  888. }
  889. @keyframes showLoadingContainerShake {
  890. 0% {
  891. transform: translate(-50%, -50%);
  892. }
  893. 25% {
  894. transform: translate(-51%, -50%);
  895. }
  896. 75% {
  897. transform: translate(-49%, -50%);
  898. }
  899. 100% {
  900. transform: translate(-50%, -50%);
  901. }
  902. }
  903. `;
  904. function TraceLoading() {
  905. return (
  906. // Dont flash the animation on load because it's annoying
  907. <LoadingContainer animate={false}>
  908. <NoMarginIndicator size={24}>
  909. <div>{t('Assembling the trace')}</div>
  910. </NoMarginIndicator>
  911. </LoadingContainer>
  912. );
  913. }
  914. function TraceError() {
  915. const linkref = useRef<HTMLAnchorElement>(null);
  916. const feedback = useFeedbackWidget({buttonRef: linkref});
  917. useEffect(() => {
  918. traceAnalytics.trackFailedToFetchTraceState();
  919. }, []);
  920. return (
  921. <LoadingContainer animate error>
  922. <div>{t('Ughhhhh, we failed to load your trace...')}</div>
  923. <div>
  924. {t('Seeing this often? Send us ')}
  925. {feedback ? (
  926. <a href="#" ref={linkref}>
  927. {t('feedback')}
  928. </a>
  929. ) : (
  930. <a href="mailto:support@sentry.io?subject=Trace%20fails%20to%20load">
  931. {t('feedback')}
  932. </a>
  933. )}
  934. </div>
  935. </LoadingContainer>
  936. );
  937. }
  938. function TraceEmpty() {
  939. const linkref = useRef<HTMLAnchorElement>(null);
  940. const feedback = useFeedbackWidget({buttonRef: linkref});
  941. useEffect(() => {
  942. traceAnalytics.trackEmptyTraceState();
  943. }, []);
  944. return (
  945. <LoadingContainer animate>
  946. <div>{t('This trace does not contain any data?!')}</div>
  947. <div>
  948. {t('Seeing this often? Send us ')}
  949. {feedback ? (
  950. <a href="#" ref={linkref}>
  951. {t('feedback')}
  952. </a>
  953. ) : (
  954. <a href="mailto:support@sentry.io?subject=Trace%20does%20not%20contain%20data">
  955. {t('feedback')}
  956. </a>
  957. )}
  958. </div>
  959. </LoadingContainer>
  960. );
  961. }
  962. const NoMarginIndicator = styled(LoadingIndicator)`
  963. margin: 0;
  964. `;