projectsTable.tsx 12 KB

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