onboarding.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import {useCallback, useContext, useEffect, useRef, useState} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {AnimatePresence, motion, MotionProps, useAnimation} from 'framer-motion';
  6. import {removeProject} from 'sentry/actionCreators/projects';
  7. import {Button, ButtonProps} from 'sentry/components/button';
  8. import Hook from 'sentry/components/hook';
  9. import Link from 'sentry/components/links/link';
  10. import LogoSentry from 'sentry/components/logoSentry';
  11. import {OnboardingContext} from 'sentry/components/onboarding/onboardingContext';
  12. import {PRODUCT} from 'sentry/components/onboarding/productSelection';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {PlatformKey} from 'sentry/data/platformCategories';
  15. import {IconArrow} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {OnboardingStatus} from 'sentry/types';
  19. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  20. import handleXhrErrorResponse from 'sentry/utils/handleXhrErrorResponse';
  21. import Redirect from 'sentry/utils/redirect';
  22. import testableTransition from 'sentry/utils/testableTransition';
  23. import useApi from 'sentry/utils/useApi';
  24. import {useExperiment} from 'sentry/utils/useExperiment';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  27. import PageCorners from 'sentry/views/onboarding/components/pageCorners';
  28. import Stepper from './components/stepper';
  29. import OnboardingPlatform from './deprecatedPlatform';
  30. import {PlatformSelection} from './platformSelection';
  31. import SetupDocs from './setupDocs';
  32. import {StepDescriptor} from './types';
  33. import {usePersistedOnboardingState} from './utils';
  34. import TargetedOnboardingWelcome from './welcome';
  35. type RouteParams = {
  36. step: string;
  37. };
  38. type Props = RouteComponentProps<RouteParams, {}>;
  39. function getOrganizationOnboardingSteps(singleSelectPlatform: boolean): StepDescriptor[] {
  40. return [
  41. {
  42. id: 'welcome',
  43. title: t('Welcome'),
  44. Component: TargetedOnboardingWelcome,
  45. cornerVariant: 'top-right',
  46. },
  47. {
  48. ...(singleSelectPlatform
  49. ? {
  50. id: 'select-platform',
  51. title: t('Select platform'),
  52. Component: PlatformSelection,
  53. hasFooter: true,
  54. cornerVariant: 'top-left',
  55. }
  56. : {
  57. id: 'select-platform',
  58. title: t('Select platforms'),
  59. Component: OnboardingPlatform,
  60. hasFooter: true,
  61. cornerVariant: 'top-left',
  62. }),
  63. },
  64. {
  65. id: 'setup-docs',
  66. title: t('Install the Sentry SDK'),
  67. Component: SetupDocs,
  68. hasFooter: true,
  69. cornerVariant: 'top-left',
  70. },
  71. ];
  72. }
  73. function Onboarding(props: Props) {
  74. const api = useApi();
  75. const organization = useOrganization();
  76. const [clientState, setClientState] = usePersistedOnboardingState();
  77. const onboardingContext = useContext(OnboardingContext);
  78. const selectedPlatforms = clientState?.selectedPlatforms || [];
  79. const selectedProjectSlug = selectedPlatforms[0];
  80. const {
  81. logExperiment: productSelectionLogExperiment,
  82. experimentAssignment: productSelectionAssignment,
  83. } = useExperiment('OnboardingProductSelectionExperiment', {
  84. logExperimentOnMount: false,
  85. });
  86. const docsWithProductSelection = !!organization.features?.includes(
  87. 'onboarding-docs-with-product-selection'
  88. );
  89. const {
  90. params: {step: stepId},
  91. } = props;
  92. const cornerVariantTimeoutRed = useRef<number | undefined>(undefined);
  93. useEffect(() => {
  94. return () => {
  95. window.clearTimeout(cornerVariantTimeoutRed.current);
  96. };
  97. }, []);
  98. useEffect(() => {
  99. if (docsWithProductSelection) {
  100. productSelectionLogExperiment();
  101. }
  102. }, [productSelectionLogExperiment, docsWithProductSelection]);
  103. const heartbeatFooter = !!organization?.features.includes(
  104. 'onboarding-heartbeat-footer'
  105. );
  106. const singleSelectPlatform = !!organization?.features.includes(
  107. 'onboarding-remove-multiselect-platform'
  108. );
  109. const projectDeletionOnBackClick = !!organization?.features.includes(
  110. 'onboarding-project-deletion-on-back-click'
  111. );
  112. const onboardingSteps = getOrganizationOnboardingSteps(singleSelectPlatform);
  113. const stepObj = onboardingSteps.find(({id}) => stepId === id);
  114. const stepIndex = onboardingSteps.findIndex(({id}) => stepId === id);
  115. const cornerVariantControl = useAnimation();
  116. const updateCornerVariant = () => {
  117. // TODO: find better way to delay the corner animation
  118. window.clearTimeout(cornerVariantTimeoutRed.current);
  119. cornerVariantTimeoutRed.current = window.setTimeout(
  120. () => cornerVariantControl.start(stepIndex === 0 ? 'top-right' : 'top-left'),
  121. 1000
  122. );
  123. };
  124. useEffect(updateCornerVariant, [stepIndex, cornerVariantControl]);
  125. // Called onExitComplete
  126. const [containerHasFooter, setContainerHasFooter] = useState<boolean>(false);
  127. const updateAnimationState = () => {
  128. if (!stepObj) {
  129. return;
  130. }
  131. setContainerHasFooter(stepObj.hasFooter ?? false);
  132. };
  133. const goToStep = (step: StepDescriptor) => {
  134. if (!stepObj) {
  135. return;
  136. }
  137. if (step.cornerVariant !== stepObj.cornerVariant) {
  138. cornerVariantControl.start('none');
  139. }
  140. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${step.id}/`));
  141. };
  142. const goNextStep = useCallback(
  143. (step: StepDescriptor, platforms?: PlatformKey[]) => {
  144. const currentStepIndex = onboardingSteps.findIndex(s => s.id === step.id);
  145. const nextStep = onboardingSteps[currentStepIndex + 1];
  146. if (nextStep.id === 'setup-docs' && !platforms) {
  147. return;
  148. }
  149. if (step.cornerVariant !== nextStep.cornerVariant) {
  150. cornerVariantControl.start('none');
  151. }
  152. if (
  153. nextStep.id === 'setup-docs' &&
  154. platforms?.[0] === 'javascript-react' &&
  155. docsWithProductSelection
  156. ) {
  157. if (productSelectionAssignment === 'variant1') {
  158. props.router.push(
  159. normalizeUrl(
  160. `/onboarding/${organization.slug}/${nextStep.id}/?product=${PRODUCT.PERFORMANCE_MONITORING}&product=${PRODUCT.SESSION_REPLAY}`
  161. )
  162. );
  163. return;
  164. }
  165. }
  166. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${nextStep.id}/`));
  167. },
  168. [
  169. organization.slug,
  170. onboardingSteps,
  171. cornerVariantControl,
  172. props.router,
  173. productSelectionAssignment,
  174. docsWithProductSelection,
  175. ]
  176. );
  177. const deleteProject = useCallback(
  178. async (projectSlug: string) => {
  179. try {
  180. await removeProject(api, organization.slug, projectSlug);
  181. } catch (error) {
  182. handleXhrErrorResponse(t('Unable to delete project'))(error);
  183. // we don't give the user any feedback regarding this error as this shall be silent
  184. }
  185. },
  186. [api, organization.slug]
  187. );
  188. const handleGoBack = useCallback(() => {
  189. if (!stepObj) {
  190. return;
  191. }
  192. const previousStep = onboardingSteps[stepIndex - 1];
  193. if (!previousStep) {
  194. return;
  195. }
  196. if (stepObj.cornerVariant !== previousStep.cornerVariant) {
  197. cornerVariantControl.start('none');
  198. }
  199. trackAdvancedAnalyticsEvent('onboarding.back_button_clicked', {
  200. organization,
  201. from: onboardingSteps[stepIndex].id,
  202. to: previousStep.id,
  203. });
  204. // from selected platform to welcome
  205. if (onboardingSteps[stepIndex].id === 'select-platform') {
  206. setClientState({
  207. platformToProjectIdMap: clientState?.platformToProjectIdMap ?? {},
  208. selectedPlatforms: [],
  209. url: 'welcome/',
  210. state: undefined,
  211. });
  212. }
  213. // from setup docs to selected platform
  214. if (onboardingSteps[stepIndex].id === 'setup-docs' && projectDeletionOnBackClick) {
  215. // The user is going back to select a new platform,
  216. // so we silently delete the last created project
  217. // if the user didn't send an first error yet.
  218. const projectShallBeRemoved = !Object.keys(onboardingContext.data).some(
  219. key =>
  220. onboardingContext.data[key].slug === selectedProjectSlug &&
  221. (onboardingContext.data[key].status === OnboardingStatus.PROCESSING ||
  222. onboardingContext.data[key].status === OnboardingStatus.PROCESSED)
  223. );
  224. let platformToProjectIdMap = clientState?.platformToProjectIdMap ?? {};
  225. if (projectShallBeRemoved) {
  226. deleteProject(selectedProjectSlug);
  227. platformToProjectIdMap = Object.keys(
  228. clientState?.platformToProjectIdMap ?? {}
  229. ).reduce((acc, platform) => {
  230. if (!acc[platform] && platform !== selectedProjectSlug) {
  231. acc[platform] = platform;
  232. }
  233. return acc;
  234. }, {});
  235. }
  236. setClientState({
  237. url: 'select-platform/',
  238. state: 'projects_selected',
  239. selectedPlatforms: [selectedProjectSlug as PlatformKey],
  240. platformToProjectIdMap,
  241. });
  242. }
  243. props.router.replace(
  244. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  245. );
  246. }, [
  247. stepObj,
  248. stepIndex,
  249. onboardingSteps,
  250. organization,
  251. cornerVariantControl,
  252. clientState,
  253. setClientState,
  254. selectedProjectSlug,
  255. props.router,
  256. deleteProject,
  257. projectDeletionOnBackClick,
  258. onboardingContext,
  259. ]);
  260. const genSkipOnboardingLink = () => {
  261. const source = `targeted-onboarding-${stepId}`;
  262. return (
  263. <SkipOnboardingLink
  264. onClick={() => {
  265. trackAdvancedAnalyticsEvent('growth.onboarding_clicked_skip', {
  266. organization,
  267. source,
  268. });
  269. if (clientState) {
  270. setClientState({
  271. ...clientState,
  272. state: 'skipped',
  273. });
  274. }
  275. }}
  276. to={normalizeUrl(
  277. `/organizations/${organization.slug}/issues/?referrer=onboarding-skip`
  278. )}
  279. >
  280. {t('Skip Onboarding')}
  281. </SkipOnboardingLink>
  282. );
  283. };
  284. const jumpToSetupProject = useCallback(() => {
  285. const nextStep = onboardingSteps.find(({id}) => id === 'setup-docs');
  286. if (!nextStep) {
  287. Sentry.captureMessage(
  288. 'Missing step in onboarding: `setup-docs` when trying to jump there'
  289. );
  290. return;
  291. }
  292. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${nextStep.id}/`));
  293. }, [onboardingSteps, organization, props.router]);
  294. if (!stepObj || stepIndex === -1) {
  295. return (
  296. <Redirect
  297. to={normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[0].id}/`)}
  298. />
  299. );
  300. }
  301. return (
  302. <OnboardingWrapper data-test-id="targeted-onboarding">
  303. <SentryDocumentTitle title={stepObj.title} />
  304. <Header>
  305. <LogoSvg />
  306. {stepIndex !== -1 && (
  307. <StyledStepper
  308. numSteps={onboardingSteps.length}
  309. currentStepIndex={stepIndex}
  310. onClick={i => goToStep(onboardingSteps[i])}
  311. />
  312. )}
  313. <UpsellWrapper>
  314. <Hook
  315. name="onboarding:targeted-onboarding-header"
  316. source="targeted-onboarding"
  317. />
  318. </UpsellWrapper>
  319. </Header>
  320. <Container hasFooter={containerHasFooter} heartbeatFooter={heartbeatFooter}>
  321. <Back animate={stepIndex > 0 ? 'visible' : 'hidden'} onClick={handleGoBack} />
  322. <AnimatePresence exitBeforeEnter onExitComplete={updateAnimationState}>
  323. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  324. {stepObj.Component && (
  325. <stepObj.Component
  326. active
  327. data-test-id={`onboarding-step-${stepObj.id}`}
  328. stepIndex={stepIndex}
  329. onComplete={platforms => {
  330. if (stepObj) {
  331. goNextStep(stepObj, platforms);
  332. }
  333. }}
  334. orgId={organization.slug}
  335. search={props.location.search}
  336. route={props.route}
  337. router={props.router}
  338. location={props.location}
  339. jumpToSetupProject={jumpToSetupProject}
  340. selectedProjectSlug={selectedProjectSlug}
  341. {...{
  342. genSkipOnboardingLink,
  343. }}
  344. />
  345. )}
  346. </OnboardingStep>
  347. </AnimatePresence>
  348. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  349. </Container>
  350. </OnboardingWrapper>
  351. );
  352. }
  353. const Container = styled('div')<{hasFooter: boolean; heartbeatFooter: boolean}>`
  354. flex-grow: 1;
  355. display: flex;
  356. flex-direction: column;
  357. position: relative;
  358. background: ${p => p.theme.background};
  359. padding: ${p =>
  360. p.heartbeatFooter ? `120px ${space(3)} 0 ${space(3)}` : `120px ${space(3)}`};
  361. width: 100%;
  362. margin: 0 auto;
  363. padding-bottom: ${p => p.hasFooter && '72px'};
  364. margin-bottom: ${p => p.hasFooter && '72px'};
  365. `;
  366. const Header = styled('header')`
  367. background: ${p => p.theme.background};
  368. padding-left: ${space(4)};
  369. padding-right: ${space(4)};
  370. position: sticky;
  371. height: 80px;
  372. align-items: center;
  373. top: 0;
  374. z-index: 100;
  375. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  376. display: grid;
  377. grid-template-columns: 1fr 1fr 1fr;
  378. justify-items: stretch;
  379. `;
  380. const LogoSvg = styled(LogoSentry)`
  381. width: 130px;
  382. height: 30px;
  383. color: ${p => p.theme.textColor};
  384. `;
  385. const OnboardingStep = styled(motion.div)`
  386. flex-grow: 1;
  387. display: flex;
  388. flex-direction: column;
  389. `;
  390. OnboardingStep.defaultProps = {
  391. initial: 'initial',
  392. animate: 'animate',
  393. exit: 'exit',
  394. variants: {animate: {}},
  395. transition: testableTransition({
  396. staggerChildren: 0.2,
  397. }),
  398. };
  399. const Sidebar = styled(motion.div)`
  400. width: 850px;
  401. display: flex;
  402. flex-direction: column;
  403. align-items: center;
  404. `;
  405. Sidebar.defaultProps = {
  406. initial: 'initial',
  407. animate: 'animate',
  408. exit: 'exit',
  409. variants: {animate: {}},
  410. transition: testableTransition({
  411. staggerChildren: 0.2,
  412. }),
  413. };
  414. const AdaptivePageCorners = styled(PageCorners)`
  415. --corner-scale: 1;
  416. @media (max-width: ${p => p.theme.breakpoints.small}) {
  417. --corner-scale: 0.5;
  418. }
  419. `;
  420. const StyledStepper = styled(Stepper)`
  421. justify-self: center;
  422. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  423. display: none;
  424. }
  425. `;
  426. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  427. animate: MotionProps['animate'];
  428. className?: string;
  429. }
  430. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  431. <motion.div
  432. className={className}
  433. animate={animate}
  434. transition={testableTransition()}
  435. variants={{
  436. initial: {opacity: 0, visibility: 'hidden'},
  437. visible: {
  438. opacity: 1,
  439. visibility: 'visible',
  440. transition: testableTransition({delay: 1}),
  441. },
  442. hidden: {
  443. opacity: 0,
  444. transitionEnd: {
  445. visibility: 'hidden',
  446. },
  447. },
  448. }}
  449. >
  450. <Button {...props} icon={<IconArrow direction="left" size="sm" />} priority="link">
  451. {t('Back')}
  452. </Button>
  453. </motion.div>
  454. ))`
  455. position: absolute;
  456. top: 40px;
  457. left: 20px;
  458. button {
  459. font-size: ${p => p.theme.fontSizeSmall};
  460. }
  461. `;
  462. const SkipOnboardingLink = styled(Link)`
  463. margin: auto ${space(4)};
  464. `;
  465. const UpsellWrapper = styled('div')`
  466. grid-column: 3;
  467. margin-left: auto;
  468. `;
  469. const OnboardingWrapper = styled('main')`
  470. flex-grow: 1;
  471. display: flex;
  472. flex-direction: column;
  473. `;
  474. export default Onboarding;