sampleImages.tsx 8.0 KB

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