sampleImages.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import {useEffect, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {Button} from 'sentry/components/button';
  6. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  7. import Link from 'sentry/components/links/link';
  8. import LoadingIndicator from 'sentry/components/loadingIndicator';
  9. import {IconImage} from 'sentry/icons';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import {safeURL} from 'sentry/utils/url/safeURL';
  13. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  14. import useOrganization from 'sentry/utils/useOrganization';
  15. import usePageFilters from 'sentry/utils/usePageFilters';
  16. import useProjects from 'sentry/utils/useProjects';
  17. import ResourceSize from 'sentry/views/insights/browser/resources/components/resourceSize';
  18. import {useIndexedResourcesQuery} from 'sentry/views/insights/browser/resources/queries/useIndexedResourceQuery';
  19. import {useResourceModuleFilters} from 'sentry/views/insights/browser/resources/utils/useResourceFilters';
  20. import ChartPanel from 'sentry/views/insights/common/components/chartPanel';
  21. import {SpanIndexedField} from 'sentry/views/insights/types';
  22. import {usePerformanceGeneralProjectSettings} from 'sentry/views/performance/utils';
  23. type Props = {groupId: string; projectId?: number};
  24. export const LOCAL_STORAGE_SHOW_LINKS = 'performance-resources-images-showLinks';
  25. const {SPAN_GROUP, RAW_DOMAIN, SPAN_DESCRIPTION, HTTP_RESPONSE_CONTENT_LENGTH, SPAN_OP} =
  26. SpanIndexedField;
  27. const imageWidth = '200px';
  28. const imageHeight = '180px';
  29. function SampleImages({groupId, projectId}: Props) {
  30. const [showLinks, setShowLinks] = useLocalStorageState(LOCAL_STORAGE_SHOW_LINKS, false);
  31. const filters = useResourceModuleFilters();
  32. const [showImages, setShowImages] = useState(showLinks);
  33. const {data: settings, isPending: isSettingsLoading} =
  34. usePerformanceGeneralProjectSettings(projectId);
  35. const isImagesEnabled = settings?.enable_images ?? false;
  36. const {data: imageResources, isPending: isLoadingImages} = useIndexedResourcesQuery({
  37. queryConditions: [
  38. `${SPAN_GROUP}:${groupId}`,
  39. ...(filters[SPAN_OP] ? [`${SPAN_OP}:${filters[SPAN_OP]}`] : []),
  40. ],
  41. sorts: [{field: `measurements.${HTTP_RESPONSE_CONTENT_LENGTH}`, kind: 'desc'}],
  42. limit: 100,
  43. referrer: 'api.performance.resources.sample-images',
  44. });
  45. const uniqueResources = new Set();
  46. const filteredResources = imageResources
  47. .filter(resource => {
  48. const fileName = getFileNameFromDescription(resource[SPAN_DESCRIPTION]!);
  49. if (uniqueResources.has(fileName)) {
  50. return false;
  51. }
  52. uniqueResources.add(fileName);
  53. return true;
  54. })
  55. .splice(0, 5);
  56. const handleClickOnlyShowLinks = () => {
  57. setShowLinks(true);
  58. setShowImages(true);
  59. };
  60. return (
  61. <ChartPanel title={showImages ? t('Largest Images') : undefined}>
  62. <SampleImagesChartPanelBody
  63. onClickShowLinks={handleClickOnlyShowLinks}
  64. images={filteredResources}
  65. isLoadingImages={isLoadingImages}
  66. isSettingsLoading={isSettingsLoading}
  67. isImagesEnabled={isImagesEnabled}
  68. showImages={showImages || isImagesEnabled}
  69. />
  70. </ChartPanel>
  71. );
  72. }
  73. function SampleImagesChartPanelBody(props: {
  74. images: ReturnType<typeof useIndexedResourcesQuery>['data'];
  75. isImagesEnabled: boolean;
  76. isLoadingImages: boolean;
  77. isSettingsLoading: boolean;
  78. showImages: boolean;
  79. onClickShowLinks?: () => void;
  80. }) {
  81. const {
  82. onClickShowLinks,
  83. images,
  84. isLoadingImages,
  85. showImages,
  86. isImagesEnabled,
  87. isSettingsLoading,
  88. } = props;
  89. const hasImages = images.length > 0;
  90. useEffect(() => {
  91. if (showImages && !hasImages && !isLoadingImages) {
  92. Sentry.captureException(new Error('No sample images found'));
  93. }
  94. }, [showImages, hasImages, isLoadingImages]);
  95. if (isSettingsLoading || (showImages && isLoadingImages)) {
  96. return <LoadingIndicator />;
  97. }
  98. if (!showImages) {
  99. return <DisabledImages onClickShowLinks={onClickShowLinks} />;
  100. }
  101. if (showImages && !hasImages) {
  102. return (
  103. <EmptyStateWarning>
  104. <p>{t('No images detected')}</p>
  105. </EmptyStateWarning>
  106. );
  107. }
  108. return (
  109. <ImageWrapper>
  110. {images.map(resource => {
  111. const hasRawDomain = Boolean(resource[RAW_DOMAIN]);
  112. const isRelativeUrl = resource[SPAN_DESCRIPTION]!.startsWith('/');
  113. let src = resource[SPAN_DESCRIPTION]!;
  114. if (isRelativeUrl && hasRawDomain) {
  115. try {
  116. const url = new URL(resource[SPAN_DESCRIPTION]!, resource[RAW_DOMAIN]!);
  117. src = url.href;
  118. } catch {
  119. Sentry.setContext('resource', {
  120. src,
  121. description: resource[SPAN_DESCRIPTION],
  122. rawDomain: resource[RAW_DOMAIN],
  123. });
  124. Sentry.captureException(new Error('Invalid URL'));
  125. }
  126. }
  127. return (
  128. <ImageContainer
  129. src={src}
  130. showImage={isImagesEnabled}
  131. fileName={getFileNameFromDescription(resource[SPAN_DESCRIPTION]!)}
  132. size={resource[`measurements.${HTTP_RESPONSE_CONTENT_LENGTH}`]}
  133. key={resource[SPAN_DESCRIPTION]}
  134. />
  135. );
  136. })}
  137. </ImageWrapper>
  138. );
  139. }
  140. export function DisabledImages(props: {
  141. onClickShowLinks?: () => void;
  142. projectSlug?: string;
  143. }) {
  144. const {onClickShowLinks} = props;
  145. const organization = useOrganization();
  146. const {
  147. selection: {projects: selectedProjects},
  148. } = usePageFilters();
  149. const {projects} = useProjects();
  150. const firstProjectSelected = props.projectSlug
  151. ? {
  152. slug: props.projectSlug,
  153. }
  154. : projects.find(project => project.id === selectedProjects[0]?.toString());
  155. return (
  156. <div>
  157. <ChartPanelTextContainer>
  158. <IconImage />
  159. <h6>{t('Images not shown')}</h6>
  160. {t(
  161. 'You know, you can see the actual images that are on your site if you opt into this feature.'
  162. )}
  163. </ChartPanelTextContainer>
  164. <ButtonContainer>
  165. <Button onClick={onClickShowLinks}>Only show links</Button>
  166. <Link
  167. to={`/settings/${organization.slug}/projects/${firstProjectSelected?.slug}/performance/`}
  168. >
  169. <Button priority="primary" data-test-id="enable-sample-images-button">
  170. {t(' Enable in Settings')}
  171. </Button>
  172. </Link>
  173. </ButtonContainer>
  174. </div>
  175. );
  176. }
  177. function ImageContainer(props: {
  178. fileName: string;
  179. showImage: boolean;
  180. size: number;
  181. src: string;
  182. }) {
  183. const [hasError, setHasError] = useState(false);
  184. const {fileName, size, src, showImage = true} = props;
  185. const isRelativeUrl = src.startsWith('/');
  186. const handleError = () => {
  187. setHasError(true);
  188. Sentry.metrics.increment('performance.resource.image_load', 1, {
  189. tags: {status: 'error'},
  190. });
  191. };
  192. const handleLoad = () => {
  193. Sentry.metrics.increment('performance.resource.image_load', 1, {
  194. tags: {status: 'success'},
  195. });
  196. };
  197. return (
  198. <div style={{width: '100%', wordWrap: 'break-word'}}>
  199. {showImage && !isRelativeUrl && !hasError ? (
  200. <div
  201. style={{
  202. width: imageWidth,
  203. height: imageHeight,
  204. }}
  205. >
  206. <img
  207. data-test-id="sample-image"
  208. onError={handleError}
  209. onLoad={handleLoad}
  210. src={src}
  211. style={{
  212. width: '100%',
  213. height: '100%',
  214. objectFit: 'contain',
  215. objectPosition: 'center',
  216. }}
  217. />
  218. </div>
  219. ) : (
  220. <MissingImage />
  221. )}
  222. {fileName} (<ResourceSize bytes={size} />)
  223. </div>
  224. );
  225. }
  226. export function MissingImage() {
  227. const theme = useTheme();
  228. return (
  229. <div
  230. style={{
  231. background: theme.gray100,
  232. width: imageWidth,
  233. height: imageHeight,
  234. position: 'relative',
  235. }}
  236. >
  237. <IconImage
  238. style={{
  239. position: 'absolute',
  240. top: 0,
  241. right: 0,
  242. bottom: 0,
  243. left: 0,
  244. margin: 'auto',
  245. }}
  246. />
  247. </div>
  248. );
  249. }
  250. const getFileNameFromDescription = (description: string) => {
  251. const url = safeURL(description);
  252. if (!url) {
  253. return description;
  254. }
  255. return url.pathname.split('/').pop() ?? '';
  256. };
  257. const ImageWrapper = styled('div')`
  258. display: grid;
  259. grid-template-columns: repeat(auto-fill, ${imageWidth});
  260. padding-top: ${space(2)};
  261. gap: 30px;
  262. `;
  263. const ButtonContainer = styled('div')`
  264. display: grid;
  265. grid-template-columns: repeat(2, auto);
  266. gap: ${space(1)};
  267. justify-content: center;
  268. align-items: center;
  269. padding-top: ${space(2)};
  270. `;
  271. const ChartPanelTextContainer = styled('div')`
  272. text-align: center;
  273. width: 300px;
  274. margin: auto;
  275. `;
  276. export default SampleImages;