onboarding.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 = useCallback(
  127. (step: StepDescriptor, platforms?: PlatformKey[]) => {
  128. const currentStepIndex = onboardingSteps.findIndex(s => s.id === step.id);
  129. const nextStep = onboardingSteps[currentStepIndex + 1];
  130. if (nextStep.id === 'setup-docs' && !platforms) {
  131. return;
  132. }
  133. if (step.cornerVariant !== nextStep.cornerVariant) {
  134. cornerVariantControl.start('none');
  135. }
  136. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${nextStep.id}/`));
  137. },
  138. [organization.slug, onboardingSteps, cornerVariantControl, props.router]
  139. );
  140. const deleteProject = useCallback(
  141. async (projectSlug: string) => {
  142. try {
  143. await removeProject(api, organization.slug, projectSlug);
  144. } catch (error) {
  145. handleXhrErrorResponse(t('Unable to delete project'))(error);
  146. // we don't give the user any feedback regarding this error as this shall be silent
  147. }
  148. },
  149. [api, organization.slug]
  150. );
  151. const handleGoBack = useCallback(() => {
  152. if (!stepObj) {
  153. return;
  154. }
  155. const previousStep = onboardingSteps[stepIndex - 1];
  156. if (!previousStep) {
  157. return;
  158. }
  159. if (stepObj.cornerVariant !== previousStep.cornerVariant) {
  160. cornerVariantControl.start('none');
  161. }
  162. trackAdvancedAnalyticsEvent('onboarding.back_button_clicked', {
  163. organization,
  164. from: onboardingSteps[stepIndex].id,
  165. to: previousStep.id,
  166. });
  167. // from selected platform to welcome
  168. if (onboardingSteps[stepIndex].id === 'select-platform') {
  169. setClientState({
  170. platformToProjectIdMap: clientState?.platformToProjectIdMap ?? {},
  171. selectedPlatforms: [],
  172. url: 'welcome/',
  173. state: undefined,
  174. });
  175. }
  176. // from setup docs to selected platform
  177. if (onboardingSteps[stepIndex].id === 'setup-docs' && projectDeletionOnBackClick) {
  178. // The user is going back to select a new platform,
  179. // so we silently delete the last created project
  180. // if the user didn't send an first error yet.
  181. const projectShallBeRemoved = !Object.keys(onboardingContext.data).some(
  182. key =>
  183. onboardingContext.data[key].slug === selectedProjectSlug &&
  184. (onboardingContext.data[key].status === OnboardingStatus.PROCESSING ||
  185. onboardingContext.data[key].status === OnboardingStatus.PROCESSED)
  186. );
  187. let platformToProjectIdMap = clientState?.platformToProjectIdMap ?? {};
  188. if (projectShallBeRemoved) {
  189. deleteProject(selectedProjectSlug);
  190. platformToProjectIdMap = Object.keys(
  191. clientState?.platformToProjectIdMap ?? {}
  192. ).reduce((acc, platform) => {
  193. if (!acc[platform] && platform !== selectedProjectSlug) {
  194. acc[platform] = platform;
  195. }
  196. return acc;
  197. }, {});
  198. }
  199. setClientState({
  200. url: 'select-platform/',
  201. state: 'projects_selected',
  202. selectedPlatforms: [selectedProjectSlug as PlatformKey],
  203. platformToProjectIdMap,
  204. });
  205. }
  206. props.router.replace(
  207. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  208. );
  209. }, [
  210. stepObj,
  211. stepIndex,
  212. onboardingSteps,
  213. organization,
  214. cornerVariantControl,
  215. clientState,
  216. setClientState,
  217. selectedProjectSlug,
  218. props.router,
  219. deleteProject,
  220. projectDeletionOnBackClick,
  221. onboardingContext,
  222. ]);
  223. const genSkipOnboardingLink = () => {
  224. const source = `targeted-onboarding-${stepId}`;
  225. return (
  226. <SkipOnboardingLink
  227. onClick={() => {
  228. trackAdvancedAnalyticsEvent('growth.onboarding_clicked_skip', {
  229. organization,
  230. source,
  231. });
  232. if (clientState) {
  233. setClientState({
  234. ...clientState,
  235. state: 'skipped',
  236. });
  237. }
  238. }}
  239. to={normalizeUrl(
  240. `/organizations/${organization.slug}/issues/?referrer=onboarding-skip`
  241. )}
  242. >
  243. {t('Skip Onboarding')}
  244. </SkipOnboardingLink>
  245. );
  246. };
  247. const jumpToSetupProject = useCallback(() => {
  248. const nextStep = onboardingSteps.find(({id}) => id === 'setup-docs');
  249. if (!nextStep) {
  250. Sentry.captureMessage(
  251. 'Missing step in onboarding: `setup-docs` when trying to jump there'
  252. );
  253. return;
  254. }
  255. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${nextStep.id}/`));
  256. }, [onboardingSteps, organization, props.router]);
  257. if (!stepObj || stepIndex === -1) {
  258. return (
  259. <Redirect
  260. to={normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[0].id}/`)}
  261. />
  262. );
  263. }
  264. return (
  265. <OnboardingWrapper data-test-id="targeted-onboarding">
  266. <SentryDocumentTitle title={stepObj.title} />
  267. <Header>
  268. <LogoSvg />
  269. {stepIndex !== -1 && (
  270. <StyledStepper
  271. numSteps={onboardingSteps.length}
  272. currentStepIndex={stepIndex}
  273. onClick={i => goToStep(onboardingSteps[i])}
  274. />
  275. )}
  276. <UpsellWrapper>
  277. <Hook
  278. name="onboarding:targeted-onboarding-header"
  279. source="targeted-onboarding"
  280. />
  281. </UpsellWrapper>
  282. </Header>
  283. <Container hasFooter={containerHasFooter} heartbeatFooter={heartbeatFooter}>
  284. <Back animate={stepIndex > 0 ? 'visible' : 'hidden'} onClick={handleGoBack} />
  285. <AnimatePresence exitBeforeEnter onExitComplete={updateAnimationState}>
  286. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  287. {stepObj.Component && (
  288. <stepObj.Component
  289. active
  290. data-test-id={`onboarding-step-${stepObj.id}`}
  291. stepIndex={stepIndex}
  292. onComplete={platforms => {
  293. if (stepObj) {
  294. goNextStep(stepObj, platforms);
  295. }
  296. }}
  297. orgId={organization.slug}
  298. search={props.location.search}
  299. route={props.route}
  300. router={props.router}
  301. location={props.location}
  302. jumpToSetupProject={jumpToSetupProject}
  303. selectedProjectSlug={selectedProjectSlug}
  304. {...{
  305. genSkipOnboardingLink,
  306. }}
  307. />
  308. )}
  309. </OnboardingStep>
  310. </AnimatePresence>
  311. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  312. </Container>
  313. </OnboardingWrapper>
  314. );
  315. }
  316. const Container = styled('div')<{hasFooter: boolean; heartbeatFooter: boolean}>`
  317. flex-grow: 1;
  318. display: flex;
  319. flex-direction: column;
  320. position: relative;
  321. background: ${p => p.theme.background};
  322. padding: ${p =>
  323. p.heartbeatFooter ? `120px ${space(3)} 0 ${space(3)}` : `120px ${space(3)}`};
  324. width: 100%;
  325. margin: 0 auto;
  326. padding-bottom: ${p => p.hasFooter && '72px'};
  327. margin-bottom: ${p => p.hasFooter && '72px'};
  328. `;
  329. const Header = styled('header')`
  330. background: ${p => p.theme.background};
  331. padding-left: ${space(4)};
  332. padding-right: ${space(4)};
  333. position: sticky;
  334. height: 80px;
  335. align-items: center;
  336. top: 0;
  337. z-index: 100;
  338. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  339. display: grid;
  340. grid-template-columns: 1fr 1fr 1fr;
  341. justify-items: stretch;
  342. `;
  343. const LogoSvg = styled(LogoSentry)`
  344. width: 130px;
  345. height: 30px;
  346. color: ${p => p.theme.textColor};
  347. `;
  348. const OnboardingStep = styled(motion.div)`
  349. flex-grow: 1;
  350. display: flex;
  351. flex-direction: column;
  352. `;
  353. OnboardingStep.defaultProps = {
  354. initial: 'initial',
  355. animate: 'animate',
  356. exit: 'exit',
  357. variants: {animate: {}},
  358. transition: testableTransition({
  359. staggerChildren: 0.2,
  360. }),
  361. };
  362. const Sidebar = styled(motion.div)`
  363. width: 850px;
  364. display: flex;
  365. flex-direction: column;
  366. align-items: center;
  367. `;
  368. Sidebar.defaultProps = {
  369. initial: 'initial',
  370. animate: 'animate',
  371. exit: 'exit',
  372. variants: {animate: {}},
  373. transition: testableTransition({
  374. staggerChildren: 0.2,
  375. }),
  376. };
  377. const AdaptivePageCorners = styled(PageCorners)`
  378. --corner-scale: 1;
  379. @media (max-width: ${p => p.theme.breakpoints.small}) {
  380. --corner-scale: 0.5;
  381. }
  382. `;
  383. const StyledStepper = styled(Stepper)`
  384. justify-self: center;
  385. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  386. display: none;
  387. }
  388. `;
  389. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  390. animate: MotionProps['animate'];
  391. className?: string;
  392. }
  393. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  394. <motion.div
  395. className={className}
  396. animate={animate}
  397. transition={testableTransition()}
  398. variants={{
  399. initial: {opacity: 0, visibility: 'hidden'},
  400. visible: {
  401. opacity: 1,
  402. visibility: 'visible',
  403. transition: testableTransition({delay: 1}),
  404. },
  405. hidden: {
  406. opacity: 0,
  407. transitionEnd: {
  408. visibility: 'hidden',
  409. },
  410. },
  411. }}
  412. >
  413. <Button {...props} icon={<IconArrow direction="left" size="sm" />} priority="link">
  414. {t('Back')}
  415. </Button>
  416. </motion.div>
  417. ))`
  418. position: absolute;
  419. top: 40px;
  420. left: 20px;
  421. button {
  422. font-size: ${p => p.theme.fontSizeSmall};
  423. }
  424. `;
  425. const SkipOnboardingLink = styled(Link)`
  426. margin: auto ${space(4)};
  427. `;
  428. const UpsellWrapper = styled('div')`
  429. grid-column: 3;
  430. margin-left: auto;
  431. `;
  432. const OnboardingWrapper = styled('main')`
  433. flex-grow: 1;
  434. display: flex;
  435. flex-direction: column;
  436. `;
  437. export default Onboarding;