setupDocsLoader.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 {
  13. ProductSelection,
  14. ProductSolution,
  15. } from 'sentry/components/onboarding/productSelection';
  16. import {PlatformKey} from 'sentry/data/platformCategories';
  17. import {IconChevron} from 'sentry/icons';
  18. import {t} from 'sentry/locale';
  19. import {Organization, Project, ProjectKey} from 'sentry/types';
  20. import {trackAnalytics} from 'sentry/utils/analytics';
  21. import {handleXhrErrorResponse} from 'sentry/utils/handleXhrErrorResponse';
  22. import {decodeList} from 'sentry/utils/queryString';
  23. import useApi from 'sentry/utils/useApi';
  24. const ProductSelectionAvailabilityHook = HookOrDefault({
  25. hookName: 'component:product-selection-availability',
  26. defaultComponent: ProductSelection,
  27. });
  28. export function SetupDocsLoader({
  29. organization,
  30. location,
  31. project,
  32. platform,
  33. close,
  34. }: {
  35. close: () => void;
  36. location: Location;
  37. organization: Organization;
  38. platform: PlatformKey | null;
  39. project: Project;
  40. }) {
  41. const api = useApi();
  42. const currentPlatform = platform ?? project?.platform ?? 'other';
  43. const [projectKey, setProjectKey] = useState<ProjectKey | null>(null);
  44. const [hasLoadingError, setHasLoadingError] = useState(false);
  45. const [projectKeyUpdateError, setProjectKeyUpdateError] = useState(false);
  46. const productsQuery =
  47. (location.query.product as ProductSolution | ProductSolution[] | undefined) ?? [];
  48. const products = decodeList(productsQuery) as ProductSolution[];
  49. const fetchData = useCallback(async () => {
  50. const keysApiUrl = `/projects/${organization.slug}/${project.slug}/keys/`;
  51. try {
  52. const loadedKeys = await api.requestPromise(keysApiUrl);
  53. if (loadedKeys.length === 0) {
  54. setHasLoadingError(true);
  55. return;
  56. }
  57. setProjectKey(loadedKeys[0]);
  58. setHasLoadingError(false);
  59. } catch (error) {
  60. setHasLoadingError(error);
  61. throw error;
  62. }
  63. }, [api, organization.slug, project.slug]);
  64. // Automatically update the products on the project key when the user changes the product selection
  65. // Note that on initial visit, this will also update the project key with the default products (=all products)
  66. // This DOES NOT take into account any initial products that may already be set on the project key - they will always be overwritten!
  67. const handleUpdateSelectedProducts = useCallback(async () => {
  68. const keyId = projectKey?.id;
  69. if (!keyId) {
  70. return;
  71. }
  72. const newDynamicSdkLoaderOptions: ProjectKey['dynamicSdkLoaderOptions'] = {
  73. hasPerformance: false,
  74. hasReplay: false,
  75. hasDebug: false,
  76. };
  77. products.forEach(product => {
  78. // eslint-disable-next-line default-case
  79. switch (product) {
  80. case ProductSolution.PERFORMANCE_MONITORING:
  81. newDynamicSdkLoaderOptions.hasPerformance = true;
  82. break;
  83. case ProductSolution.SESSION_REPLAY:
  84. newDynamicSdkLoaderOptions.hasReplay = true;
  85. break;
  86. }
  87. });
  88. try {
  89. await api.requestPromise(
  90. `/projects/${organization.slug}/${project.slug}/keys/${keyId}/`,
  91. {
  92. method: 'PUT',
  93. data: {
  94. dynamicSdkLoaderOptions: newDynamicSdkLoaderOptions,
  95. },
  96. }
  97. );
  98. setProjectKeyUpdateError(false);
  99. } catch (error) {
  100. const message = t('Unable to updated dynamic SDK loader configuration');
  101. handleXhrErrorResponse(message, error);
  102. setProjectKeyUpdateError(true);
  103. }
  104. }, [api, organization.slug, project.slug, projectKey?.id, products]);
  105. const track = useCallback(() => {
  106. if (!project?.id) {
  107. return;
  108. }
  109. trackAnalytics('onboarding.setup_loader_docs_rendered', {
  110. organization,
  111. platform: currentPlatform,
  112. project_id: project?.id,
  113. });
  114. }, [organization, currentPlatform, project?.id]);
  115. useEffect(() => {
  116. fetchData();
  117. }, [fetchData, organization.slug, project.slug]);
  118. useEffect(() => {
  119. handleUpdateSelectedProducts();
  120. }, [handleUpdateSelectedProducts, location.query.product]);
  121. useEffect(() => {
  122. track();
  123. }, [track]);
  124. return (
  125. <Fragment>
  126. <ProductSelectionAvailabilityHook
  127. organization={organization}
  128. lazyLoader
  129. skipLazyLoader={close}
  130. platform={currentPlatform}
  131. />
  132. <Divider />
  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. products={products}
  147. />
  148. )
  149. ) : (
  150. <LoadingError
  151. message={t('Failed to load Client Keys for the project.')}
  152. onRetry={fetchData}
  153. />
  154. )}
  155. </Fragment>
  156. );
  157. }
  158. function ProjectKeyInfo({
  159. projectKey,
  160. platform,
  161. organization,
  162. project,
  163. products,
  164. }: {
  165. organization: Organization;
  166. platform: PlatformKey | null;
  167. products: ProductSolution[];
  168. project: Project;
  169. projectKey: ProjectKey;
  170. }) {
  171. const [showOptionalConfig, setShowOptionalConfig] = useState(false);
  172. const loaderLink = projectKey.dsn.cdn;
  173. const currentPlatform = platform ?? project?.platform ?? 'other';
  174. const hasPerformance = products.includes(ProductSolution.PERFORMANCE_MONITORING);
  175. const hasSessionReplay = products.includes(ProductSolution.SESSION_REPLAY);
  176. const configCodeSnippet = beautify.html(
  177. `<script>
  178. Sentry.onLoad(function() {
  179. Sentry.init({${
  180. !(hasPerformance || hasSessionReplay)
  181. ? `
  182. // You can add any additional configuration here`
  183. : ''
  184. }${
  185. hasPerformance
  186. ? `
  187. // Performance Monitoring
  188. tracesSampleRate: 1.0, // Capture 100% of the transactions, reduce in production!`
  189. : ''
  190. }${
  191. hasSessionReplay
  192. ? `
  193. // Session Replay
  194. replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
  195. replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.`
  196. : ''
  197. }
  198. });
  199. });
  200. </script>`,
  201. {indent_size: 2}
  202. );
  203. const verifyCodeSnippet = beautify.html(
  204. `<script>
  205. myUndefinedFunction();
  206. </script>`,
  207. {indent_size: 2}
  208. );
  209. const toggleOptionalConfiguration = useCallback(() => {
  210. const show = !showOptionalConfig;
  211. setShowOptionalConfig(show);
  212. if (show) {
  213. trackAnalytics('onboarding.js_loader_optional_configuration_shown', {
  214. organization,
  215. platform: currentPlatform,
  216. project_id: project.id,
  217. });
  218. }
  219. }, [organization, project.id, currentPlatform, showOptionalConfig]);
  220. return (
  221. <DocsWrapper>
  222. <DocumentationWrapper>
  223. <h2>{t('Install')}</h2>
  224. <p>{t('Add this script tag to the top of the page:')}</p>
  225. <CodeSnippet dark language="html">
  226. {beautify.html(
  227. `<script src="${loaderLink}" crossorigin="anonymous"></script>`,
  228. {indent_size: 2, wrap_attributes: 'force-expand-multiline'}
  229. )}
  230. </CodeSnippet>
  231. <OptionalConfigWrapper>
  232. <ToggleButton
  233. priority="link"
  234. borderless
  235. size="zero"
  236. icon={<IconChevron direction={showOptionalConfig ? 'down' : 'right'} />}
  237. aria-label={t('Toggle optional configuration')}
  238. onClick={toggleOptionalConfiguration}
  239. />
  240. <h2 onClick={toggleOptionalConfiguration}>{t('Configuration (Optional)')}</h2>
  241. </OptionalConfigWrapper>
  242. {showOptionalConfig && (
  243. <div>
  244. <p>
  245. {t(
  246. "Initialise Sentry as early as possible in your application's lifecycle."
  247. )}
  248. </p>
  249. <CodeSnippet dark language="html">
  250. {configCodeSnippet}
  251. </CodeSnippet>
  252. </div>
  253. )}
  254. <h2>{t('Verify')}</h2>
  255. <p>
  256. {t(
  257. "This snippet contains an intentional error and can be used as a test to make sure that everything's working as expected."
  258. )}
  259. </p>
  260. <CodeSnippet dark language="html">
  261. {verifyCodeSnippet}
  262. </CodeSnippet>
  263. <hr />
  264. <h2>{t('Next Steps')}</h2>
  265. <ul>
  266. <li>
  267. <ExternalLink href="https://docs.sentry.io/platforms/javascript/sourcemaps/">
  268. {t('Source Maps')}
  269. </ExternalLink>
  270. {': '}
  271. {t('Learn how to enable readable stack traces in your Sentry errors.')}
  272. </li>
  273. <li>
  274. <ExternalLink href="https://docs.sentry.io/platforms/javascript/configuration/">
  275. {t('SDK Configuration')}
  276. </ExternalLink>
  277. {': '}
  278. {t('Learn how to configure your SDK using our Loader Script')}
  279. </li>
  280. {!products.includes(ProductSolution.PERFORMANCE_MONITORING) && (
  281. <li>
  282. <ExternalLink href="https://docs.sentry.io/platforms/javascript/performance/">
  283. {t('Performance Monitoring')}
  284. </ExternalLink>
  285. {': '}
  286. {t(
  287. 'Track down transactions to connect the dots between 10-second page loads and poor-performing API calls or slow database queries.'
  288. )}
  289. </li>
  290. )}
  291. {!products.includes(ProductSolution.SESSION_REPLAY) && (
  292. <li>
  293. <ExternalLink href="https://docs.sentry.io/platforms/javascript/session-replay/">
  294. {t('Session Replay')}
  295. </ExternalLink>
  296. {': '}
  297. {t(
  298. 'Get to the root cause of an error or latency issue faster by seeing all the technical details related to that issue in one visual replay on your web application.'
  299. )}
  300. </li>
  301. )}
  302. </ul>
  303. </DocumentationWrapper>
  304. </DocsWrapper>
  305. );
  306. }
  307. const DocsWrapper = styled(motion.div)``;
  308. const OptionalConfigWrapper = styled('div')`
  309. display: flex;
  310. cursor: pointer;
  311. `;
  312. const ToggleButton = styled(Button)`
  313. &,
  314. :hover {
  315. color: ${p => p.theme.gray500};
  316. }
  317. `;
  318. const Divider = styled('hr')<{withBottomMargin?: boolean}>`
  319. height: 1px;
  320. width: 100%;
  321. background: ${p => p.theme.border};
  322. border: none;
  323. `;