onboarding.tsx 17 KB

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