onboarding.tsx 14 KB

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