sampleImages.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 usePageFilters from 'sentry/utils/usePageFilters';
  15. import useProjects from 'sentry/utils/useProjects';
  16. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  17. import ResourceSize from 'sentry/views/performance/browser/resources/shared/resourceSize';
  18. import {useIndexedResourcesQuery} from 'sentry/views/performance/browser/resources/utils/useIndexedResourceQuery';
  19. import {useResourceModuleFilters} from 'sentry/views/performance/browser/resources/utils/useResourceFilters';
  20. import {usePerformanceGeneralProjectSettings} from 'sentry/views/performance/utils';
  21. import ChartPanel from 'sentry/views/starfish/components/chartPanel';
  22. import {SpanIndexedField} from 'sentry/views/starfish/types';
  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, isLoading: isSettingsLoading} =
  34. usePerformanceGeneralProjectSettings(projectId);
  35. const isImagesEnabled = settings?.enable_images ?? false;
  36. const {data: imageResources, isLoading: 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. function DisabledImages(props: {onClickShowLinks?: () => void}) {
  141. const {onClickShowLinks} = props;
  142. const {
  143. selection: {projects: selectedProjects},
  144. } = usePageFilters();
  145. const {projects} = useProjects();
  146. const firstProjectSelected = projects.find(
  147. project => project.id === selectedProjects[0].toString()
  148. );
  149. return (
  150. <div>
  151. <ChartPanelTextContainer>
  152. <IconImage />
  153. <h6>{t('Images not shown')}</h6>
  154. {t(
  155. 'You know, you can see the actual images that are on your site if you opt into this feature.'
  156. )}
  157. </ChartPanelTextContainer>
  158. <ButtonContainer>
  159. <Button onClick={onClickShowLinks}>Only show links</Button>
  160. <Link
  161. to={normalizeUrl(
  162. `/settings/projects/${firstProjectSelected?.slug}/performance/`
  163. )}
  164. >
  165. <Button priority="primary" data-test-id="enable-sample-images-button">
  166. {t(' Enable in Settings')}
  167. </Button>
  168. </Link>
  169. </ButtonContainer>
  170. </div>
  171. );
  172. }
  173. function ImageContainer(props: {
  174. fileName: string;
  175. showImage: boolean;
  176. size: number;
  177. src: string;
  178. }) {
  179. const [hasError, setHasError] = useState(false);
  180. const {fileName, size, src, showImage = true} = props;
  181. const isRelativeUrl = src.startsWith('/');
  182. const handleError = () => {
  183. setHasError(true);
  184. Sentry.metrics.increment('performance.resource.image_load', 1, {
  185. tags: {status: 'error'},
  186. });
  187. };
  188. const handleLoad = () => {
  189. Sentry.metrics.increment('performance.resource.image_load', 1, {
  190. tags: {status: 'success'},
  191. });
  192. };
  193. return (
  194. <div style={{width: '100%', wordWrap: 'break-word'}}>
  195. {showImage && !isRelativeUrl && !hasError ? (
  196. <div
  197. style={{
  198. width: imageWidth,
  199. height: imageHeight,
  200. }}
  201. >
  202. <img
  203. data-test-id="sample-image"
  204. onError={handleError}
  205. onLoad={handleLoad}
  206. src={src}
  207. style={{
  208. width: '100%',
  209. height: '100%',
  210. objectFit: 'contain',
  211. objectPosition: 'center',
  212. }}
  213. />
  214. </div>
  215. ) : (
  216. <MissingImage />
  217. )}
  218. {fileName} (<ResourceSize bytes={size} />)
  219. </div>
  220. );
  221. }
  222. function MissingImage() {
  223. const theme = useTheme();
  224. return (
  225. <div
  226. style={{
  227. background: theme.gray100,
  228. width: imageWidth,
  229. height: imageHeight,
  230. position: 'relative',
  231. }}
  232. >
  233. <IconImage
  234. style={{
  235. position: 'absolute',
  236. top: 0,
  237. right: 0,
  238. bottom: 0,
  239. left: 0,
  240. margin: 'auto',
  241. }}
  242. />
  243. </div>
  244. );
  245. }
  246. const getFileNameFromDescription = (description: string) => {
  247. const url = safeURL(description);
  248. if (!url) {
  249. return description;
  250. }
  251. return url.pathname.split('/').pop() ?? '';
  252. };
  253. const ImageWrapper = styled('div')`
  254. display: grid;
  255. grid-template-columns: repeat(auto-fill, ${imageWidth});
  256. padding-top: ${space(2)};
  257. gap: 30px;
  258. `;
  259. const ButtonContainer = styled('div')`
  260. display: grid;
  261. grid-template-columns: repeat(2, auto);
  262. gap: ${space(1)};
  263. justify-content: center;
  264. align-items: center;
  265. padding-top: ${space(2)};
  266. `;
  267. const ChartPanelTextContainer = styled('div')`
  268. text-align: center;
  269. width: 300px;
  270. margin: auto;
  271. `;
  272. export default SampleImages;