onboarding.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import {useCallback, useContext, useEffect, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {MotionProps} from 'framer-motion';
  4. import {AnimatePresence, motion, useAnimation} from 'framer-motion';
  5. import {removeProject} from 'sentry/actionCreators/projects';
  6. import type {ButtonProps} from 'sentry/components/button';
  7. import {Button} from 'sentry/components/button';
  8. import type {OpenConfirmOptions} from 'sentry/components/confirm';
  9. import Confirm, {openConfirmModal} from 'sentry/components/confirm';
  10. import Hook from 'sentry/components/hook';
  11. import Link from 'sentry/components/links/link';
  12. import LogoSentry from 'sentry/components/logoSentry';
  13. import {OnboardingContext} from 'sentry/components/onboarding/onboardingContext';
  14. import {useRecentCreatedProject} from 'sentry/components/onboarding/useRecentCreatedProject';
  15. import Redirect from 'sentry/components/redirect';
  16. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  17. import categoryList from 'sentry/data/platformPickerCategories';
  18. import platforms from 'sentry/data/platforms';
  19. import {IconArrow} from 'sentry/icons';
  20. import {t} from 'sentry/locale';
  21. import {space} from 'sentry/styles/space';
  22. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  23. import type {OnboardingSelectedSDK} from 'sentry/types/onboarding';
  24. import {defined} from 'sentry/utils';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import {handleXhrErrorResponse} from 'sentry/utils/handleXhrErrorResponse';
  27. import testableTransition from 'sentry/utils/testableTransition';
  28. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  29. import useApi from 'sentry/utils/useApi';
  30. import useOrganization from 'sentry/utils/useOrganization';
  31. import PageCorners from 'sentry/views/onboarding/components/pageCorners';
  32. import Stepper from './components/stepper';
  33. import {PlatformSelection} from './platformSelection';
  34. import SetupDocs from './setupDocs';
  35. import type {StepDescriptor} from './types';
  36. import TargetedOnboardingWelcome from './welcome';
  37. type RouteParams = {
  38. step: string;
  39. };
  40. type Props = RouteComponentProps<RouteParams, {}>;
  41. function getOrganizationOnboardingSteps(): StepDescriptor[] {
  42. return [
  43. {
  44. id: 'welcome',
  45. title: t('Welcome'),
  46. Component: TargetedOnboardingWelcome,
  47. cornerVariant: 'top-right',
  48. },
  49. {
  50. id: 'select-platform',
  51. title: t('Select platform'),
  52. Component: PlatformSelection,
  53. hasFooter: true,
  54. cornerVariant: 'top-left',
  55. },
  56. {
  57. id: 'setup-docs',
  58. title: t('Install the Sentry SDK'),
  59. Component: SetupDocs,
  60. hasFooter: true,
  61. cornerVariant: 'top-left',
  62. },
  63. ];
  64. }
  65. function Onboarding(props: Props) {
  66. const api = useApi();
  67. const organization = useOrganization();
  68. const onboardingContext = useContext(OnboardingContext);
  69. const selectedSDK = onboardingContext.data.selectedSDK;
  70. const selectedProjectSlug = selectedSDK?.key;
  71. const {
  72. params: {step: stepId},
  73. } = props;
  74. const onboardingSteps = getOrganizationOnboardingSteps();
  75. const stepObj = onboardingSteps.find(({id}) => stepId === id);
  76. const stepIndex = onboardingSteps.findIndex(({id}) => stepId === id);
  77. const projectSlug =
  78. stepObj && stepObj.id === 'setup-docs' ? selectedProjectSlug : undefined;
  79. const recentCreatedProject = useRecentCreatedProject({
  80. orgSlug: organization.slug,
  81. projectSlug,
  82. });
  83. const cornerVariantTimeoutRed = useRef<number | undefined>(undefined);
  84. useEffect(() => {
  85. return () => {
  86. window.clearTimeout(cornerVariantTimeoutRed.current);
  87. };
  88. }, []);
  89. useEffect(() => {
  90. if (
  91. props.location.pathname === `/onboarding/${onboardingSteps[2]!.id}/` &&
  92. props.location.query?.platform &&
  93. onboardingContext.data.selectedSDK === undefined
  94. ) {
  95. const platformKey = Object.keys(platforms).find(
  96. // @ts-expect-error TS(7015): Element implicitly has an 'any' type because index... Remove this comment to see the full error message
  97. key => platforms[key].id === props.location.query.platform
  98. );
  99. // @ts-expect-error TS(7015): Element implicitly has an 'any' type because index... Remove this comment to see the full error message
  100. const platform = platformKey ? platforms[platformKey] : undefined;
  101. // if no platform found, we redirect the user to the platform select page
  102. if (!platform) {
  103. props.router.push(
  104. normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[1]!.id}/`)
  105. );
  106. return;
  107. }
  108. const frameworkCategory =
  109. categoryList.find(category => {
  110. return category.platforms?.has(platform.id);
  111. })?.id ?? 'all';
  112. onboardingContext.setData({
  113. ...onboardingContext.data,
  114. selectedSDK: {
  115. key: props.location.query.platform,
  116. category: frameworkCategory,
  117. language: platform.language,
  118. type: platform.type,
  119. link: platform.link,
  120. name: platform.name,
  121. },
  122. });
  123. }
  124. }, [
  125. props.location.query,
  126. props.router,
  127. onboardingContext,
  128. onboardingSteps,
  129. organization.slug,
  130. props.location.pathname,
  131. ]);
  132. const shallProjectBeDeleted =
  133. stepObj?.id === 'setup-docs' &&
  134. recentCreatedProject &&
  135. // if the project has received a first error, we don't delete it
  136. recentCreatedProject.firstError === false &&
  137. // if the project has received a first transaction, we don't delete it
  138. recentCreatedProject.firstTransaction === false &&
  139. // if the project has replays, we don't delete it
  140. recentCreatedProject.hasReplays === false &&
  141. // if the project has sessions, we don't delete it
  142. recentCreatedProject.hasSessions === false &&
  143. // if the project is older than one hour, we don't delete it
  144. recentCreatedProject.olderThanOneHour === false;
  145. const cornerVariantControl = useAnimation();
  146. const updateCornerVariant = () => {
  147. // TODO: find better way to delay the corner animation
  148. window.clearTimeout(cornerVariantTimeoutRed.current);
  149. cornerVariantTimeoutRed.current = window.setTimeout(
  150. () => cornerVariantControl.start(stepIndex === 0 ? 'top-right' : 'top-left'),
  151. 1000
  152. );
  153. };
  154. useEffect(updateCornerVariant, [stepIndex, cornerVariantControl]);
  155. // Called onExitComplete
  156. const [containerHasFooter, setContainerHasFooter] = useState<boolean>(false);
  157. const updateAnimationState = () => {
  158. if (!stepObj) {
  159. return;
  160. }
  161. setContainerHasFooter(stepObj.hasFooter ?? false);
  162. };
  163. const goToStep = (step: StepDescriptor) => {
  164. if (!stepObj) {
  165. return;
  166. }
  167. if (step.cornerVariant !== stepObj.cornerVariant) {
  168. cornerVariantControl.start('none');
  169. }
  170. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${step.id}/`));
  171. };
  172. const goNextStep = useCallback(
  173. (step: StepDescriptor, platform?: OnboardingSelectedSDK) => {
  174. const currentStepIndex = onboardingSteps.findIndex(s => s.id === step.id);
  175. const nextStep = onboardingSteps[currentStepIndex + 1]!;
  176. if (nextStep.id === 'setup-docs' && !platform) {
  177. return;
  178. }
  179. if (step.cornerVariant !== nextStep.cornerVariant) {
  180. cornerVariantControl.start('none');
  181. }
  182. props.router.push(normalizeUrl(`/onboarding/${organization.slug}/${nextStep.id}/`));
  183. },
  184. [organization.slug, onboardingSteps, cornerVariantControl, props.router]
  185. );
  186. const deleteRecentCreatedProject = useCallback(async () => {
  187. if (!recentCreatedProject?.slug) {
  188. return;
  189. }
  190. const newProjects = Object.keys(onboardingContext.data.projects).reduce(
  191. (acc, key) => {
  192. if (
  193. onboardingContext.data.projects[key]!.slug !==
  194. onboardingContext.data.selectedSDK?.key
  195. ) {
  196. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  197. acc[key] = onboardingContext.data.projects[key];
  198. }
  199. return acc;
  200. },
  201. {}
  202. );
  203. try {
  204. await removeProject({
  205. api,
  206. orgSlug: organization.slug,
  207. projectSlug: recentCreatedProject.slug,
  208. origin: 'onboarding',
  209. });
  210. onboardingContext.setData({
  211. ...onboardingContext.data,
  212. projects: newProjects,
  213. });
  214. trackAnalytics('onboarding.data_removed', {
  215. organization,
  216. date_created: recentCreatedProject.dateCreated,
  217. platform: recentCreatedProject.slug,
  218. project_id: recentCreatedProject.id,
  219. });
  220. } catch (error) {
  221. handleXhrErrorResponse('Unable to delete project in onboarding', error);
  222. // we don't give the user any feedback regarding this error as this shall be silent
  223. }
  224. }, [api, organization, recentCreatedProject, onboardingContext]);
  225. const handleGoBack = useCallback(
  226. (goToStepIndex?: number) => {
  227. if (!stepObj) {
  228. return;
  229. }
  230. const previousStep = defined(goToStepIndex)
  231. ? onboardingSteps[goToStepIndex]
  232. : onboardingSteps[stepIndex - 1];
  233. if (!previousStep) {
  234. return;
  235. }
  236. if (stepObj.cornerVariant !== previousStep.cornerVariant) {
  237. cornerVariantControl.start('none');
  238. }
  239. trackAnalytics('onboarding.back_button_clicked', {
  240. organization,
  241. from: onboardingSteps[stepIndex]!.id,
  242. to: previousStep.id,
  243. });
  244. // from selected platform to welcome
  245. if (onboardingSteps[stepIndex]!.id === 'select-platform') {
  246. onboardingContext.setData({...onboardingContext.data, selectedSDK: undefined});
  247. props.router.replace(
  248. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  249. );
  250. return;
  251. }
  252. // from setup docs to selected platform
  253. if (onboardingSteps[stepIndex]!.id === 'setup-docs' && shallProjectBeDeleted) {
  254. trackAnalytics('onboarding.data_removal_modal_confirm_button_clicked', {
  255. organization,
  256. platform: recentCreatedProject.slug,
  257. project_id: recentCreatedProject.id,
  258. });
  259. deleteRecentCreatedProject();
  260. }
  261. props.router.replace(
  262. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  263. );
  264. },
  265. [
  266. stepObj,
  267. stepIndex,
  268. onboardingSteps,
  269. organization,
  270. cornerVariantControl,
  271. props.router,
  272. onboardingContext,
  273. shallProjectBeDeleted,
  274. deleteRecentCreatedProject,
  275. recentCreatedProject,
  276. ]
  277. );
  278. const genSkipOnboardingLink = () => {
  279. const source = `targeted-onboarding-${stepId}`;
  280. return (
  281. <SkipOnboardingLink
  282. onClick={() => {
  283. trackAnalytics('growth.onboarding_clicked_skip', {
  284. organization,
  285. source,
  286. });
  287. onboardingContext.setData({...onboardingContext.data, selectedSDK: undefined});
  288. }}
  289. to={normalizeUrl(
  290. `/organizations/${organization.slug}/issues/?referrer=onboarding-skip`
  291. )}
  292. >
  293. {t('Skip Onboarding')}
  294. </SkipOnboardingLink>
  295. );
  296. };
  297. // Redirect to the first step if we end up in an invalid state
  298. const isInvalidDocsStep = stepId === 'setup-docs' && !projectSlug;
  299. if (!stepObj || stepIndex === -1 || isInvalidDocsStep) {
  300. return (
  301. <Redirect
  302. to={normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[0]!.id}/`)}
  303. />
  304. );
  305. }
  306. const goBackDeletionAlertModalProps: OpenConfirmOptions = {
  307. message: t(
  308. "Hey, just a heads up - we haven't received any data for this SDK yet and by going back all changes will be discarded. Are you sure you want to head back?"
  309. ),
  310. priority: 'danger',
  311. confirmText: t("Yes I'm sure"),
  312. onConfirm: handleGoBack,
  313. onClose: () => {
  314. if (!recentCreatedProject) {
  315. return;
  316. }
  317. trackAnalytics('onboarding.data_removal_modal_dismissed', {
  318. organization,
  319. platform: recentCreatedProject.slug,
  320. project_id: recentCreatedProject.id,
  321. });
  322. },
  323. onRender: () => {
  324. if (!recentCreatedProject) {
  325. return;
  326. }
  327. trackAnalytics('onboarding.data_removal_modal_rendered', {
  328. organization,
  329. platform: recentCreatedProject.slug,
  330. project_id: recentCreatedProject.id,
  331. });
  332. },
  333. };
  334. return (
  335. <OnboardingWrapper data-test-id="targeted-onboarding">
  336. <SentryDocumentTitle title={stepObj.title} />
  337. <Header>
  338. <LogoSvg />
  339. {stepIndex !== -1 && (
  340. <StyledStepper
  341. numSteps={onboardingSteps.length}
  342. currentStepIndex={stepIndex}
  343. onClick={i => {
  344. if ((i as number) < stepIndex && shallProjectBeDeleted) {
  345. openConfirmModal({
  346. ...goBackDeletionAlertModalProps,
  347. // @ts-expect-error TS(2345): Argument of type 'number | MouseEvent<HTMLDivEleme... Remove this comment to see the full error message
  348. onConfirm: () => handleGoBack(i),
  349. });
  350. return;
  351. }
  352. // @ts-expect-error TS(2538): Type 'MouseEvent<HTMLDivElement, MouseEvent>' cann... Remove this comment to see the full error message
  353. goToStep(onboardingSteps[i]!);
  354. }}
  355. />
  356. )}
  357. <UpsellWrapper>
  358. <Hook
  359. name="onboarding:targeted-onboarding-header"
  360. source="targeted-onboarding"
  361. />
  362. </UpsellWrapper>
  363. </Header>
  364. <Container hasFooter={containerHasFooter}>
  365. <Confirm bypass={!shallProjectBeDeleted} {...goBackDeletionAlertModalProps}>
  366. <Back animate={stepIndex > 0 ? 'visible' : 'hidden'} />
  367. </Confirm>
  368. <AnimatePresence mode="wait" onExitComplete={updateAnimationState}>
  369. <OnboardingStep
  370. initial="initial"
  371. animate="animate"
  372. exit="exit"
  373. variants={{animate: {}}}
  374. transition={testableTransition({
  375. staggerChildren: 0.2,
  376. })}
  377. key={stepObj.id}
  378. data-test-id={`onboarding-step-${stepObj.id}`}
  379. >
  380. {stepObj.Component && (
  381. <stepObj.Component
  382. active
  383. data-test-id={`onboarding-step-${stepObj.id}`}
  384. stepIndex={stepIndex}
  385. onComplete={platform => {
  386. if (stepObj) {
  387. goNextStep(stepObj, platform);
  388. }
  389. }}
  390. orgId={organization.slug}
  391. search={props.location.search}
  392. route={props.route}
  393. router={props.router}
  394. location={props.location}
  395. recentCreatedProject={recentCreatedProject}
  396. {...{
  397. genSkipOnboardingLink,
  398. }}
  399. />
  400. )}
  401. </OnboardingStep>
  402. </AnimatePresence>
  403. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  404. </Container>
  405. </OnboardingWrapper>
  406. );
  407. }
  408. const Container = styled('div')<{hasFooter: boolean}>`
  409. flex-grow: 1;
  410. display: flex;
  411. flex-direction: column;
  412. position: relative;
  413. background: ${p => p.theme.background};
  414. padding: 120px ${space(3)};
  415. width: 100%;
  416. margin: 0 auto;
  417. padding-bottom: ${p => p.hasFooter && '72px'};
  418. margin-bottom: ${p => p.hasFooter && '72px'};
  419. `;
  420. const Header = styled('header')`
  421. background: ${p => p.theme.background};
  422. padding-left: ${space(4)};
  423. padding-right: ${space(4)};
  424. position: sticky;
  425. height: 80px;
  426. align-items: center;
  427. top: 0;
  428. z-index: 100;
  429. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  430. display: grid;
  431. grid-template-columns: 1fr 1fr 1fr;
  432. justify-items: stretch;
  433. `;
  434. const LogoSvg = styled(LogoSentry)`
  435. width: 130px;
  436. height: 30px;
  437. color: ${p => p.theme.textColor};
  438. `;
  439. const OnboardingStep = styled(motion.div)`
  440. flex-grow: 1;
  441. display: flex;
  442. flex-direction: column;
  443. `;
  444. const AdaptivePageCorners = styled(PageCorners)`
  445. --corner-scale: 1;
  446. @media (max-width: ${p => p.theme.breakpoints.small}) {
  447. --corner-scale: 0.5;
  448. }
  449. `;
  450. const StyledStepper = styled(Stepper)`
  451. justify-self: center;
  452. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  453. display: none;
  454. }
  455. `;
  456. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  457. animate: MotionProps['animate'];
  458. className?: string;
  459. }
  460. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  461. <motion.div
  462. className={className}
  463. animate={animate}
  464. transition={testableTransition()}
  465. variants={{
  466. initial: {opacity: 0, visibility: 'hidden'},
  467. visible: {
  468. opacity: 1,
  469. visibility: 'visible',
  470. transition: testableTransition({delay: 1}),
  471. },
  472. hidden: {
  473. opacity: 0,
  474. transitionEnd: {
  475. visibility: 'hidden',
  476. },
  477. },
  478. }}
  479. >
  480. <Button {...props} icon={<IconArrow direction="left" />} priority="link">
  481. {t('Back')}
  482. </Button>
  483. </motion.div>
  484. ))`
  485. position: absolute;
  486. top: 40px;
  487. left: 20px;
  488. button {
  489. font-size: ${p => p.theme.fontSizeSmall};
  490. }
  491. `;
  492. const SkipOnboardingLink = styled(Link)`
  493. margin: auto ${space(4)};
  494. `;
  495. const UpsellWrapper = styled('div')`
  496. grid-column: 3;
  497. margin-left: auto;
  498. `;
  499. const OnboardingWrapper = styled('main')`
  500. flex-grow: 1;
  501. display: flex;
  502. flex-direction: column;
  503. `;
  504. export default Onboarding;