index.tsx 33 KB

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