index.tsx 35 KB

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