index.tsx 35 KB

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