setupDocsLoader.tsx 9.2 KB

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