metricListItemDetails.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import {
  2. Fragment,
  3. startTransition,
  4. type SyntheticEvent,
  5. useEffect,
  6. useMemo,
  7. useState,
  8. } from 'react';
  9. import styled from '@emotion/styled';
  10. import {navigateTo} from 'sentry/actionCreators/navigation';
  11. import {Button, LinkButton} from 'sentry/components/button';
  12. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  13. import LoadingIndicator from 'sentry/components/loadingIndicator';
  14. import {IconInfo, IconSettings, IconWarning} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {MetricMeta, MRI} from 'sentry/types/metrics';
  18. import type {Project} from 'sentry/types/project';
  19. import {getReadableMetricType} from 'sentry/utils/metrics/formatters';
  20. import {formatMRI, parseMRI} from 'sentry/utils/metrics/mri';
  21. import {
  22. getMetricsTagsQueryKey,
  23. useMetricsTags,
  24. } from 'sentry/utils/metrics/useMetricsTags';
  25. import {useQueryClient} from 'sentry/utils/queryClient';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import useRouter from 'sentry/utils/useRouter';
  28. const MAX_PROJECTS_TO_SHOW = 3;
  29. const MAX_TAGS_TO_SHOW = 5;
  30. const STANDARD_TAGS = ['release', 'environment', 'transaction', 'project'];
  31. function stopPropagationAndPreventDefault(e: SyntheticEvent) {
  32. e.stopPropagation();
  33. e.preventDefault();
  34. }
  35. export function MetricListItemDetails({
  36. metric,
  37. selectedProjects,
  38. onTagClick,
  39. isDuplicateWithDifferentUnit,
  40. }: {
  41. isDuplicateWithDifferentUnit: boolean;
  42. metric: MetricMeta;
  43. onTagClick: (mri: MRI, tag: string) => void;
  44. selectedProjects: Project[];
  45. }) {
  46. const router = useRouter();
  47. const organization = useOrganization();
  48. const queryClient = useQueryClient();
  49. const isCustomMetric = parseMRI(metric.mri)?.useCase === 'custom';
  50. const [showAllTags, setShowAllTags] = useState(false);
  51. const [showAllProjects, setShowAllProjects] = useState(false);
  52. const projectIds = useMemo(
  53. () => selectedProjects.map(project => parseInt(project.id, 10)),
  54. [selectedProjects]
  55. );
  56. const [isQueryEnabled, setIsQueryEnabled] = useState(() => {
  57. // We only wnat to disable the query if there is no data in the cache
  58. const queryKey = getMetricsTagsQueryKey(organization, metric.mri, {
  59. projects: projectIds,
  60. });
  61. const data = queryClient.getQueryData(queryKey);
  62. return !!data;
  63. });
  64. const {data: tagsData = [], isLoading: tagsIsLoading} = useMetricsTags(
  65. // TODO: improve useMetricsTag interface
  66. isQueryEnabled ? metric.mri : undefined,
  67. {
  68. projects: projectIds,
  69. }
  70. );
  71. useEffect(() => {
  72. // Start querying tags after a short delay to avoid querying
  73. // for every metric if a user quickly hovers over them
  74. const timeout = setTimeout(() => {
  75. startTransition(() => setIsQueryEnabled(true));
  76. }, 200);
  77. return () => clearTimeout(timeout);
  78. }, []);
  79. const metricProjects = selectedProjects.filter(project =>
  80. metric.projectIds.includes(parseInt(project.id, 10))
  81. );
  82. const truncatedProjects = showAllProjects
  83. ? metricProjects
  84. : metricProjects.slice(0, MAX_PROJECTS_TO_SHOW);
  85. // Display custom tags first, then sort alphabetically
  86. const sortedTags = useMemo(
  87. () =>
  88. tagsData.toSorted((a, b) => {
  89. const aIsStandard = STANDARD_TAGS.includes(a.key);
  90. const bIsStandard = STANDARD_TAGS.includes(b.key);
  91. if (aIsStandard && !bIsStandard) {
  92. return 1;
  93. }
  94. if (!aIsStandard && bIsStandard) {
  95. return -1;
  96. }
  97. return a.key.localeCompare(b.key);
  98. }),
  99. [tagsData]
  100. );
  101. const truncatedTags = showAllTags ? sortedTags : sortedTags.slice(0, MAX_TAGS_TO_SHOW);
  102. const firstMetricProject = metricProjects[0];
  103. return (
  104. <DetailsWrapper
  105. // Stop propagation and default behaviour to keep the focus in the combobox
  106. onMouseDown={stopPropagationAndPreventDefault}
  107. >
  108. <Header>
  109. <MetricName>
  110. {/* Add zero width spaces at delimiter characters for nice word breaks */}
  111. {formatMRI(metric.mri).replaceAll(/([\.\/-_])/g, '\u200b$1')}
  112. {isDuplicateWithDifferentUnit && (
  113. <Disclaimer textColor="yellow400">
  114. <IconWrapper>
  115. <IconWarning color="yellow400" size="xs" />
  116. </IconWrapper>
  117. {t(
  118. 'Metrics with the same name and different units were detected. Unwanted metrics can be disabled in settings.'
  119. )}
  120. </Disclaimer>
  121. )}
  122. {!isCustomMetric && (
  123. <Disclaimer>
  124. <IconWrapper>
  125. <IconInfo size="xs" />
  126. </IconWrapper>
  127. {t('Prone to client-side sampling')}
  128. </Disclaimer>
  129. )}
  130. </MetricName>
  131. {isCustomMetric &&
  132. (firstMetricProject ? (
  133. <LinkButton
  134. size="xs"
  135. to={`/settings/projects/${firstMetricProject.slug}/metrics/${encodeURIComponent(metric.mri)}`}
  136. aria-label={t('Open metric settings')}
  137. icon={<IconSettings />}
  138. borderless
  139. />
  140. ) : (
  141. // TODO: figure out when we can end up in this case
  142. <Button
  143. size="xs"
  144. onClick={() =>
  145. navigateTo(
  146. `/settings/projects/:projectId/metrics/${encodeURIComponent(metric.mri)}`,
  147. router
  148. )
  149. }
  150. aria-label={t('Open metric settings')}
  151. icon={<IconSettings />}
  152. borderless
  153. />
  154. ))}
  155. </Header>
  156. <DetailsGrid>
  157. <DetailsLabel>{t('Project')}</DetailsLabel>
  158. <DetailsValue>
  159. {truncatedProjects.map(project => (
  160. <ProjectBadge project={project} key={project.slug} avatarSize={12} />
  161. ))}
  162. {metricProjects.length > MAX_PROJECTS_TO_SHOW && !showAllProjects && (
  163. <Button priority="link" onClick={() => setShowAllProjects(true)}>
  164. {t('+%d more', metricProjects.length - MAX_PROJECTS_TO_SHOW)}
  165. </Button>
  166. )}
  167. </DetailsValue>
  168. <DetailsLabel>{t('Type')}</DetailsLabel>
  169. <DetailsValue>{getReadableMetricType(metric.type)}</DetailsValue>
  170. <DetailsLabel>{t('Unit')}</DetailsLabel>
  171. <DetailsValue>{metric.unit}</DetailsValue>
  172. <DetailsLabel>{t('Tags')}</DetailsLabel>
  173. <DetailsValue>
  174. {tagsIsLoading || !isQueryEnabled ? (
  175. <StyledLoadingIndicator mini size={12} />
  176. ) : truncatedTags.length === 0 ? (
  177. t('(None)')
  178. ) : (
  179. <Fragment>
  180. {truncatedTags.map((tag, index) => {
  181. const shouldAddDelimiter = index < truncatedTags.length - 1;
  182. return (
  183. <Fragment key={tag.key}>
  184. <TagWrapper>
  185. <Button
  186. priority="link"
  187. onClick={() => onTagClick(metric.mri, tag.key)}
  188. >
  189. {tag.key}
  190. </Button>
  191. {/* Make the comma stick to the Button when the text wraps to the next line */}
  192. {shouldAddDelimiter ? ',' : null}
  193. </TagWrapper>
  194. {shouldAddDelimiter ? ' ' : null}
  195. </Fragment>
  196. );
  197. })}
  198. <br />
  199. {tagsData.length > MAX_TAGS_TO_SHOW && !showAllTags && (
  200. <Button priority="link" onClick={() => setShowAllTags(true)}>
  201. {t('+%d more', tagsData.length - MAX_TAGS_TO_SHOW)}
  202. </Button>
  203. )}
  204. </Fragment>
  205. )}
  206. </DetailsValue>
  207. </DetailsGrid>
  208. </DetailsWrapper>
  209. );
  210. }
  211. const DetailsWrapper = styled('div')`
  212. width: 300px;
  213. line-height: 1.4;
  214. `;
  215. const Header = styled('div')`
  216. display: grid;
  217. grid-template-columns: 1fr max-content;
  218. align-items: center;
  219. gap: ${space(0.5)};
  220. padding: ${space(0.75)} ${space(0.25)} ${space(0.75)} ${space(1.5)};
  221. `;
  222. const MetricName = styled('div')`
  223. word-break: break-word;
  224. `;
  225. const DetailsGrid = styled('div')`
  226. display: grid;
  227. grid-template-columns: max-content 1fr;
  228. & > div:nth-child(4n + 1),
  229. & > div:nth-child(4n + 2) {
  230. background-color: ${p => p.theme.backgroundSecondary};
  231. }
  232. `;
  233. const StyledLoadingIndicator = styled(LoadingIndicator)`
  234. && {
  235. margin: ${space(0.75)} 0 0;
  236. height: 12px;
  237. width: 12px;
  238. }
  239. `;
  240. const DetailsLabel = styled('div')`
  241. color: ${p => p.theme.subText};
  242. padding: ${space(0.75)} ${space(1)} ${space(0.75)} ${space(1.5)};
  243. border-top-left-radius: ${p => p.theme.borderRadius};
  244. border-bottom-left-radius: ${p => p.theme.borderRadius};
  245. `;
  246. const DetailsValue = styled('div')`
  247. white-space: pre-wrap;
  248. padding: ${space(0.75)} ${space(1.5)} ${space(0.75)} ${space(1)};
  249. border-top-right-radius: ${p => p.theme.borderRadius};
  250. border-bottom-right-radius: ${p => p.theme.borderRadius};
  251. min-width: 0;
  252. `;
  253. const TagWrapper = styled('span')`
  254. white-space: nowrap;
  255. `;
  256. const Disclaimer = styled('div')<{textColor?: string}>`
  257. display: grid;
  258. gap: ${space(0.5)};
  259. grid-template-columns: max-content 1fr;
  260. font-size: ${p => p.theme.fontSizeSmall};
  261. color: ${p => (p.textColor ? p.theme[p.textColor] ?? null : null)};
  262. `;
  263. const IconWrapper = styled('div')`
  264. margin-top: 1px;
  265. `;