sampleImages.tsx 8.6 KB

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