setupDocsLoader.tsx 8.9 KB

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