index.tsx 34 KB

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