setupDocs.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import {Fragment, useCallback, useEffect, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {motion} from 'framer-motion';
  5. import * as qs from 'query-string';
  6. import {loadDocs} from 'sentry/actionCreators/projects';
  7. import {Alert} from 'sentry/components/alert';
  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 {Footer} from 'sentry/components/onboarding/footer';
  12. import {FooterWithViewSampleErrorButton} from 'sentry/components/onboarding/footerWithViewSampleErrorButton';
  13. import {PRODUCT, ProductSelection} from 'sentry/components/onboarding/productSelection';
  14. import {PlatformKey} from 'sentry/data/platformCategories';
  15. import platforms, {ReactDocVariant} from 'sentry/data/platforms';
  16. import {t, tct} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {Organization, Project} from 'sentry/types';
  19. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  20. import getDynamicText from 'sentry/utils/getDynamicText';
  21. import {platformToIntegrationMap} from 'sentry/utils/integrationUtil';
  22. import useApi from 'sentry/utils/useApi';
  23. import {useExperiment} from 'sentry/utils/useExperiment';
  24. import useOrganization from 'sentry/utils/useOrganization';
  25. import useProjects from 'sentry/utils/useProjects';
  26. import SetupIntroduction from 'sentry/views/onboarding/components/setupIntroduction';
  27. import FirstEventFooter from './components/firstEventFooter';
  28. import ProjectSidebarSection from './components/projectSidebarSection';
  29. import IntegrationSetup from './integrationSetup';
  30. import {StepProps} from './types';
  31. import {usePersistedOnboardingState} from './utils';
  32. /**
  33. * The documentation will include the following string should it be missing the
  34. * verification example, which currently a lot of docs are.
  35. */
  36. const INCOMPLETE_DOC_FLAG = 'TODO-ADD-VERIFICATION-EXAMPLE';
  37. type PlatformDoc = {html: string; link: string};
  38. type Props = {
  39. search: string;
  40. } & StepProps;
  41. function ProjectDocs(props: {
  42. hasError: boolean;
  43. onRetry: () => void;
  44. organization: Organization;
  45. platform: PlatformKey | null;
  46. platformDocs: PlatformDoc | null;
  47. project: Project;
  48. }) {
  49. const testOnlyAlert = (
  50. <Alert type="warning">
  51. Platform documentation is not rendered in for tests in CI
  52. </Alert>
  53. );
  54. const missingExampleWarning = () => {
  55. const missingExample =
  56. props.platformDocs && props.platformDocs.html.includes(INCOMPLETE_DOC_FLAG);
  57. if (!missingExample) {
  58. return null;
  59. }
  60. return (
  61. <Alert type="warning" showIcon>
  62. {tct(
  63. `Looks like this getting started example is still undergoing some
  64. work and doesn't include an example for triggering an event quite
  65. yet. If you have trouble sending your first event be sure to consult
  66. the [docsLink:full documentation] for [platform].`,
  67. {
  68. docsLink: <ExternalLink href={props.platformDocs?.link} />,
  69. platform: platforms.find(p => p.id === props.platform)?.name,
  70. }
  71. )}
  72. </Alert>
  73. );
  74. };
  75. const docs = props.platformDocs !== null && (
  76. <DocsWrapper key={props.platformDocs.html}>
  77. <DocumentationWrapper dangerouslySetInnerHTML={{__html: props.platformDocs.html}} />
  78. {missingExampleWarning()}
  79. </DocsWrapper>
  80. );
  81. const loadingError = (
  82. <LoadingError
  83. message={t(
  84. 'Failed to load documentation for the %s platform.',
  85. props.project?.platform
  86. )}
  87. onRetry={props.onRetry}
  88. />
  89. );
  90. const currentPlatform = props.platform ?? props.project?.platform ?? 'other';
  91. return (
  92. <Fragment>
  93. <SetupIntroduction
  94. stepHeaderText={t(
  95. 'Configure %s SDK',
  96. platforms.find(p => p.id === currentPlatform)?.name ?? ''
  97. )}
  98. platform={currentPlatform}
  99. />
  100. {currentPlatform === 'javascript-react' &&
  101. props.organization.features?.includes(
  102. 'onboarding-docs-with-product-selection'
  103. ) && <ProductSelection />}
  104. {getDynamicText({
  105. value: !props.hasError ? docs : loadingError,
  106. fixed: testOnlyAlert,
  107. })}
  108. </Fragment>
  109. );
  110. }
  111. function SetupDocs({search, route, router, location, ...props}: Props) {
  112. const api = useApi();
  113. const organization = useOrganization();
  114. const {projects: rawProjects} = useProjects();
  115. const [clientState, setClientState] = usePersistedOnboardingState();
  116. const [selectedProjectSlug, _setSelectedProjectSlug] = useState(
  117. props.selectedProjectSlug
  118. );
  119. const {logExperiment, experimentAssignment} = useExperiment(
  120. 'OnboardingNewFooterExperiment',
  121. {
  122. logExperimentOnMount: false,
  123. }
  124. );
  125. const singleSelectPlatform = !!organization?.features.includes(
  126. 'onboarding-remove-multiselect-platform'
  127. );
  128. const heartbeatFooter = !!organization?.features.includes(
  129. 'onboarding-heartbeat-footer'
  130. );
  131. const selectedPlatforms = clientState?.selectedPlatforms || [];
  132. const platformToProjectIdMap = clientState?.platformToProjectIdMap || {};
  133. // id is really slug here
  134. const projectSlugs = selectedPlatforms
  135. .map(platform => platformToProjectIdMap[platform])
  136. .filter((slug): slug is string => slug !== undefined);
  137. const selectedProjectsSet = new Set(projectSlugs);
  138. // get projects in the order they appear in selectedPlatforms
  139. const projects = projectSlugs
  140. .map(slug => rawProjects.find(project => project.slug === slug))
  141. .filter((project): project is Project => project !== undefined);
  142. // SDK instrumentation
  143. const [hasError, setHasError] = useState(false);
  144. const [platformDocs, setPlatformDocs] = useState<PlatformDoc | null>(null);
  145. const [loadedPlatform, setLoadedPlatform] = useState<PlatformKey | null>(null);
  146. // store what projects have sent first event in state based project.firstEvent
  147. const [hasFirstEventMap, setHasFirstEventMap] = useState<Record<string, boolean>>(
  148. projects.reduce((accum, project: Project) => {
  149. accum[project.id] = !!project.firstEvent;
  150. return accum;
  151. }, {} as Record<string, boolean>)
  152. );
  153. const checkProjectHasFirstEvent = (project: Project) => {
  154. return !!hasFirstEventMap[project.id];
  155. };
  156. const {project_id: rawProjectId} = qs.parse(search);
  157. const rawProjectIndex = projects.findIndex(p => p.id === rawProjectId);
  158. const firstProjectNoError = projects.findIndex(p => selectedProjectsSet.has(p.slug));
  159. // Select a project based on search params. If non exist, use the first project without first event.
  160. const projectIndex = rawProjectIndex >= 0 ? rawProjectIndex : firstProjectNoError;
  161. const project =
  162. projects[projectIndex] ?? rawProjects.find(p => p.slug === selectedProjectSlug);
  163. // find the next project that doesn't have a first event
  164. const nextProject = projects.find(
  165. (p, i) => i > projectIndex && !checkProjectHasFirstEvent(p)
  166. );
  167. const integrationSlug = project?.platform && platformToIntegrationMap[project.platform];
  168. const [integrationUseManualSetup, setIntegrationUseManualSetup] = useState(false);
  169. const currentPlatform = loadedPlatform ?? project?.platform ?? 'other';
  170. const fetchData = useCallback(async () => {
  171. // TODO: add better error handling logic
  172. if (!project?.platform) {
  173. return;
  174. }
  175. if (integrationSlug && !integrationUseManualSetup) {
  176. setLoadedPlatform(project.platform);
  177. setPlatformDocs(null);
  178. setHasError(false);
  179. return;
  180. }
  181. let loadPlatform = String(project.platform);
  182. if (
  183. organization.features?.includes('onboarding-docs-with-product-selection') &&
  184. project.platform === 'javascript-react'
  185. ) {
  186. // This is an experiment we are doing with react.
  187. // In this experiment we let the user choose which Sentry product he would like to have in his `Sentry.Init()`
  188. // and the docs will reflect that.
  189. const products = location.query.product ?? [];
  190. if (
  191. products.includes(PRODUCT.PERFORMANCE_MONITORING) &&
  192. products.includes(PRODUCT.SESSION_REPLAY)
  193. ) {
  194. loadPlatform = ReactDocVariant.ErrorMonitoringPerformanceAndReplay;
  195. } else if (products.includes(PRODUCT.PERFORMANCE_MONITORING)) {
  196. loadPlatform = ReactDocVariant.ErrorMonitoringAndPerformance;
  197. } else if (products.includes(PRODUCT.SESSION_REPLAY)) {
  198. loadPlatform = ReactDocVariant.ErrorMonitoringAndSessionReplay;
  199. } else {
  200. loadPlatform = ReactDocVariant.ErrorMonitoring;
  201. }
  202. }
  203. try {
  204. const loadedDocs = await loadDocs({
  205. api,
  206. orgSlug: organization.slug,
  207. projectSlug: project.slug,
  208. platform: loadPlatform as PlatformKey,
  209. });
  210. setPlatformDocs(loadedDocs);
  211. setLoadedPlatform(project.platform);
  212. setHasError(false);
  213. } catch (error) {
  214. setHasError(error);
  215. throw error;
  216. }
  217. }, [
  218. project?.slug,
  219. project?.platform,
  220. api,
  221. organization.slug,
  222. organization.features,
  223. integrationSlug,
  224. integrationUseManualSetup,
  225. location.query.product,
  226. ]);
  227. useEffect(() => {
  228. fetchData();
  229. }, [fetchData, location.query.product, project?.platform]);
  230. // log experiment on mount if feature enabled
  231. useEffect(() => {
  232. if (heartbeatFooter) {
  233. logExperiment();
  234. }
  235. }, [logExperiment, heartbeatFooter]);
  236. if (!project) {
  237. return null;
  238. }
  239. const setNewProject = (newProjectId: string) => {
  240. setLoadedPlatform(null);
  241. setPlatformDocs(null);
  242. setHasError(false);
  243. setIntegrationUseManualSetup(false);
  244. const searchParams = new URLSearchParams({
  245. sub_step: 'project',
  246. project_id: newProjectId,
  247. });
  248. browserHistory.push(`${window.location.pathname}?${searchParams}`);
  249. clientState &&
  250. setClientState({
  251. ...clientState,
  252. state: 'projects_selected',
  253. url: `setup-docs/?${searchParams}`,
  254. });
  255. };
  256. const selectProject = (newProjectId: string) => {
  257. const matchedProject = projects.find(p => p.id === newProjectId);
  258. trackAdvancedAnalyticsEvent('growth.onboarding_clicked_project_in_sidebar', {
  259. organization,
  260. platform: matchedProject?.platform || 'unknown',
  261. });
  262. setNewProject(newProjectId);
  263. };
  264. return (
  265. <Fragment>
  266. <Wrapper>
  267. {!singleSelectPlatform && (
  268. <SidebarWrapper>
  269. <ProjectSidebarSection
  270. projects={projects}
  271. selectedPlatformToProjectIdMap={Object.fromEntries(
  272. selectedPlatforms.map(platform => [
  273. platform,
  274. platformToProjectIdMap[platform],
  275. ])
  276. )}
  277. activeProject={project}
  278. {...{checkProjectHasFirstEvent, selectProject}}
  279. />
  280. </SidebarWrapper>
  281. )}
  282. <MainContent>
  283. {integrationSlug && !integrationUseManualSetup ? (
  284. <IntegrationSetup
  285. integrationSlug={integrationSlug}
  286. project={project}
  287. onClickManualSetup={() => {
  288. setIntegrationUseManualSetup(true);
  289. }}
  290. />
  291. ) : (
  292. <ProjectDocs
  293. platform={loadedPlatform}
  294. project={project}
  295. hasError={hasError}
  296. platformDocs={platformDocs}
  297. onRetry={fetchData}
  298. organization={organization}
  299. />
  300. )}
  301. </MainContent>
  302. </Wrapper>
  303. {heartbeatFooter ? (
  304. experimentAssignment === 'variant2' ? (
  305. <FooterWithViewSampleErrorButton
  306. projectSlug={project.slug}
  307. projectId={project.id}
  308. route={route}
  309. router={router}
  310. location={location}
  311. newOrg
  312. />
  313. ) : experimentAssignment === 'variant1' ? (
  314. <Footer
  315. projectSlug={project.slug}
  316. projectId={project.id}
  317. route={route}
  318. router={router}
  319. location={location}
  320. newOrg
  321. />
  322. ) : (
  323. <FirstEventFooter
  324. project={project}
  325. organization={organization}
  326. isLast={!nextProject}
  327. hasFirstEvent={checkProjectHasFirstEvent(project)}
  328. onClickSetupLater={() => {
  329. const orgIssuesURL = `/organizations/${organization.slug}/issues/?project=${project.id}&referrer=onboarding-setup-docs`;
  330. trackAdvancedAnalyticsEvent(
  331. 'growth.onboarding_clicked_setup_platform_later',
  332. {
  333. organization,
  334. platform: currentPlatform,
  335. project_index: projectIndex,
  336. }
  337. );
  338. if (!project.platform || !clientState) {
  339. browserHistory.push(orgIssuesURL);
  340. return;
  341. }
  342. // if we have a next project, switch to that
  343. if (nextProject) {
  344. setNewProject(nextProject.id);
  345. } else {
  346. setClientState({
  347. ...clientState,
  348. state: 'finished',
  349. });
  350. browserHistory.push(orgIssuesURL);
  351. }
  352. }}
  353. handleFirstIssueReceived={() => {
  354. const newHasFirstEventMap = {...hasFirstEventMap, [project.id]: true};
  355. setHasFirstEventMap(newHasFirstEventMap);
  356. }}
  357. />
  358. )
  359. ) : (
  360. <FirstEventFooter
  361. project={project}
  362. organization={organization}
  363. isLast={!nextProject}
  364. hasFirstEvent={checkProjectHasFirstEvent(project)}
  365. onClickSetupLater={() => {
  366. const orgIssuesURL = `/organizations/${organization.slug}/issues/?project=${project.id}&referrer=onboarding-setup-docs`;
  367. trackAdvancedAnalyticsEvent(
  368. 'growth.onboarding_clicked_setup_platform_later',
  369. {
  370. organization,
  371. platform: currentPlatform,
  372. project_index: projectIndex,
  373. }
  374. );
  375. if (!project.platform || !clientState) {
  376. browserHistory.push(orgIssuesURL);
  377. return;
  378. }
  379. // if we have a next project, switch to that
  380. if (nextProject) {
  381. setNewProject(nextProject.id);
  382. } else {
  383. setClientState({
  384. ...clientState,
  385. state: 'finished',
  386. });
  387. browserHistory.push(orgIssuesURL);
  388. }
  389. }}
  390. handleFirstIssueReceived={() => {
  391. const newHasFirstEventMap = {...hasFirstEventMap, [project.id]: true};
  392. setHasFirstEventMap(newHasFirstEventMap);
  393. }}
  394. />
  395. )}
  396. </Fragment>
  397. );
  398. }
  399. export default SetupDocs;
  400. const AnimatedContentWrapper = styled(motion.div)`
  401. overflow: hidden;
  402. `;
  403. AnimatedContentWrapper.defaultProps = {
  404. initial: {
  405. height: 0,
  406. },
  407. animate: {
  408. height: 'auto',
  409. },
  410. exit: {
  411. height: 0,
  412. },
  413. };
  414. const DocsWrapper = styled(motion.div)``;
  415. DocsWrapper.defaultProps = {
  416. initial: {opacity: 0, y: 40},
  417. animate: {opacity: 1, y: 0},
  418. exit: {opacity: 0},
  419. };
  420. const Wrapper = styled('div')`
  421. display: flex;
  422. flex-direction: row;
  423. margin: ${space(2)};
  424. justify-content: center;
  425. `;
  426. const MainContent = styled('div')`
  427. max-width: 850px;
  428. min-width: 0;
  429. flex-grow: 1;
  430. `;
  431. // the number icon will be space(2) + 30px to the left of the margin of center column
  432. // so we need to offset the right margin by that much
  433. // also hide the sidebar if the screen is too small
  434. const SidebarWrapper = styled('div')`
  435. margin: ${space(1)} calc(${space(2)} + 30px + ${space(4)}) 0 ${space(2)};
  436. @media (max-width: 1150px) {
  437. display: none;
  438. }
  439. flex-basis: 240px;
  440. flex-grow: 0;
  441. flex-shrink: 0;
  442. min-width: 240px;
  443. `;