styles.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. import {Fragment, type PropsWithChildren, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {LocationDescriptor} from 'history';
  4. import {Button, LinkButton} from 'sentry/components/button';
  5. import {CopyToClipboardButton} from 'sentry/components/copyToClipboardButton';
  6. import {
  7. DropdownMenu,
  8. type DropdownMenuProps,
  9. type MenuItemProps,
  10. } from 'sentry/components/dropdownMenu';
  11. import EventTagsDataSection from 'sentry/components/events/eventTagsAndScreenshot/tags';
  12. import {generateStats} from 'sentry/components/events/opsBreakdown';
  13. import {DataSection} from 'sentry/components/events/styles';
  14. import FileSize from 'sentry/components/fileSize';
  15. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  16. import KeyValueData, {
  17. CardPanel,
  18. type KeyValueDataContentProps,
  19. Subject,
  20. } from 'sentry/components/keyValueData';
  21. import {LazyRender, type LazyRenderProps} from 'sentry/components/lazyRender';
  22. import Link from 'sentry/components/links/link';
  23. import Panel from 'sentry/components/panels/panel';
  24. import PanelBody from 'sentry/components/panels/panelBody';
  25. import PanelHeader from 'sentry/components/panels/panelHeader';
  26. import {pickBarColor} from 'sentry/components/performance/waterfall/utils';
  27. import QuestionTooltip from 'sentry/components/questionTooltip';
  28. import {Tooltip} from 'sentry/components/tooltip';
  29. import {
  30. IconChevron,
  31. IconCircleFill,
  32. IconFocus,
  33. IconJson,
  34. IconOpen,
  35. IconPanel,
  36. IconProfiling,
  37. } from 'sentry/icons';
  38. import {t, tct} from 'sentry/locale';
  39. import {space} from 'sentry/styles/space';
  40. import type {Event, EventTransaction} from 'sentry/types/event';
  41. import type {KeyValueListData} from 'sentry/types/group';
  42. import type {Organization} from 'sentry/types/organization';
  43. import type {Project} from 'sentry/types/project';
  44. import {formatBytesBase10} from 'sentry/utils/bytes/formatBytesBase10';
  45. import getDuration from 'sentry/utils/duration/getDuration';
  46. import type {Color, ColorOrAlias} from 'sentry/utils/theme';
  47. import {useNavigate} from 'sentry/utils/useNavigate';
  48. import useOrganization from 'sentry/utils/useOrganization';
  49. import {useParams} from 'sentry/utils/useParams';
  50. import {traceAnalytics} from '../../traceAnalytics';
  51. import {useTransaction} from '../../traceApi/useTransaction';
  52. import {useDrawerContainerRef} from '../../traceDrawer/details/drawerContainerRefContext';
  53. import {makeTraceContinuousProfilingLink} from '../../traceDrawer/traceProfilingLink';
  54. import {
  55. isAutogroupedNode,
  56. isMissingInstrumentationNode,
  57. isRootNode,
  58. isSpanNode,
  59. isTraceErrorNode,
  60. isTransactionNode,
  61. } from '../../traceGuards';
  62. import type {MissingInstrumentationNode} from '../../traceModels/missingInstrumentationNode';
  63. import type {ParentAutogroupNode} from '../../traceModels/parentAutogroupNode';
  64. import type {SiblingAutogroupNode} from '../../traceModels/siblingAutogroupNode';
  65. import {TraceTree} from '../../traceModels/traceTree';
  66. import type {TraceTreeNode} from '../../traceModels/traceTreeNode';
  67. import {useTraceState, useTraceStateDispatch} from '../../traceState/traceStateProvider';
  68. import {useHasTraceNewUi} from '../../useHasTraceNewUi';
  69. const DetailContainer = styled('div')<{hasNewTraceUi?: boolean}>`
  70. display: flex;
  71. flex-direction: column;
  72. gap: ${p => (p.hasNewTraceUi ? 0 : space(2))};
  73. padding: ${space(1)};
  74. ${DataSection} {
  75. padding: 0;
  76. }
  77. `;
  78. const FlexBox = styled('div')`
  79. display: flex;
  80. align-items: center;
  81. `;
  82. const Actions = styled(FlexBox)`
  83. gap: ${space(0.5)};
  84. justify-content: end;
  85. width: 100%;
  86. `;
  87. const Title = styled(FlexBox)`
  88. gap: ${space(1)};
  89. flex-grow: 1;
  90. overflow: hidden;
  91. > span {
  92. min-width: 30px;
  93. }
  94. `;
  95. const LegacyTitleText = styled('div')`
  96. ${p => p.theme.overflowEllipsis}
  97. `;
  98. const TitleText = styled('div')`
  99. font-size: ${p => p.theme.fontSizeExtraLarge};
  100. font-weight: bold;
  101. `;
  102. function TitleWithTestId(props: PropsWithChildren<{}>) {
  103. return <Title data-test-id="trace-drawer-title">{props.children}</Title>;
  104. }
  105. function SubtitleWithCopyButton({text}: {text: string}) {
  106. return (
  107. <SubTitleWrapper>
  108. <StyledSubTitleText>{text}</StyledSubTitleText>
  109. <CopyToClipboardButton
  110. borderless
  111. size="zero"
  112. iconSize="xs"
  113. text={text}
  114. tooltipProps={{disabled: true}}
  115. />
  116. </SubTitleWrapper>
  117. );
  118. }
  119. const SubTitleWrapper = styled(FlexBox)`
  120. ${p => p.theme.overflowEllipsis}
  121. `;
  122. const StyledSubTitleText = styled('span')`
  123. font-size: ${p => p.theme.fontSizeMedium};
  124. color: ${p => p.theme.subText};
  125. `;
  126. function TitleOp({text}: {text: string}) {
  127. return (
  128. <Tooltip
  129. title={
  130. <Fragment>
  131. {text}
  132. <CopyToClipboardButton
  133. borderless
  134. size="zero"
  135. iconSize="xs"
  136. text={text}
  137. tooltipProps={{disabled: true}}
  138. />
  139. </Fragment>
  140. }
  141. showOnlyOnOverflow
  142. isHoverable
  143. >
  144. <TitleOpText>{text}</TitleOpText>
  145. </Tooltip>
  146. );
  147. }
  148. const Type = styled('div')`
  149. font-size: ${p => p.theme.fontSizeSmall};
  150. `;
  151. const TitleOpText = styled('div')`
  152. font-size: 15px;
  153. font-weight: ${p => p.theme.fontWeightBold};
  154. ${p => p.theme.overflowEllipsis}
  155. `;
  156. const Table = styled('table')`
  157. margin-bottom: 0 !important;
  158. td {
  159. overflow: hidden;
  160. }
  161. `;
  162. const IconTitleWrapper = styled(FlexBox)`
  163. gap: ${space(1)};
  164. min-width: 30px;
  165. `;
  166. const IconBorder = styled('div')<{backgroundColor: string; errored?: boolean}>`
  167. background-color: ${p => p.backgroundColor};
  168. border-radius: ${p => p.theme.borderRadius};
  169. padding: 0;
  170. display: flex;
  171. align-items: center;
  172. justify-content: center;
  173. width: 30px;
  174. height: 30px;
  175. min-width: 30px;
  176. svg {
  177. fill: ${p => p.theme.white};
  178. width: 14px;
  179. height: 14px;
  180. }
  181. `;
  182. const LegacyHeaderContainer = styled(FlexBox)`
  183. justify-content: space-between;
  184. gap: ${space(3)};
  185. container-type: inline-size;
  186. @container (max-width: 780px) {
  187. .DropdownMenu {
  188. display: block;
  189. }
  190. .Actions {
  191. display: none;
  192. }
  193. }
  194. @container (min-width: 781px) {
  195. .DropdownMenu {
  196. display: none;
  197. }
  198. }
  199. `;
  200. const HeaderContainer = styled(FlexBox)`
  201. align-items: baseline;
  202. justify-content: space-between;
  203. gap: ${space(3)};
  204. margin-bottom: ${space(2)};
  205. `;
  206. const DURATION_COMPARISON_STATUS_COLORS: {
  207. equal: {light: ColorOrAlias; normal: ColorOrAlias};
  208. faster: {light: ColorOrAlias; normal: ColorOrAlias};
  209. slower: {light: ColorOrAlias; normal: ColorOrAlias};
  210. } = {
  211. faster: {
  212. light: 'green100',
  213. normal: 'green300',
  214. },
  215. slower: {
  216. light: 'red100',
  217. normal: 'red300',
  218. },
  219. equal: {
  220. light: 'gray100',
  221. normal: 'gray300',
  222. },
  223. };
  224. const MIN_PCT_DURATION_DIFFERENCE = 10;
  225. type DurationComparison = {
  226. deltaPct: number;
  227. deltaText: JSX.Element;
  228. status: 'faster' | 'slower' | 'equal';
  229. } | null;
  230. const getDurationComparison = (
  231. baseline: number | undefined,
  232. duration: number,
  233. baseDescription?: string
  234. ): DurationComparison => {
  235. if (!baseline) {
  236. return null;
  237. }
  238. const delta = duration - baseline;
  239. const deltaPct = Math.round(Math.abs((delta / baseline) * 100));
  240. const status = delta > 0 ? 'slower' : delta < 0 ? 'faster' : 'equal';
  241. const formattedBaseDuration = (
  242. <Tooltip
  243. title={baseDescription}
  244. showUnderline
  245. underlineColor={DURATION_COMPARISON_STATUS_COLORS[status].normal}
  246. >
  247. {getDuration(baseline, 2, true)}
  248. </Tooltip>
  249. );
  250. const deltaText =
  251. status === 'equal'
  252. ? tct(`equal to avg [formattedBaseDuration]`, {
  253. formattedBaseDuration,
  254. })
  255. : status === 'faster'
  256. ? tct(`[deltaPct] faster than avg [formattedBaseDuration]`, {
  257. formattedBaseDuration,
  258. deltaPct: `${deltaPct}%`,
  259. })
  260. : tct(`[deltaPct] slower than avg [formattedBaseDuration]`, {
  261. formattedBaseDuration,
  262. deltaPct: `${deltaPct}%`,
  263. });
  264. return {deltaPct, status, deltaText};
  265. };
  266. type DurationProps = {
  267. baseline: number | undefined;
  268. duration: number;
  269. node: TraceTreeNode<TraceTree.NodeValue>;
  270. baseDescription?: string;
  271. ratio?: number;
  272. };
  273. function Duration(props: DurationProps) {
  274. if (typeof props.duration !== 'number' || Number.isNaN(props.duration)) {
  275. return <DurationContainer>{t('unknown')}</DurationContainer>;
  276. }
  277. // Since transactions have ms precision, we show 2 decimal places only if the duration is greater than 1 second.
  278. const precision = isTransactionNode(props.node) ? (props.duration > 1 ? 2 : 0) : 2;
  279. if (props.baseline === undefined || props.baseline === 0) {
  280. return (
  281. <DurationContainer>
  282. {getDuration(props.duration, precision, true)}
  283. </DurationContainer>
  284. );
  285. }
  286. const comparison = getDurationComparison(
  287. props.baseline,
  288. props.duration,
  289. props.baseDescription
  290. );
  291. return (
  292. <Fragment>
  293. <DurationContainer>
  294. {getDuration(props.duration, precision, true)}{' '}
  295. {props.ratio ? `(${(props.ratio * 100).toFixed()}%)` : null}
  296. </DurationContainer>
  297. {comparison && comparison.deltaPct >= MIN_PCT_DURATION_DIFFERENCE ? (
  298. <Comparison status={comparison.status}>{comparison.deltaText}</Comparison>
  299. ) : null}
  300. </Fragment>
  301. );
  302. }
  303. function TableRow({
  304. title,
  305. keep,
  306. children,
  307. prefix,
  308. extra = null,
  309. toolTipText,
  310. }: {
  311. children: React.ReactNode;
  312. title: JSX.Element | string | null;
  313. extra?: React.ReactNode;
  314. keep?: boolean;
  315. prefix?: JSX.Element;
  316. toolTipText?: string;
  317. }) {
  318. if (!keep && !children) {
  319. return null;
  320. }
  321. return (
  322. <tr>
  323. <td className="key">
  324. <Flex>
  325. {prefix}
  326. {title}
  327. {toolTipText ? <StyledQuestionTooltip size="xs" title={toolTipText} /> : null}
  328. </Flex>
  329. </td>
  330. <ValueTd className="value">
  331. <TableValueRow>
  332. <StyledPre>
  333. <span className="val-string">{children}</span>
  334. </StyledPre>
  335. <TableRowButtonContainer>{extra}</TableRowButtonContainer>
  336. </TableValueRow>
  337. </ValueTd>
  338. </tr>
  339. );
  340. }
  341. type HighlightProps = {
  342. avgDuration: number | undefined;
  343. bodyContent: React.ReactNode;
  344. headerContent: React.ReactNode;
  345. node: TraceTreeNode<TraceTree.NodeValue>;
  346. project: Project | undefined;
  347. transaction: EventTransaction | undefined;
  348. };
  349. function Highlights({
  350. node,
  351. transaction: event,
  352. avgDuration,
  353. project,
  354. headerContent,
  355. bodyContent,
  356. }: HighlightProps) {
  357. if (!isTransactionNode(node)) {
  358. return null;
  359. }
  360. const startTimestamp = node.space[0];
  361. const endTimestamp = node.space[0] + node.space[1];
  362. const durationInSeconds = (endTimestamp - startTimestamp) / 1e3;
  363. const comparison = getDurationComparison(
  364. avgDuration,
  365. durationInSeconds,
  366. t('Average duration for this transaction over the last 24 hours')
  367. );
  368. return (
  369. <Fragment>
  370. <HighlightsWrapper>
  371. <HighlightsLeftColumn>
  372. <Tooltip title={node.value.project_slug}>
  373. <ProjectBadge
  374. project={project ? project : {slug: node.value.project_slug}}
  375. avatarSize={18}
  376. hideName
  377. />
  378. </Tooltip>
  379. <VerticalLine />
  380. </HighlightsLeftColumn>
  381. <HighlightsRightColumn>
  382. <HighlightOp>{node.value['transaction.op']}</HighlightOp>
  383. <HighlightsDurationWrapper>
  384. <HighlightDuration>
  385. {getDuration(durationInSeconds, 2, true)}
  386. </HighlightDuration>
  387. {comparison && comparison.deltaPct >= MIN_PCT_DURATION_DIFFERENCE ? (
  388. <HiglightsDurationComparison status={comparison.status}>
  389. {comparison.deltaText}
  390. </HiglightsDurationComparison>
  391. ) : null}
  392. </HighlightsDurationWrapper>
  393. <Panel>
  394. <StyledPanelHeader>{headerContent}</StyledPanelHeader>
  395. <PanelBody>{bodyContent}</PanelBody>
  396. </Panel>
  397. {event ? <HighLightsOpsBreakdown event={event} /> : null}
  398. </HighlightsRightColumn>
  399. </HighlightsWrapper>
  400. <SectionDivider />
  401. </Fragment>
  402. );
  403. }
  404. function HighLightsOpsBreakdown({event}: {event: EventTransaction}) {
  405. const breakdown = generateStats(event, {type: 'no_filter'});
  406. const spansCount =
  407. event.entries?.find(entry => entry.type === 'spans')?.data?.length ?? 0;
  408. return (
  409. <HighlightsOpsBreakdownWrapper>
  410. <HighlightsSpanCount>
  411. {tct('This transaction contains [spansCount] spans', {
  412. spansCount,
  413. })}
  414. </HighlightsSpanCount>
  415. {breakdown.slice(0, 5).map(currOp => {
  416. const {name, percentage} = currOp;
  417. const operationName = typeof name === 'string' ? name : t('Other');
  418. const color = pickBarColor(operationName);
  419. const pctLabel = isFinite(percentage) ? Math.round(percentage * 100) : '∞';
  420. return (
  421. <HighlightsOpRow key={operationName}>
  422. <IconCircleFill size="xs" color={color as Color} />
  423. {operationName}
  424. <HighlightsOpPct>{pctLabel}%</HighlightsOpPct>
  425. </HighlightsOpRow>
  426. );
  427. })}
  428. {breakdown.length > 5 ? (
  429. <HighlightsOpsBreakdownMoreCount>
  430. {tct('+ [moreCount] more', {moreCount: breakdown.length - 5})}
  431. </HighlightsOpsBreakdownMoreCount>
  432. ) : null}
  433. </HighlightsOpsBreakdownWrapper>
  434. );
  435. }
  436. const HighlightsOpsBreakdownMoreCount = styled('div')`
  437. font-size: 12px;
  438. color: ${p => p.theme.subText};
  439. `;
  440. const HighlightsOpPct = styled('div')`
  441. color: ${p => p.theme.subText};
  442. font-size: 14px;
  443. `;
  444. const HighlightsSpanCount = styled('div')`
  445. margin-bottom: ${space(0.25)};
  446. `;
  447. const HighlightsOpRow = styled(FlexBox)`
  448. font-size: 13px;
  449. gap: ${space(0.5)};
  450. `;
  451. const HighlightsOpsBreakdownWrapper = styled(FlexBox)`
  452. align-items: flex-start;
  453. flex-direction: column;
  454. gap: ${space(0.25)};
  455. `;
  456. const HiglightsDurationComparison = styled('div')<{status: string}>`
  457. white-space: nowrap;
  458. border-radius: 12px;
  459. color: ${p => p.theme[DURATION_COMPARISON_STATUS_COLORS[p.status].normal]};
  460. background-color: ${p => p.theme[DURATION_COMPARISON_STATUS_COLORS[p.status].light]};
  461. border: solid 1px ${p => p.theme[DURATION_COMPARISON_STATUS_COLORS[p.status].light]};
  462. font-size: ${p => p.theme.fontSizeExtraSmall};
  463. padding: ${space(0.25)} ${space(1)};
  464. display: inline-block;
  465. height: 21px;
  466. `;
  467. const HighlightsDurationWrapper = styled(FlexBox)`
  468. gap: ${space(1)};
  469. margin-bottom: ${space(1)};
  470. `;
  471. const HighlightDuration = styled('div')`
  472. font-size: ${p => p.theme.headerFontSize};
  473. font-weight: 400;
  474. `;
  475. const HighlightOp = styled('div')`
  476. font-weight: bold;
  477. font-size: ${p => p.theme.fontSizeMedium};
  478. line-height: normal;
  479. `;
  480. const StyledPanelHeader = styled(PanelHeader)`
  481. font-weight: normal;
  482. padding: 0;
  483. line-height: normal;
  484. text-transform: none;
  485. font-size: ${p => p.theme.fontSizeMedium};
  486. overflow: hidden;
  487. `;
  488. const SectionDivider = styled('hr')`
  489. border-color: ${p => p.theme.translucentBorder};
  490. margin: ${space(1.5)} 0;
  491. `;
  492. const VerticalLine = styled('div')`
  493. width: 1px;
  494. height: 100%;
  495. background-color: ${p => p.theme.border};
  496. margin-top: ${space(0.5)};
  497. `;
  498. const HighlightsWrapper = styled('div')`
  499. display: flex;
  500. align-items: stretch;
  501. gap: ${space(1)};
  502. width: 100%;
  503. overflow: hidden;
  504. margin: ${space(1)} 0;
  505. `;
  506. const HighlightsLeftColumn = styled('div')`
  507. display: flex;
  508. flex-direction: column;
  509. justify-content: center;
  510. align-items: center;
  511. `;
  512. const HighlightsRightColumn = styled('div')`
  513. display: flex;
  514. flex-direction: column;
  515. justify-content: left;
  516. height: 100%;
  517. flex: 1;
  518. overflow: hidden;
  519. `;
  520. function IssuesLink({
  521. node,
  522. children,
  523. }: {
  524. children: React.ReactNode;
  525. node: TraceTreeNode<TraceTree.NodeValue>;
  526. }) {
  527. const organization = useOrganization();
  528. const params = useParams<{traceSlug?: string}>();
  529. const traceSlug = params.traceSlug?.trim() ?? '';
  530. // Adding a buffer of 15mins for errors only traces, where there is no concept of
  531. // trace duration and start equals end timestamps.
  532. const buffer = node.space[1] > 0 ? 0 : 15 * 60 * 1000;
  533. return (
  534. <Link
  535. to={{
  536. pathname: `/organizations/${organization.slug}/issues/`,
  537. query: {
  538. query: `trace:${traceSlug}`,
  539. start: new Date(node.space[0] - buffer).toISOString(),
  540. end: new Date(node.space[0] + node.space[1] + buffer).toISOString(),
  541. // If we don't pass the project param, the issues page will filter by the last selected project.
  542. // Traces can have multiple projects, so we query issues by all projects and rely on our search query to filter the results.
  543. project: -1,
  544. },
  545. }}
  546. >
  547. {children}
  548. </Link>
  549. );
  550. }
  551. const LAZY_RENDER_PROPS: Partial<LazyRenderProps> = {
  552. observerOptions: {rootMargin: '50px'},
  553. };
  554. const DurationContainer = styled('span')`
  555. font-weight: ${p => p.theme.fontWeightBold};
  556. margin-right: ${space(1)};
  557. `;
  558. const Comparison = styled('span')<{status: 'faster' | 'slower' | 'equal'}>`
  559. color: ${p => p.theme[DURATION_COMPARISON_STATUS_COLORS[p.status].normal]};
  560. `;
  561. const Flex = styled('div')`
  562. display: flex;
  563. align-items: center;
  564. `;
  565. const TableValueRow = styled('div')`
  566. display: grid;
  567. grid-template-columns: auto min-content;
  568. gap: ${space(1)};
  569. border-radius: 4px;
  570. background-color: ${p => p.theme.surface200};
  571. margin: 2px;
  572. `;
  573. const StyledQuestionTooltip = styled(QuestionTooltip)`
  574. margin-left: ${space(0.5)};
  575. `;
  576. const StyledPre = styled('pre')`
  577. margin: 0 !important;
  578. background-color: transparent !important;
  579. `;
  580. const TableRowButtonContainer = styled('div')`
  581. padding: 8px 10px;
  582. `;
  583. const ValueTd = styled('td')`
  584. position: relative;
  585. `;
  586. function getThreadIdFromNode(
  587. node: TraceTreeNode<TraceTree.NodeValue>,
  588. transaction: EventTransaction | undefined
  589. ): string | undefined {
  590. if (isSpanNode(node) && node.value.data?.['thread.id']) {
  591. return node.value.data['thread.id'];
  592. }
  593. if (transaction) {
  594. return transaction.contexts?.trace?.data?.['thread.id'];
  595. }
  596. return undefined;
  597. }
  598. // Renders the dropdown menu list at the root trace drawer content container level, to prevent
  599. // being stacked under other content.
  600. function DropdownMenuWithPortal(props: DropdownMenuProps) {
  601. const drawerContainerRef = useDrawerContainerRef();
  602. return (
  603. <DropdownMenu
  604. {...props}
  605. usePortal={!!drawerContainerRef}
  606. portalContainerRef={drawerContainerRef}
  607. />
  608. );
  609. }
  610. function TypeSafeBoolean<T>(value: T | null | undefined): value is NonNullable<T> {
  611. return value !== null && value !== undefined;
  612. }
  613. function PanelPositionDropDown({organization}: {organization: Organization}) {
  614. const traceState = useTraceState();
  615. const traceDispatch = useTraceStateDispatch();
  616. const options: MenuItemProps[] = [];
  617. const layoutOptions = traceState.preferences.drawer.layoutOptions;
  618. if (layoutOptions.includes('drawer left')) {
  619. options.push({
  620. key: 'drawer-left',
  621. onAction: () => {
  622. traceAnalytics.trackLayoutChange('drawer left', organization);
  623. traceDispatch({type: 'set layout', payload: 'drawer left'});
  624. },
  625. leadingItems: <IconPanel direction="left" size="xs" />,
  626. label: t('Left'),
  627. disabled: traceState.preferences.layout === 'drawer left',
  628. });
  629. }
  630. if (layoutOptions.includes('drawer right')) {
  631. options.push({
  632. key: 'drawer-right',
  633. onAction: () => {
  634. traceAnalytics.trackLayoutChange('drawer right', organization);
  635. traceDispatch({type: 'set layout', payload: 'drawer right'});
  636. },
  637. leadingItems: <IconPanel direction="right" size="xs" />,
  638. label: t('Right'),
  639. disabled: traceState.preferences.layout === 'drawer right',
  640. });
  641. }
  642. if (layoutOptions.includes('drawer bottom')) {
  643. options.push({
  644. key: 'drawer-bottom',
  645. onAction: () => {
  646. traceAnalytics.trackLayoutChange('drawer bottom', organization);
  647. traceDispatch({type: 'set layout', payload: 'drawer bottom'});
  648. },
  649. leadingItems: <IconPanel direction="down" size="xs" />,
  650. label: t('Bottom'),
  651. disabled: traceState.preferences.layout === 'drawer bottom',
  652. });
  653. }
  654. return (
  655. <DropdownMenu
  656. size="sm"
  657. items={options}
  658. menuTitle={<div>{t('Panel Position')}</div>}
  659. trigger={triggerProps => (
  660. <Tooltip title={t('Panel Position')}>
  661. <ActionButton
  662. {...triggerProps}
  663. size="xs"
  664. aria-label={t('Panel position')}
  665. icon={<IconPanel direction="right" size="xs" />}
  666. />
  667. </Tooltip>
  668. )}
  669. />
  670. );
  671. }
  672. function NodeActions(props: {
  673. node: TraceTreeNode<any>;
  674. onTabScrollToNode: (
  675. node:
  676. | TraceTreeNode<any>
  677. | ParentAutogroupNode
  678. | SiblingAutogroupNode
  679. | MissingInstrumentationNode
  680. ) => void;
  681. organization: Organization;
  682. eventSize?: number | undefined;
  683. }) {
  684. const hasNewTraceUi = useHasTraceNewUi();
  685. const organization = useOrganization();
  686. const params = useParams<{traceSlug?: string}>();
  687. const {data: transaction} = useTransaction({
  688. node: isTransactionNode(props.node) ? props.node : null,
  689. organization,
  690. });
  691. const profilerId: string = useMemo(() => {
  692. if (isTransactionNode(props.node)) {
  693. return props.node.value.profiler_id;
  694. }
  695. if (isSpanNode(props.node)) {
  696. return props.node.value.sentry_tags?.profiler_id ?? '';
  697. }
  698. return '';
  699. }, [props]);
  700. const profileLink = makeTraceContinuousProfilingLink(props.node, profilerId, {
  701. orgSlug: props.organization.slug,
  702. projectSlug: props.node.metadata.project_slug ?? '',
  703. traceId: params.traceSlug ?? '',
  704. threadId: getThreadIdFromNode(props.node, transaction),
  705. });
  706. if (!hasNewTraceUi) {
  707. return (
  708. <LegacyNodeActions
  709. {...props}
  710. profileLink={profileLink}
  711. profilerId={profilerId}
  712. transaction={transaction}
  713. />
  714. );
  715. }
  716. return (
  717. <ActionWrapper>
  718. <Tooltip title={t('Show in view')}>
  719. <ActionButton
  720. onClick={_e => {
  721. traceAnalytics.trackShowInView(props.organization);
  722. props.onTabScrollToNode(props.node);
  723. }}
  724. size="xs"
  725. aria-label={t('Show in view')}
  726. icon={<IconFocus size="xs" />}
  727. />
  728. </Tooltip>
  729. {isTransactionNode(props.node) ? (
  730. <Tooltip title={t('JSON')}>
  731. <ActionButton
  732. onClick={() => traceAnalytics.trackViewEventJSON(props.organization)}
  733. href={`/api/0/projects/${props.organization.slug}/${props.node.value.project_slug}/events/${props.node.value.event_id}/json/`}
  734. size="xs"
  735. aria-label={t('JSON')}
  736. icon={<IconJson size="xs" />}
  737. />
  738. </Tooltip>
  739. ) : null}
  740. {profileLink ? (
  741. <Tooltip title={t('Continuous Profile')}>
  742. <ActionButton
  743. size="xs"
  744. aria-label={t('Continuous Profile')}
  745. icon={<IconProfiling size="xs" />}
  746. />
  747. </Tooltip>
  748. ) : null}
  749. <PanelPositionDropDown organization={organization} />
  750. </ActionWrapper>
  751. );
  752. }
  753. const ActionButton = styled(Button)`
  754. border: none;
  755. background-color: transparent;
  756. box-shadow: none;
  757. transition: none !important;
  758. opacity: 0.8;
  759. height: 24px;
  760. max-height: 24px;
  761. &:hover {
  762. border: none;
  763. background-color: transparent;
  764. box-shadow: none;
  765. opacity: 1;
  766. }
  767. `;
  768. const ActionWrapper = styled('div')`
  769. display: flex;
  770. align-items: center;
  771. gap: ${space(0.25)};
  772. `;
  773. function LegacyNodeActions(props: {
  774. node: TraceTreeNode<any>;
  775. onTabScrollToNode: (
  776. node:
  777. | TraceTreeNode<any>
  778. | ParentAutogroupNode
  779. | SiblingAutogroupNode
  780. | MissingInstrumentationNode
  781. ) => void;
  782. profileLink: LocationDescriptor | null;
  783. profilerId: string;
  784. transaction: EventTransaction | undefined;
  785. eventSize?: number | undefined;
  786. }) {
  787. const navigate = useNavigate();
  788. const organization = useOrganization();
  789. const items = useMemo((): MenuItemProps[] => {
  790. const showInView: MenuItemProps = {
  791. key: 'show-in-view',
  792. label: t('Show in View'),
  793. onAction: () => {
  794. traceAnalytics.trackShowInView(organization);
  795. props.onTabScrollToNode(props.node);
  796. },
  797. };
  798. const eventId =
  799. props.node.metadata.event_id ??
  800. TraceTree.ParentTransaction(props.node)?.metadata.event_id;
  801. const projectSlug =
  802. props.node.metadata.project_slug ??
  803. TraceTree.ParentTransaction(props.node)?.metadata.project_slug;
  804. const eventSize = props.eventSize;
  805. const jsonDetails: MenuItemProps = {
  806. key: 'json-details',
  807. onAction: () => {
  808. traceAnalytics.trackViewEventJSON(organization);
  809. window.open(
  810. `/api/0/projects/${organization.slug}/${projectSlug}/events/${eventId}/json/`,
  811. '_blank'
  812. );
  813. },
  814. label:
  815. t('JSON') +
  816. (typeof eventSize === 'number' ? ` (${formatBytesBase10(eventSize, 0)})` : ''),
  817. };
  818. const continuousProfileLink: MenuItemProps | null = props.profileLink
  819. ? {
  820. key: 'continuous-profile',
  821. onAction: () => {
  822. traceAnalytics.trackViewContinuousProfile(organization);
  823. navigate(props.profileLink!);
  824. },
  825. label: t('Continuous Profile'),
  826. }
  827. : null;
  828. if (isTransactionNode(props.node)) {
  829. return [showInView, jsonDetails, continuousProfileLink].filter(TypeSafeBoolean);
  830. }
  831. if (isSpanNode(props.node)) {
  832. return [showInView, continuousProfileLink].filter(TypeSafeBoolean);
  833. }
  834. if (isMissingInstrumentationNode(props.node)) {
  835. return [showInView, continuousProfileLink].filter(TypeSafeBoolean);
  836. }
  837. if (isTraceErrorNode(props.node)) {
  838. return [showInView, continuousProfileLink].filter(TypeSafeBoolean);
  839. }
  840. if (isRootNode(props.node)) {
  841. return [showInView];
  842. }
  843. if (isAutogroupedNode(props.node)) {
  844. return [showInView];
  845. }
  846. return [showInView];
  847. }, [props, navigate, organization]);
  848. return (
  849. <ActionsContainer>
  850. <Actions className="Actions">
  851. {props.profileLink ? (
  852. <LinkButton size="xs" to={props.profileLink}>
  853. {t('Continuous Profile')}
  854. </LinkButton>
  855. ) : null}
  856. <Button
  857. size="xs"
  858. onClick={_e => {
  859. traceAnalytics.trackShowInView(organization);
  860. props.onTabScrollToNode(props.node);
  861. }}
  862. >
  863. {t('Show in view')}
  864. </Button>
  865. {isTransactionNode(props.node) ? (
  866. <LinkButton
  867. size="xs"
  868. icon={<IconOpen />}
  869. onClick={() => traceAnalytics.trackViewEventJSON(organization)}
  870. href={`/api/0/projects/${organization.slug}/${props.node.value.project_slug}/events/${props.node.value.event_id}/json/`}
  871. external
  872. >
  873. {t('JSON')} (<FileSize bytes={props.eventSize ?? 0} />)
  874. </LinkButton>
  875. ) : null}
  876. </Actions>
  877. <DropdownMenuWithPortal
  878. items={items}
  879. className="DropdownMenu"
  880. position="bottom-end"
  881. trigger={triggerProps => (
  882. <ActionsButtonTrigger size="xs" {...triggerProps}>
  883. {t('Actions')}
  884. <IconChevron direction="down" size="xs" />
  885. </ActionsButtonTrigger>
  886. )}
  887. />
  888. </ActionsContainer>
  889. );
  890. }
  891. const ActionsButtonTrigger = styled(Button)`
  892. svg {
  893. margin-left: ${space(0.5)};
  894. width: 10px;
  895. height: 10px;
  896. }
  897. `;
  898. const ActionsContainer = styled('div')`
  899. display: flex;
  900. justify-content: end;
  901. align-items: center;
  902. gap: ${space(1)};
  903. `;
  904. function EventTags({projectSlug, event}: {event: Event; projectSlug: string}) {
  905. const hasNewTraceUi = useHasTraceNewUi();
  906. if (!hasNewTraceUi) {
  907. return <LegacyEventTags event={event} projectSlug={projectSlug} />;
  908. }
  909. return <EventTagsDataSection event={event} projectSlug={projectSlug} />;
  910. }
  911. function LegacyEventTags({projectSlug, event}: {event: Event; projectSlug: string}) {
  912. return (
  913. <LazyRender {...TraceDrawerComponents.LAZY_RENDER_PROPS} containerHeight={200}>
  914. <TagsWrapper>
  915. <EventTagsDataSection event={event} projectSlug={projectSlug} />
  916. </TagsWrapper>
  917. </LazyRender>
  918. );
  919. }
  920. const TagsWrapper = styled('div')`
  921. h3 {
  922. color: ${p => p.theme.textColor};
  923. }
  924. `;
  925. export type SectionCardKeyValueList = KeyValueListData;
  926. function SectionCard({
  927. items,
  928. title,
  929. disableTruncate,
  930. sortAlphabetically = false,
  931. itemProps = {},
  932. }: {
  933. items: SectionCardKeyValueList;
  934. title: React.ReactNode;
  935. disableTruncate?: boolean;
  936. itemProps?: Partial<KeyValueDataContentProps>;
  937. sortAlphabetically?: boolean;
  938. }) {
  939. const contentItems = items.map(item => ({item, ...itemProps}));
  940. return (
  941. <CardWrapper>
  942. <KeyValueData.Card
  943. title={title}
  944. contentItems={contentItems}
  945. sortAlphabetically={sortAlphabetically}
  946. truncateLength={disableTruncate ? Infinity : 5}
  947. />
  948. </CardWrapper>
  949. );
  950. }
  951. // This is trace-view specific styling. The card is rendered in a number of different places
  952. // with tests failing otherwise, since @container queries are not supported by the version of
  953. // jsdom currently used by jest.
  954. const CardWrapper = styled('div')`
  955. ${CardPanel} {
  956. container-type: inline-size;
  957. }
  958. ${Subject} {
  959. @container (width < 350px) {
  960. max-width: 200px;
  961. }
  962. }
  963. `;
  964. function SectionCardGroup({children}: {children: React.ReactNode}) {
  965. return <KeyValueData.Container>{children}</KeyValueData.Container>;
  966. }
  967. function CopyableCardValueWithLink({
  968. value,
  969. linkTarget,
  970. linkText,
  971. onClick,
  972. }: {
  973. value: React.ReactNode;
  974. linkTarget?: LocationDescriptor;
  975. linkText?: string;
  976. onClick?: () => void;
  977. }) {
  978. return (
  979. <CardValueContainer>
  980. <CardValueText>
  981. {value}
  982. {typeof value === 'string' ? (
  983. <StyledCopyToClipboardButton
  984. borderless
  985. size="zero"
  986. iconSize="xs"
  987. text={value}
  988. />
  989. ) : null}
  990. </CardValueText>
  991. {linkTarget && linkTarget ? (
  992. <Link to={linkTarget} onClick={onClick}>
  993. {linkText}
  994. </Link>
  995. ) : null}
  996. </CardValueContainer>
  997. );
  998. }
  999. function TraceDataSection({event}: {event: EventTransaction}) {
  1000. const traceData = event.contexts.trace?.data;
  1001. if (!traceData) {
  1002. return null;
  1003. }
  1004. return (
  1005. <SectionCard
  1006. items={Object.entries(traceData).map(([key, value]) => ({
  1007. key,
  1008. subject: key,
  1009. value,
  1010. }))}
  1011. title={t('Trace Data')}
  1012. />
  1013. );
  1014. }
  1015. const StyledCopyToClipboardButton = styled(CopyToClipboardButton)`
  1016. transform: translateY(2px);
  1017. `;
  1018. const CardValueContainer = styled(FlexBox)`
  1019. justify-content: space-between;
  1020. gap: ${space(1)};
  1021. flex-wrap: wrap;
  1022. `;
  1023. const CardValueText = styled('span')`
  1024. overflow-wrap: anywhere;
  1025. `;
  1026. export const CardContentSubject = styled('div')`
  1027. grid-column: span 1;
  1028. font-family: ${p => p.theme.text.familyMono};
  1029. word-wrap: break-word;
  1030. `;
  1031. const TraceDrawerComponents = {
  1032. DetailContainer,
  1033. FlexBox,
  1034. Title: TitleWithTestId,
  1035. Type,
  1036. TitleOp,
  1037. HeaderContainer,
  1038. LegacyHeaderContainer,
  1039. Highlights,
  1040. Actions,
  1041. NodeActions,
  1042. Table,
  1043. IconTitleWrapper,
  1044. IconBorder,
  1045. TitleText,
  1046. LegacyTitleText,
  1047. Duration,
  1048. TableRow,
  1049. LAZY_RENDER_PROPS,
  1050. TableRowButtonContainer,
  1051. TableValueRow,
  1052. IssuesLink,
  1053. SectionCard,
  1054. CopyableCardValueWithLink,
  1055. EventTags,
  1056. SubtitleWithCopyButton,
  1057. TraceDataSection,
  1058. SectionCardGroup,
  1059. DropdownMenuWithPortal,
  1060. };
  1061. export {TraceDrawerComponents};