projectsTable.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import {Fragment, memo, useCallback, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {hasEveryAccess} from 'sentry/components/acl/access';
  4. import {LinkButton} from 'sentry/components/button';
  5. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  6. import {PanelTable} from 'sentry/components/panels/panelTable';
  7. import {Tooltip} from 'sentry/components/tooltip';
  8. import {IconArrow, IconChevron, IconSettings} from 'sentry/icons';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import type {Project} from 'sentry/types/project';
  12. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  13. import oxfordizeArray from 'sentry/utils/oxfordizeArray';
  14. import useOrganization from 'sentry/utils/useOrganization';
  15. import {PercentInput} from 'sentry/views/settings/dynamicSampling/percentInput';
  16. import {useHasDynamicSamplingWriteAccess} from 'sentry/views/settings/dynamicSampling/utils/access';
  17. import {parsePercent} from 'sentry/views/settings/dynamicSampling/utils/parsePercent';
  18. interface ProjectItem {
  19. count: number;
  20. initialSampleRate: string;
  21. ownCount: number;
  22. project: Project;
  23. sampleRate: string;
  24. subProjects: SubProject[];
  25. error?: string;
  26. }
  27. interface Props extends Omit<React.ComponentProps<typeof StyledPanelTable>, 'headers'> {
  28. items: ProjectItem[];
  29. rateHeader: React.ReactNode;
  30. canEdit?: boolean;
  31. inactiveItems?: ProjectItem[];
  32. inputTooltip?: string;
  33. onChange?: (projectId: string, value: string) => void;
  34. }
  35. const COLUMN_COUNT = 4;
  36. export function ProjectsTable({
  37. items,
  38. inactiveItems = [],
  39. inputTooltip,
  40. canEdit,
  41. rateHeader,
  42. onChange,
  43. ...props
  44. }: Props) {
  45. const hasAccess = useHasDynamicSamplingWriteAccess();
  46. const [tableSort, setTableSort] = useState<'asc' | 'desc'>('desc');
  47. const handleTableSort = useCallback(() => {
  48. setTableSort(value => (value === 'asc' ? 'desc' : 'asc'));
  49. }, []);
  50. const [isExpanded, setIsExpanded] = useState(false);
  51. const hasActiveItems = items.length > 0;
  52. const mainItems = hasActiveItems ? items : inactiveItems;
  53. return (
  54. <StyledPanelTable
  55. {...props}
  56. isEmpty={!items.length && !inactiveItems.length}
  57. headers={[
  58. t('Project'),
  59. <SortableHeader type="button" key="spans" onClick={handleTableSort}>
  60. {t('Accepted Spans')}
  61. <IconArrow direction={tableSort === 'desc' ? 'down' : 'up'} size="xs" />
  62. </SortableHeader>,
  63. t('Stored Spans'),
  64. rateHeader,
  65. ]}
  66. >
  67. {mainItems
  68. .toSorted((a, b) => {
  69. if (a.count === b.count) {
  70. return a.project.slug.localeCompare(b.project.slug);
  71. }
  72. if (tableSort === 'asc') {
  73. return a.count - b.count;
  74. }
  75. return b.count - a.count;
  76. })
  77. .map(item => (
  78. <TableRow
  79. key={item.project.id}
  80. canEdit={canEdit}
  81. onChange={onChange}
  82. inputTooltip={inputTooltip}
  83. hasAccess={hasAccess}
  84. {...item}
  85. />
  86. ))}
  87. {hasActiveItems && inactiveItems.length > 0 && (
  88. <SectionHeader
  89. isExpanded={isExpanded}
  90. setIsExpanded={setIsExpanded}
  91. title={
  92. inactiveItems.length > 1
  93. ? t(`+%d Inactive Projects`, inactiveItems.length)
  94. : t(`+1 Inactive Project`)
  95. }
  96. />
  97. )}
  98. {hasActiveItems &&
  99. isExpanded &&
  100. inactiveItems
  101. .toSorted((a, b) => a.project.slug.localeCompare(b.project.slug))
  102. .map(item => (
  103. <TableRow
  104. key={item.project.id}
  105. canEdit={canEdit}
  106. onChange={onChange}
  107. hasAccess={hasAccess}
  108. {...item}
  109. />
  110. ))}
  111. </StyledPanelTable>
  112. );
  113. }
  114. interface SubProject {
  115. count: number;
  116. slug: string;
  117. }
  118. function SectionHeader({
  119. isExpanded,
  120. setIsExpanded,
  121. title,
  122. }: {
  123. isExpanded: boolean;
  124. setIsExpanded: React.Dispatch<React.SetStateAction<boolean>>;
  125. title: React.ReactNode;
  126. }) {
  127. return (
  128. <Fragment>
  129. <SectionHeaderCell
  130. role="button"
  131. tabIndex={0}
  132. onClick={() => setIsExpanded(value => !value)}
  133. aria-label={
  134. isExpanded ? t('Collapse inactive projects') : t('Expand inactive projects')
  135. }
  136. onKeyDown={e => {
  137. if (e.key === 'Enter' || e.key === ' ') {
  138. setIsExpanded(value => !value);
  139. }
  140. }}
  141. >
  142. <StyledIconChevron direction={isExpanded ? 'down' : 'right'} />
  143. {title}
  144. </SectionHeaderCell>
  145. {/* As the main element spans COLUMN_COUNT grid colums we need to ensure that nth child css selectors of other elements
  146. remain functional by adding hidden elements */}
  147. {Array.from({length: COLUMN_COUNT - 1}).map((_, i) => (
  148. <div key={i} style={{display: 'none'}} />
  149. ))}
  150. </Fragment>
  151. );
  152. }
  153. function getSubProjectContent(
  154. ownSlug: string,
  155. subProjects: SubProject[],
  156. isExpanded: boolean
  157. ) {
  158. let subProjectContent: React.ReactNode = t('No distributed traces');
  159. if (subProjects.length > 0) {
  160. const truncatedSubProjects = subProjects.slice(0, MAX_PROJECTS_COLLAPSED);
  161. const overflowCount = subProjects.length - MAX_PROJECTS_COLLAPSED;
  162. const moreTranslation = t('+%d more', overflowCount);
  163. const stringifiedSubProjects =
  164. overflowCount > 0
  165. ? `${truncatedSubProjects.map(p => p.slug).join(', ')}, ${moreTranslation}`
  166. : oxfordizeArray(truncatedSubProjects.map(p => p.slug));
  167. subProjectContent = isExpanded ? (
  168. <Fragment>
  169. <div>{ownSlug}</div>
  170. {subProjects.map(subProject => (
  171. <div key={subProject.slug}>{subProject.slug}</div>
  172. ))}
  173. </Fragment>
  174. ) : (
  175. t('Including spans in ') + stringifiedSubProjects
  176. );
  177. }
  178. return subProjectContent;
  179. }
  180. function getSubSpansContent(
  181. ownCount: number,
  182. subProjects: SubProject[],
  183. isExpanded: boolean
  184. ) {
  185. let subSpansContent: React.ReactNode = '';
  186. if (subProjects.length > 0) {
  187. const subProjectSum = subProjects.reduce(
  188. (acc, subProject) => acc + subProject.count,
  189. 0
  190. );
  191. subSpansContent = isExpanded ? (
  192. <Fragment>
  193. <div>{formatAbbreviatedNumber(ownCount, 2)}</div>
  194. {subProjects.map(subProject => (
  195. <div key={subProject.slug}>{formatAbbreviatedNumber(subProject.count)}</div>
  196. ))}
  197. </Fragment>
  198. ) : (
  199. formatAbbreviatedNumber(subProjectSum)
  200. );
  201. }
  202. return subSpansContent;
  203. }
  204. function getStoredSpansContent(
  205. ownCount: number,
  206. subProjects: SubProject[],
  207. sampleRate: number,
  208. isExpanded: boolean
  209. ) {
  210. let subSpansContent: React.ReactNode = '';
  211. if (subProjects.length > 0) {
  212. const subProjectSum = subProjects.reduce(
  213. (acc, subProject) => acc + Math.floor(subProject.count * sampleRate),
  214. 0
  215. );
  216. subSpansContent = isExpanded ? (
  217. <Fragment>
  218. <div>{formatAbbreviatedNumber(Math.floor(ownCount * sampleRate), 2)}</div>
  219. {subProjects.map(subProject => (
  220. <div key={subProject.slug}>
  221. {formatAbbreviatedNumber(Math.floor(subProject.count * sampleRate))}
  222. </div>
  223. ))}
  224. </Fragment>
  225. ) : (
  226. formatAbbreviatedNumber(subProjectSum)
  227. );
  228. }
  229. return subSpansContent;
  230. }
  231. const MAX_PROJECTS_COLLAPSED = 3;
  232. const TableRow = memo(function TableRow({
  233. project,
  234. hasAccess,
  235. canEdit,
  236. count,
  237. ownCount,
  238. sampleRate,
  239. initialSampleRate,
  240. subProjects,
  241. error,
  242. inputTooltip: inputTooltipProp,
  243. onChange,
  244. }: {
  245. count: number;
  246. hasAccess: boolean;
  247. initialSampleRate: string;
  248. ownCount: number;
  249. project: Project;
  250. sampleRate: string;
  251. subProjects: SubProject[];
  252. canEdit?: boolean;
  253. error?: string;
  254. inputTooltip?: string;
  255. onChange?: (projectId: string, value: string) => void;
  256. }) {
  257. const organization = useOrganization();
  258. const [isExpanded, setIsExpanded] = useState(false);
  259. const isExpandable = subProjects.length > 0;
  260. const hasProjectAccess = hasEveryAccess(['project:write'], {organization, project});
  261. const subProjectContent = getSubProjectContent(project.slug, subProjects, isExpanded);
  262. const subSpansContent = getSubSpansContent(ownCount, subProjects, isExpanded);
  263. let inputTooltip = inputTooltipProp;
  264. if (!hasAccess) {
  265. inputTooltip = t('You do not have permission to change the sample rate.');
  266. }
  267. const handleChange = useCallback(
  268. (event: React.ChangeEvent<HTMLInputElement>) => {
  269. onChange?.(project.id, event.target.value);
  270. },
  271. [onChange, project.id]
  272. );
  273. const storedSpans = Math.floor(count * parsePercent(sampleRate));
  274. return (
  275. <Fragment key={project.slug}>
  276. <Cell>
  277. <FirstCellLine data-has-chevron={isExpandable}>
  278. <HiddenButton
  279. type="button"
  280. disabled={!isExpandable}
  281. aria-label={isExpanded ? t('Collapse') : t('Expand')}
  282. onClick={() => setIsExpanded(value => !value)}
  283. >
  284. {isExpandable && (
  285. <StyledIconChevron direction={isExpanded ? 'down' : 'right'} />
  286. )}
  287. <ProjectBadge project={project} disableLink avatarSize={16} />
  288. </HiddenButton>
  289. {hasProjectAccess && (
  290. <SettingsButton
  291. tabIndex={-1}
  292. title={t('Open Project Settings')}
  293. aria-label={t('Open Project Settings')}
  294. size="xs"
  295. priority="link"
  296. icon={<IconSettings />}
  297. to={`/organizations/${organization.slug}/settings/projects/${project.slug}/performance`}
  298. />
  299. )}
  300. </FirstCellLine>
  301. <SubProjects data-is-first-column>{subProjectContent}</SubProjects>
  302. </Cell>
  303. <Cell>
  304. <FirstCellLine data-align="right">{formatAbbreviatedNumber(count)}</FirstCellLine>
  305. <SubContent>{subSpansContent}</SubContent>
  306. </Cell>
  307. <Cell>
  308. <FirstCellLine data-align="right">
  309. {formatAbbreviatedNumber(storedSpans)}
  310. </FirstCellLine>
  311. <SubContent data-is-last-column>
  312. {getStoredSpansContent(
  313. ownCount,
  314. subProjects,
  315. parsePercent(sampleRate),
  316. isExpanded
  317. )}
  318. </SubContent>
  319. </Cell>
  320. <Cell>
  321. <FirstCellLine>
  322. <Tooltip disabled={!inputTooltip} title={inputTooltip}>
  323. <PercentInput
  324. type="number"
  325. disabled={!canEdit || !hasAccess}
  326. onChange={handleChange}
  327. size="sm"
  328. value={sampleRate}
  329. />
  330. </Tooltip>
  331. </FirstCellLine>
  332. {error ? (
  333. <ErrorMessage>{error}</ErrorMessage>
  334. ) : sampleRate !== initialSampleRate ? (
  335. <SmallPrint>{t('previous: %s%%', initialSampleRate)}</SmallPrint>
  336. ) : null}
  337. </Cell>
  338. </Fragment>
  339. );
  340. });
  341. const StyledPanelTable = styled(PanelTable)`
  342. grid-template-columns: 1fr repeat(${COLUMN_COUNT - 1}, max-content);
  343. `;
  344. const SmallPrint = styled('span')`
  345. font-size: ${p => p.theme.fontSizeExtraSmall};
  346. color: ${p => p.theme.subText};
  347. line-height: 1.5;
  348. text-align: right;
  349. `;
  350. const ErrorMessage = styled('span')`
  351. color: ${p => p.theme.error};
  352. font-size: ${p => p.theme.fontSizeExtraSmall};
  353. line-height: 1.5;
  354. text-align: right;
  355. `;
  356. const SortableHeader = styled('button')`
  357. border: none;
  358. background: none;
  359. cursor: pointer;
  360. display: flex;
  361. text-transform: inherit;
  362. align-items: center;
  363. gap: ${space(0.5)};
  364. `;
  365. const Cell = styled('div')`
  366. display: flex;
  367. flex-direction: column;
  368. gap: ${space(0.25)};
  369. `;
  370. const SectionHeaderCell = styled('div')`
  371. display: flex;
  372. grid-column: span ${COLUMN_COUNT};
  373. padding: ${space(1.5)};
  374. align-items: center;
  375. background: ${p => p.theme.backgroundSecondary};
  376. color: ${p => p.theme.subText};
  377. cursor: pointer;
  378. `;
  379. const FirstCellLine = styled('div')`
  380. display: flex;
  381. align-items: center;
  382. height: 32px;
  383. & > * {
  384. flex-shrink: 0;
  385. }
  386. &[data-align='right'] {
  387. justify-content: flex-end;
  388. }
  389. &[data-has-chevron='false'] {
  390. padding-left: ${space(2)};
  391. }
  392. `;
  393. const SubContent = styled('div')`
  394. color: ${p => p.theme.subText};
  395. font-size: ${p => p.theme.fontSizeSmall};
  396. text-align: right;
  397. & > div {
  398. line-height: 2;
  399. margin-left: -${space(2)};
  400. padding-left: ${space(2)};
  401. margin-right: -${space(2)};
  402. padding-right: ${space(2)};
  403. &:nth-child(odd) {
  404. background: ${p => p.theme.backgroundSecondary};
  405. }
  406. }
  407. &[data-is-first-column] > div {
  408. margin-left: -${space(1)};
  409. padding-left: ${space(1)};
  410. border-top-left-radius: ${p => p.theme.borderRadius};
  411. border-bottom-left-radius: ${p => p.theme.borderRadius};
  412. }
  413. &[data-is-last-column] > div {
  414. margin-right: -${space(1)};
  415. padding-right: ${space(1)};
  416. border-top-right-radius: ${p => p.theme.borderRadius};
  417. border-bottom-right-radius: ${p => p.theme.borderRadius};
  418. }
  419. `;
  420. const SubProjects = styled(SubContent)`
  421. text-align: left;
  422. margin-left: ${space(2)};
  423. `;
  424. const HiddenButton = styled('button')`
  425. background: none;
  426. border: none;
  427. padding: 0;
  428. cursor: pointer;
  429. display: flex;
  430. align-items: center;
  431. /* Overwrite the platform icon's cursor style */
  432. &:not([disabled]) img {
  433. cursor: pointer;
  434. }
  435. `;
  436. const StyledIconChevron = styled(IconChevron)`
  437. height: 12px;
  438. width: 12px;
  439. margin-right: ${space(0.5)};
  440. color: ${p => p.theme.subText};
  441. `;
  442. const SettingsButton = styled(LinkButton)`
  443. margin-left: ${space(0.5)};
  444. color: ${p => p.theme.subText};
  445. visibility: hidden;
  446. &:focus {
  447. visibility: visible;
  448. }
  449. ${Cell}:hover & {
  450. visibility: visible;
  451. }
  452. `;