setupDocsLoader.tsx 8.7 KB

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