index.tsx 35 KB

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