onboarding.tsx 15 KB

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