index.tsx 35 KB

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