setupDocsLoader.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import {Fragment, useCallback, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {motion} from 'framer-motion';
  4. import {Location} from 'history';
  5. import beautify from 'js-beautify';
  6. import {Button} from 'sentry/components/button';
  7. import {CodeSnippet} from 'sentry/components/codeSnippet';
  8. import ExternalLink from 'sentry/components/links/externalLink';
  9. import LoadingError from 'sentry/components/loadingError';
  10. import {DocumentationWrapper} from 'sentry/components/onboarding/documentationWrapper';
  11. import {PRODUCT, ProductSelection} from 'sentry/components/onboarding/productSelection';
  12. import {PlatformKey} from 'sentry/data/platformCategories';
  13. import platforms from 'sentry/data/platforms';
  14. import {IconChevron} from 'sentry/icons';
  15. import {t} from 'sentry/locale';
  16. import {Organization, Project, ProjectKey} from 'sentry/types';
  17. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  18. import handleXhrErrorResponse from 'sentry/utils/handleXhrErrorResponse';
  19. import {decodeList} from 'sentry/utils/queryString';
  20. import useApi from 'sentry/utils/useApi';
  21. import SetupIntroduction from 'sentry/views/onboarding/components/setupIntroduction';
  22. import {DynamicSDKLoaderOption} from 'sentry/views/settings/project/projectKeys/details/keySettings';
  23. export function SetupDocsLoader({
  24. organization,
  25. location,
  26. project,
  27. platform,
  28. close,
  29. }: {
  30. close: () => void;
  31. location: Location;
  32. organization: Organization;
  33. platform: PlatformKey | null;
  34. project: Project;
  35. }) {
  36. const api = useApi();
  37. const currentPlatform = platform ?? project?.platform ?? 'other';
  38. const [projectKey, setProjectKey] = useState<ProjectKey | null>(null);
  39. const [hasLoadingError, setHasLoadingError] = useState(false);
  40. const [projectKeyUpdateError, setProjectKeyUpdateError] = useState(false);
  41. const fetchData = useCallback(async () => {
  42. const keysApiUrl = `/projects/${organization.slug}/${project.slug}/keys/`;
  43. try {
  44. const loadedKeys = await api.requestPromise(keysApiUrl);
  45. if (loadedKeys.length === 0) {
  46. setHasLoadingError(true);
  47. return;
  48. }
  49. setProjectKey(loadedKeys[0]);
  50. setHasLoadingError(false);
  51. } catch (error) {
  52. setHasLoadingError(error);
  53. throw error;
  54. }
  55. }, [api, organization.slug, project.slug]);
  56. // Automatically update the products on the project key when the user changes the product selection
  57. // Note that on initial visit, this will also update the project key with the default products (=all products)
  58. // This DOES NOT take into account any initial products that may already be set on the project key - they will always be overwritten!
  59. const handleUpdateSelectedProducts = useCallback(async () => {
  60. const productsQuery =
  61. (location.query.product as PRODUCT | PRODUCT[] | undefined) ?? [];
  62. const products = decodeList(productsQuery);
  63. const keyId = projectKey?.id;
  64. if (!keyId) {
  65. return;
  66. }
  67. const newDynamicSdkLoaderOptions: Record<DynamicSDKLoaderOption, boolean> = {
  68. [DynamicSDKLoaderOption.HAS_PERFORMANCE]: false,
  69. [DynamicSDKLoaderOption.HAS_REPLAY]: false,
  70. [DynamicSDKLoaderOption.HAS_DEBUG]: false,
  71. };
  72. products.forEach(product => {
  73. // eslint-disable-next-line default-case
  74. switch (product) {
  75. case PRODUCT.PERFORMANCE_MONITORING:
  76. newDynamicSdkLoaderOptions[DynamicSDKLoaderOption.HAS_PERFORMANCE] = true;
  77. break;
  78. case PRODUCT.SESSION_REPLAY:
  79. newDynamicSdkLoaderOptions[DynamicSDKLoaderOption.HAS_REPLAY] = true;
  80. break;
  81. }
  82. });
  83. try {
  84. await api.requestPromise(
  85. `/projects/${organization.slug}/${project.slug}/keys/${keyId}/`,
  86. {
  87. method: 'PUT',
  88. data: {
  89. dynamicSdkLoaderOptions: newDynamicSdkLoaderOptions,
  90. },
  91. }
  92. );
  93. setProjectKeyUpdateError(false);
  94. } catch (error) {
  95. const message = t('Unable to updated dynamic SDK loader configuration');
  96. handleXhrErrorResponse(message)(error);
  97. setProjectKeyUpdateError(true);
  98. }
  99. }, [api, location.query.product, organization.slug, project.slug, projectKey?.id]);
  100. const track = useCallback(() => {
  101. if (!project?.id) {
  102. return;
  103. }
  104. trackAdvancedAnalyticsEvent('onboarding.setup_loader_docs_rendered', {
  105. organization,
  106. platform: currentPlatform,
  107. project_id: project?.id,
  108. });
  109. }, [organization, currentPlatform, project?.id]);
  110. useEffect(() => {
  111. fetchData();
  112. }, [fetchData, organization.slug, project.slug]);
  113. useEffect(() => {
  114. handleUpdateSelectedProducts();
  115. }, [handleUpdateSelectedProducts, location.query.product]);
  116. useEffect(() => {
  117. track();
  118. }, [track]);
  119. return (
  120. <Fragment>
  121. <SetupIntroduction
  122. stepHeaderText={t(
  123. 'Configure %s SDK',
  124. platforms.find(p => p.id === currentPlatform)?.name ?? ''
  125. )}
  126. platform={currentPlatform}
  127. />
  128. <ProductSelection
  129. defaultSelectedProducts={[PRODUCT.PERFORMANCE_MONITORING, PRODUCT.SESSION_REPLAY]}
  130. lazyLoader
  131. skipLazyLoader={close}
  132. />
  133. {projectKeyUpdateError && (
  134. <LoadingError
  135. message={t('Failed to update the project key with the selected products.')}
  136. onRetry={handleUpdateSelectedProducts}
  137. />
  138. )}
  139. {!hasLoadingError ? (
  140. projectKey !== null && (
  141. <ProjectKeyInfo
  142. projectKey={projectKey}
  143. platform={platform}
  144. organization={organization}
  145. project={project}
  146. />
  147. )
  148. ) : (
  149. <LoadingError
  150. message={t('Failed to load Client Keys for the project.')}
  151. onRetry={fetchData}
  152. />
  153. )}
  154. </Fragment>
  155. );
  156. }
  157. function ProjectKeyInfo({
  158. projectKey,
  159. platform,
  160. organization,
  161. project,
  162. }: {
  163. organization: Organization;
  164. platform: PlatformKey | null;
  165. project: Project;
  166. projectKey: ProjectKey;
  167. }) {
  168. const [showOptionalConfig, setShowOptionalConfig] = useState(false);
  169. const loaderLink = projectKey.dsn.cdn;
  170. const currentPlatform = platform ?? project?.platform ?? 'other';
  171. const configCodeSnippet = beautify.html(
  172. `<script>
  173. Sentry.onLoad(function() {
  174. Sentry.init({
  175. // No need to configure DSN here, it is already configured in the loader script
  176. // You can add any additional configuration here
  177. sampleRate: 0.5,
  178. });
  179. });
  180. </script>`,
  181. {indent_size: 2}
  182. );
  183. const verifyCodeSnippet = beautify.html(
  184. `<script>
  185. myUndefinedFunction();
  186. </script>`,
  187. {indent_size: 2}
  188. );
  189. const toggleOptionalConfiguration = useCallback(() => {
  190. const show = !showOptionalConfig;
  191. setShowOptionalConfig(show);
  192. if (show) {
  193. trackAdvancedAnalyticsEvent('onboarding.js_loader_optional_configuration_shown', {
  194. organization,
  195. platform: currentPlatform,
  196. project_id: project.id,
  197. });
  198. }
  199. }, [organization, project.id, currentPlatform, showOptionalConfig]);
  200. return (
  201. <DocsWrapper>
  202. <DocumentationWrapper>
  203. <h2>{t('Install')}</h2>
  204. <p>{t('Add this script tag to the top of the page:')}</p>
  205. <CodeSnippet dark language="html">
  206. {beautify.html(
  207. `<script src="${loaderLink}" crossorigin="anonymous"></script>`,
  208. {indent_size: 2, wrap_attributes: 'force-expand-multiline'}
  209. )}
  210. </CodeSnippet>
  211. <OptionalConfigWrapper>
  212. <ToggleButton
  213. priority="link"
  214. borderless
  215. size="zero"
  216. icon={<IconChevron direction={showOptionalConfig ? 'down' : 'right'} />}
  217. aria-label={t('Toggle optional configuration')}
  218. onClick={toggleOptionalConfiguration}
  219. />
  220. <h2 onClick={toggleOptionalConfiguration}>{t('Configuration (Optional)')}</h2>
  221. </OptionalConfigWrapper>
  222. {showOptionalConfig && (
  223. <div>
  224. <p>
  225. {t(
  226. "Initialise Sentry as early as possible in your application's lifecycle."
  227. )}
  228. </p>
  229. <CodeSnippet dark language="html">
  230. {configCodeSnippet}
  231. </CodeSnippet>
  232. </div>
  233. )}
  234. <h2>{t('Verify')}</h2>
  235. <p>
  236. {t(
  237. "This snippet contains an intentional error and can be used as a test to make sure that everything's working as expected."
  238. )}
  239. </p>
  240. <CodeSnippet dark language="html">
  241. {verifyCodeSnippet}
  242. </CodeSnippet>
  243. <hr />
  244. <h2>{t('Next Steps')}</h2>
  245. <ul>
  246. <li>
  247. <ExternalLink href="https://docs.sentry.io/platforms/javascript/sourcemaps/">
  248. {t('Source Maps')}
  249. </ExternalLink>
  250. {': '}
  251. {t('Learn how to enable readable stack traces in your Sentry errors.')}
  252. </li>
  253. <li>
  254. <ExternalLink href="https://docs.sentry.io/platforms/javascript/configuration/">
  255. {t('SDK Configuration')}
  256. </ExternalLink>
  257. {': '}
  258. {t('Learn how to configure your SDK using our Loader Script')}
  259. </li>
  260. </ul>
  261. </DocumentationWrapper>
  262. </DocsWrapper>
  263. );
  264. }
  265. const DocsWrapper = styled(motion.div)``;
  266. const OptionalConfigWrapper = styled('div')`
  267. display: flex;
  268. cursor: pointer;
  269. `;
  270. const ToggleButton = styled(Button)`
  271. &,
  272. :hover {
  273. color: ${p => p.theme.gray500};
  274. }
  275. `;