index.tsx 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 {flushSync} from 'react-dom';
  12. import styled from '@emotion/styled';
  13. import * as Sentry from '@sentry/react';
  14. import * as qs from 'query-string';
  15. import {Button} from 'sentry/components/button';
  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. TraceMeta,
  30. TraceSplitResults,
  31. } 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 {capitalize} from 'sentry/utils/string/capitalize';
  39. import useApi from 'sentry/utils/useApi';
  40. import {
  41. type DispatchingReducerMiddleware,
  42. useDispatchingReducer,
  43. } from 'sentry/utils/useDispatchingReducer';
  44. import useOrganization from 'sentry/utils/useOrganization';
  45. import {useParams} from 'sentry/utils/useParams';
  46. import useProjects from 'sentry/utils/useProjects';
  47. import {traceAnalytics} from 'sentry/views/performance/newTraceDetails/traceAnalytics';
  48. import {
  49. type ViewManagerScrollAnchor,
  50. VirtualizedViewManager,
  51. } from 'sentry/views/performance/newTraceDetails/traceRenderers/virtualizedViewManager';
  52. import {
  53. searchInTraceTreeText,
  54. searchInTraceTreeTokens,
  55. } from 'sentry/views/performance/newTraceDetails/traceSearch/traceSearchEvaluator';
  56. import {parseTraceSearch} from 'sentry/views/performance/newTraceDetails/traceSearch/traceTokenConverter';
  57. import {TraceShortcuts} from 'sentry/views/performance/newTraceDetails/traceShortcutsModal';
  58. import {
  59. loadTraceViewPreferences,
  60. storeTraceViewPreferences,
  61. } from 'sentry/views/performance/newTraceDetails/traceState/tracePreferences';
  62. import {useTrace} from './traceApi/useTrace';
  63. import {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 {isTraceNode} from './guards';
  69. import {Trace} from './trace';
  70. import {TraceMetadataHeader} from './traceMetadataHeader';
  71. import {TraceReducer, type TraceReducerState} from './traceState';
  72. import {TraceType} from './traceType';
  73. import {TraceUXChangeAlert} from './traceUXChangeBanner';
  74. import {useTraceQueryParamStateSync} from './useTraceQueryParamStateSync';
  75. function decodeScrollQueue(maybePath: unknown): TraceTree.NodePath[] | null {
  76. if (Array.isArray(maybePath)) {
  77. return maybePath;
  78. }
  79. if (typeof maybePath === 'string') {
  80. return [maybePath as TraceTree.NodePath];
  81. }
  82. return null;
  83. }
  84. function logTraceType(type: TraceType, organization: Organization) {
  85. switch (type) {
  86. case TraceType.BROKEN_SUBTRACES:
  87. case TraceType.EMPTY_TRACE:
  88. case TraceType.MULTIPLE_ROOTS:
  89. case TraceType.ONE_ROOT:
  90. case TraceType.NO_ROOT:
  91. case TraceType.ONLY_ERRORS:
  92. traceAnalytics.trackTraceShape(type, organization);
  93. break;
  94. default: {
  95. Sentry.captureMessage('Unknown trace type');
  96. }
  97. }
  98. }
  99. export function TraceView() {
  100. const params = useParams<{traceSlug?: string}>();
  101. const organization = useOrganization();
  102. const traceSlug = useMemo(() => {
  103. const slug = params.traceSlug?.trim() ?? '';
  104. // null and undefined are not valid trace slugs, but they can be passed
  105. // in the URL and need to check for their string coerced values.
  106. if (!slug || slug === 'null' || slug === 'undefined') {
  107. Sentry.withScope(scope => {
  108. scope.setFingerprint(['trace-null-slug']);
  109. Sentry.captureMessage(`Trace slug is empty`);
  110. });
  111. }
  112. return slug;
  113. }, [params.traceSlug]);
  114. useEffect(() => {
  115. trackAnalytics('performance_views.trace_view_v1_page_load', {
  116. organization,
  117. });
  118. }, [organization]);
  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();
  160. return (
  161. <SentryDocumentTitle
  162. title={`${t('Trace')} - ${traceSlug}`}
  163. orgSlug={organization.slug}
  164. >
  165. <NoProjectMessage organization={organization}>
  166. <TraceViewContent
  167. status={trace.status}
  168. trace={trace.data ?? null}
  169. traceSlug={traceSlug}
  170. organization={organization}
  171. traceEventView={traceEventView}
  172. metaResults={meta}
  173. />
  174. </NoProjectMessage>
  175. </SentryDocumentTitle>
  176. );
  177. }
  178. const TRACE_TAB: TraceReducerState['tabs']['tabs'][0] = {
  179. node: 'trace',
  180. label: t('Trace'),
  181. };
  182. const VITALS_TAB: TraceReducerState['tabs']['tabs'][0] = {
  183. node: 'vitals',
  184. label: t('Vitals'),
  185. };
  186. const STATIC_DRAWER_TABS: TraceReducerState['tabs']['tabs'] = [TRACE_TAB];
  187. type TraceViewContentProps = {
  188. metaResults: UseApiQueryResult<TraceMeta | null, any>;
  189. organization: Organization;
  190. status: UseApiQueryResult<any, any>['status'];
  191. trace: TraceSplitResults<TraceTree.Transaction> | null;
  192. traceEventView: EventView;
  193. traceSlug: string;
  194. };
  195. function TraceViewContent(props: TraceViewContentProps) {
  196. const api = useApi();
  197. const organization = props.organization;
  198. const {projects} = useProjects();
  199. const rootEvent = useTraceRootEvent(props.trace);
  200. const loadingTraceRef = useRef<TraceTree | null>(null);
  201. const [forceRender, rerender] = useReducer(x => (x + 1) % Number.MAX_SAFE_INTEGER, 0);
  202. const forceRerender = useCallback(() => {
  203. flushSync(rerender);
  204. }, []);
  205. const initializedRef = useRef(false);
  206. const scrollQueueRef = useRef<
  207. {eventId?: string; path?: TraceTree.NodePath[]} | null | undefined
  208. >(undefined);
  209. if (scrollQueueRef.current === undefined) {
  210. const queryParams = qs.parse(location.search);
  211. const maybeQueue = decodeScrollQueue(queryParams.node);
  212. if (maybeQueue || queryParams.eventId) {
  213. scrollQueueRef.current = {
  214. eventId: queryParams.eventId as string,
  215. path: maybeQueue as TraceTreeNode<TraceTree.NodeValue>['path'],
  216. };
  217. } else {
  218. scrollQueueRef.current = null;
  219. }
  220. }
  221. const previouslyFocusedNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  222. null
  223. );
  224. const previouslyScrolledToNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  225. null
  226. );
  227. const tree = useMemo(() => {
  228. if (props.status === 'error') {
  229. const errorTree = TraceTree.Error(
  230. {
  231. project_slug: projects?.[0]?.slug ?? '',
  232. event_id: props.traceSlug,
  233. },
  234. loadingTraceRef.current
  235. );
  236. return errorTree;
  237. }
  238. if (
  239. props.trace?.transactions.length === 0 &&
  240. props.trace?.orphan_errors.length === 0
  241. ) {
  242. return TraceTree.Empty();
  243. }
  244. if (props.status === 'loading') {
  245. const loadingTrace =
  246. loadingTraceRef.current ??
  247. TraceTree.Loading(
  248. {
  249. project_slug: projects?.[0]?.slug ?? '',
  250. event_id: props.traceSlug,
  251. },
  252. loadingTraceRef.current
  253. );
  254. loadingTraceRef.current = loadingTrace;
  255. return loadingTrace;
  256. }
  257. if (props.trace) {
  258. return TraceTree.FromTrace(props.trace);
  259. }
  260. throw new Error('Invalid trace state');
  261. }, [props.traceSlug, props.trace, props.status, projects]);
  262. const initialQuery = useMemo((): string | undefined => {
  263. const query = qs.parse(location.search);
  264. if (typeof query.search === 'string') {
  265. return query.search;
  266. }
  267. return undefined;
  268. // We only want to decode on load
  269. // eslint-disable-next-line react-hooks/exhaustive-deps
  270. }, []);
  271. const preferences = useMemo(() => loadTraceViewPreferences(), []);
  272. const [traceState, traceDispatch, traceStateEmitter] = useDispatchingReducer(
  273. TraceReducer,
  274. {
  275. rovingTabIndex: {
  276. index: null,
  277. items: null,
  278. node: null,
  279. },
  280. search: {
  281. node: null,
  282. query: initialQuery,
  283. resultIteratorIndex: null,
  284. resultIndex: null,
  285. results: null,
  286. status: undefined,
  287. resultsLookup: new Map(),
  288. },
  289. preferences,
  290. tabs: {
  291. tabs: STATIC_DRAWER_TABS,
  292. current_tab: STATIC_DRAWER_TABS[0] ?? null,
  293. last_clicked_tab: null,
  294. },
  295. }
  296. );
  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,
  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. 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,
  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, 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. useLayoutEffect(() => {
  727. storeTraceViewPreferences(traceState.preferences);
  728. }, [traceState.preferences]);
  729. const [traceGridRef, setTraceGridRef] = useState<HTMLElement | null>(null);
  730. // Memoized because it requires tree traversal
  731. const shape = useMemo(() => tree.shape, [tree]);
  732. useEffect(() => {
  733. if (tree.type !== 'trace') {
  734. return;
  735. }
  736. logTraceType(shape, organization);
  737. }, [tree, shape, organization]);
  738. useLayoutEffect(() => {
  739. if (!tree.root?.space || tree.type !== 'trace') {
  740. return undefined;
  741. }
  742. viewManager.initializeTraceSpace([tree.root.space[0], 0, tree.root.space[1], 1]);
  743. // Whenever the timeline changes, update the trace space
  744. const onTraceTimelineChange = (s: [number, number]) => {
  745. viewManager.updateTraceSpace(s[0], s[1]);
  746. };
  747. tree.on('trace timeline change', onTraceTimelineChange);
  748. return () => {
  749. tree.off('trace timeline change', onTraceTimelineChange);
  750. };
  751. }, [viewManager, tree]);
  752. return (
  753. <TraceExternalLayout>
  754. <TraceUXChangeAlert />
  755. <TraceMetadataHeader
  756. organization={props.organization}
  757. projectID={rootEvent?.data?.projectID ?? ''}
  758. title={rootEvent?.data?.title ?? ''}
  759. traceSlug={props.traceSlug}
  760. traceEventView={props.traceEventView}
  761. />
  762. <TraceInnerLayout>
  763. <TraceToolbar>
  764. <TraceSearchInput
  765. trace_state={traceState}
  766. trace_dispatch={traceDispatch}
  767. onTraceSearch={onTraceSearch}
  768. />
  769. <TraceResetZoomButton viewManager={viewManager} organization={organization} />
  770. <TraceShortcuts />
  771. </TraceToolbar>
  772. <TraceGrid layout={traceState.preferences.layout} ref={setTraceGridRef}>
  773. <Trace
  774. trace={tree}
  775. rerender={forceRerender}
  776. trace_id={props.traceSlug}
  777. trace_state={traceState}
  778. trace_dispatch={traceDispatch}
  779. scrollQueueRef={scrollQueueRef}
  780. initializedRef={initializedRef}
  781. onRowClick={onRowClick}
  782. onTraceLoad={onTraceLoad}
  783. onTraceSearch={onTraceSearch}
  784. previouslyFocusedNodeRef={previouslyFocusedNodeRef}
  785. manager={viewManager}
  786. forceRerender={forceRender}
  787. />
  788. {tree.type === 'error' ? (
  789. <TraceError />
  790. ) : tree.type === 'empty' ? (
  791. <TraceEmpty />
  792. ) : tree.type === 'loading' || scrollQueueRef.current ? (
  793. <TraceLoading />
  794. ) : null}
  795. <TraceDrawer
  796. metaResults={props.metaResults}
  797. traceType={shape}
  798. trace={tree}
  799. traceGridRef={traceGridRef}
  800. traces={props.trace}
  801. manager={viewManager}
  802. trace_state={traceState}
  803. trace_dispatch={traceDispatch}
  804. onTabScrollToNode={onTabScrollToNode}
  805. onScrollToNode={onScrollToNode}
  806. rootEventResults={rootEvent}
  807. traceEventView={props.traceEventView}
  808. />
  809. </TraceGrid>
  810. </TraceInnerLayout>
  811. </TraceExternalLayout>
  812. );
  813. }
  814. function TraceResetZoomButton(props: {
  815. organization: Organization;
  816. viewManager: VirtualizedViewManager;
  817. }) {
  818. const onResetZoom = useCallback(() => {
  819. traceAnalytics.trackResetZoom(props.organization);
  820. props.viewManager.resetZoom();
  821. }, [props.viewManager, props.organization]);
  822. return (
  823. <ResetZoomButton
  824. size="xs"
  825. onClick={onResetZoom}
  826. ref={props.viewManager.registerResetZoomRef}
  827. >
  828. {t('Reset Zoom')}
  829. </ResetZoomButton>
  830. );
  831. }
  832. const ResetZoomButton = styled(Button)`
  833. transition: opacity 0.2s 0.5s ease-in-out;
  834. &[disabled] {
  835. cursor: not-allowed;
  836. opacity: 0.65;
  837. }
  838. `;
  839. const TraceExternalLayout = styled('div')`
  840. display: flex;
  841. flex-direction: column;
  842. flex: 1 1 100%;
  843. ~ footer {
  844. display: none;
  845. }
  846. `;
  847. const TraceInnerLayout = styled('div')`
  848. display: flex;
  849. flex-direction: column;
  850. flex: 1 1 100%;
  851. padding: ${space(2)};
  852. background-color: ${p => p.theme.background};
  853. --info: ${p => p.theme.purple400};
  854. --warning: ${p => p.theme.yellow300};
  855. --error: ${p => p.theme.error};
  856. --fatal: ${p => p.theme.error};
  857. --default: ${p => p.theme.gray300};
  858. --unknown: ${p => p.theme.gray300};
  859. --profile: ${p => p.theme.purple300};
  860. --autogrouped: ${p => p.theme.blue300};
  861. --performance-issue: ${p => p.theme.blue300};
  862. `;
  863. const TraceToolbar = styled('div')`
  864. flex-grow: 0;
  865. display: grid;
  866. grid-template-columns: 1fr min-content min-content;
  867. gap: ${space(1)};
  868. `;
  869. const TraceGrid = styled('div')<{
  870. layout: 'drawer bottom' | 'drawer left' | 'drawer right';
  871. }>`
  872. box-shadow: 0 0 0 1px ${p => p.theme.border};
  873. flex: 1 1 100%;
  874. display: grid;
  875. border-radius: ${p => p.theme.borderRadius};
  876. overflow: hidden;
  877. position: relative;
  878. /* false positive for grid layout */
  879. /* stylelint-disable */
  880. grid-template-areas: ${p =>
  881. p.layout === 'drawer bottom'
  882. ? `
  883. 'trace'
  884. 'drawer'
  885. `
  886. : p.layout === 'drawer left'
  887. ? `'drawer trace'`
  888. : `'trace drawer'`};
  889. grid-template-columns: ${p =>
  890. p.layout === 'drawer bottom'
  891. ? '1fr'
  892. : p.layout === 'drawer left'
  893. ? 'min-content 1fr'
  894. : '1fr min-content'};
  895. grid-template-rows: 1fr auto;
  896. `;
  897. const LoadingContainer = styled('div')<{animate: boolean; error?: boolean}>`
  898. display: flex;
  899. justify-content: center;
  900. align-items: center;
  901. flex-direction: column;
  902. left: 50%;
  903. top: 50%;
  904. position: absolute;
  905. height: auto;
  906. font-size: ${p => p.theme.fontSizeMedium};
  907. color: ${p => p.theme.gray300};
  908. z-index: 30;
  909. padding: 24px;
  910. background-color: ${p => p.theme.background};
  911. border-radius: ${p => p.theme.borderRadius};
  912. border: 1px solid ${p => p.theme.border};
  913. transform-origin: 50% 50%;
  914. transform: translate(-50%, -50%);
  915. animation: ${p =>
  916. p.animate
  917. ? `${p.error ? 'showLoadingContainerShake' : 'showLoadingContainer'} 300ms cubic-bezier(0.61, 1, 0.88, 1) forwards`
  918. : 'none'};
  919. @keyframes showLoadingContainer {
  920. from {
  921. opacity: 0.6;
  922. transform: scale(0.99) translate(-50%, -50%);
  923. }
  924. to {
  925. opacity: 1;
  926. transform: scale(1) translate(-50%, -50%);
  927. }
  928. }
  929. @keyframes showLoadingContainerShake {
  930. 0% {
  931. transform: translate(-50%, -50%);
  932. }
  933. 25% {
  934. transform: translate(-51%, -50%);
  935. }
  936. 75% {
  937. transform: translate(-49%, -50%);
  938. }
  939. 100% {
  940. transform: translate(-50%, -50%);
  941. }
  942. }
  943. `;
  944. function TraceLoading() {
  945. return (
  946. // Dont flash the animation on load because it's annoying
  947. <LoadingContainer animate={false}>
  948. <NoMarginIndicator size={24}>
  949. <div>{t('Assembling the trace')}</div>
  950. </NoMarginIndicator>
  951. </LoadingContainer>
  952. );
  953. }
  954. function TraceError() {
  955. const linkref = useRef<HTMLAnchorElement>(null);
  956. const feedback = useFeedbackWidget({buttonRef: linkref});
  957. useEffect(() => {
  958. traceAnalytics.trackFailedToFetchTraceState();
  959. }, []);
  960. return (
  961. <LoadingContainer animate error>
  962. <div>{t('Ughhhhh, we failed to load your trace...')}</div>
  963. <div>
  964. {t('Seeing this often? Send us ')}
  965. {feedback ? (
  966. <a href="#" ref={linkref}>
  967. {t('feedback')}
  968. </a>
  969. ) : (
  970. <a href="mailto:support@sentry.io?subject=Trace%20fails%20to%20load">
  971. {t('feedback')}
  972. </a>
  973. )}
  974. </div>
  975. </LoadingContainer>
  976. );
  977. }
  978. function TraceEmpty() {
  979. const linkref = useRef<HTMLAnchorElement>(null);
  980. const feedback = useFeedbackWidget({buttonRef: linkref});
  981. useEffect(() => {
  982. traceAnalytics.trackEmptyTraceState();
  983. }, []);
  984. return (
  985. <LoadingContainer animate>
  986. <div>{t('This trace does not contain any data?!')}</div>
  987. <div>
  988. {t('Seeing this often? Send us ')}
  989. {feedback ? (
  990. <a href="#" ref={linkref}>
  991. {t('feedback')}
  992. </a>
  993. ) : (
  994. <a href="mailto:support@sentry.io?subject=Trace%20does%20not%20contain%20data">
  995. {t('feedback')}
  996. </a>
  997. )}
  998. </div>
  999. </LoadingContainer>
  1000. );
  1001. }
  1002. const NoMarginIndicator = styled(LoadingIndicator)`
  1003. margin: 0;
  1004. `;