setupDocsLoader.tsx 11 KB

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