index.tsx 34 KB

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