onboarding.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. }}
  292. to={normalizeUrl(
  293. `/organizations/${organization.slug}/issues/?referrer=onboarding-skip`
  294. )}
  295. >
  296. {t('Skip Onboarding')}
  297. </SkipOnboardingLink>
  298. );
  299. };
  300. // Redirect to the first step if we end up in an invalid state
  301. const isInvalidDocsStep = stepId === 'setup-docs' && !projectSlug;
  302. if (!stepObj || stepIndex === -1 || isInvalidDocsStep) {
  303. return (
  304. <Redirect
  305. to={normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[0]!.id}/`)}
  306. />
  307. );
  308. }
  309. const goBackDeletionAlertModalProps: OpenConfirmOptions = {
  310. message: t(
  311. "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?"
  312. ),
  313. priority: 'danger',
  314. confirmText: t("Yes I'm sure"),
  315. onConfirm: handleGoBack,
  316. onClose: () => {
  317. if (!recentCreatedProject) {
  318. return;
  319. }
  320. trackAnalytics('onboarding.data_removal_modal_dismissed', {
  321. organization,
  322. platform: recentCreatedProject.slug,
  323. project_id: recentCreatedProject.id,
  324. });
  325. },
  326. onRender: () => {
  327. if (!recentCreatedProject) {
  328. return;
  329. }
  330. trackAnalytics('onboarding.data_removal_modal_rendered', {
  331. organization,
  332. platform: recentCreatedProject.slug,
  333. project_id: recentCreatedProject.id,
  334. });
  335. },
  336. };
  337. return (
  338. <OnboardingWrapper data-test-id="targeted-onboarding">
  339. <SentryDocumentTitle title={stepObj.title} />
  340. <Header>
  341. <LogoSvg />
  342. {stepIndex !== -1 && (
  343. <StyledStepper
  344. numSteps={onboardingSteps.length}
  345. currentStepIndex={stepIndex}
  346. onClick={i => {
  347. if ((i as number) < stepIndex && shallProjectBeDeleted) {
  348. openConfirmModal({
  349. ...goBackDeletionAlertModalProps,
  350. // @ts-expect-error TS(2345): Argument of type 'number | MouseEvent<HTMLDivEleme... Remove this comment to see the full error message
  351. onConfirm: () => handleGoBack(i),
  352. });
  353. return;
  354. }
  355. // @ts-expect-error TS(2538): Type 'MouseEvent<HTMLDivElement, MouseEvent>' cann... Remove this comment to see the full error message
  356. goToStep(onboardingSteps[i]);
  357. }}
  358. />
  359. )}
  360. <UpsellWrapper>
  361. <Hook
  362. name="onboarding:targeted-onboarding-header"
  363. source="targeted-onboarding"
  364. />
  365. </UpsellWrapper>
  366. </Header>
  367. <Container hasFooter={containerHasFooter}>
  368. <Confirm bypass={!shallProjectBeDeleted} {...goBackDeletionAlertModalProps}>
  369. <Back animate={stepIndex > 0 ? 'visible' : 'hidden'} />
  370. </Confirm>
  371. <AnimatePresence mode="wait" onExitComplete={updateAnimationState}>
  372. <OnboardingStep
  373. initial="initial"
  374. animate="animate"
  375. exit="exit"
  376. variants={{animate: {}}}
  377. transition={testableTransition({
  378. staggerChildren: 0.2,
  379. })}
  380. key={stepObj.id}
  381. data-test-id={`onboarding-step-${stepObj.id}`}
  382. >
  383. {stepObj.Component && (
  384. <stepObj.Component
  385. active
  386. data-test-id={`onboarding-step-${stepObj.id}`}
  387. stepIndex={stepIndex}
  388. onComplete={platform => {
  389. if (stepObj) {
  390. goNextStep(stepObj, platform);
  391. }
  392. }}
  393. orgId={organization.slug}
  394. search={props.location.search}
  395. route={props.route}
  396. router={props.router}
  397. location={props.location}
  398. recentCreatedProject={recentCreatedProject}
  399. {...{
  400. genSkipOnboardingLink,
  401. }}
  402. />
  403. )}
  404. </OnboardingStep>
  405. </AnimatePresence>
  406. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  407. </Container>
  408. </OnboardingWrapper>
  409. );
  410. }
  411. const Container = styled('div')<{hasFooter: boolean}>`
  412. flex-grow: 1;
  413. display: flex;
  414. flex-direction: column;
  415. position: relative;
  416. background: ${p => p.theme.background};
  417. padding: 120px ${space(3)};
  418. width: 100%;
  419. margin: 0 auto;
  420. padding-bottom: ${p => p.hasFooter && '72px'};
  421. margin-bottom: ${p => p.hasFooter && '72px'};
  422. `;
  423. const Header = styled('header')`
  424. background: ${p => p.theme.background};
  425. padding-left: ${space(4)};
  426. padding-right: ${space(4)};
  427. position: sticky;
  428. height: 80px;
  429. align-items: center;
  430. top: 0;
  431. z-index: 100;
  432. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  433. display: grid;
  434. grid-template-columns: 1fr 1fr 1fr;
  435. justify-items: stretch;
  436. `;
  437. const LogoSvg = styled(LogoSentry)`
  438. width: 130px;
  439. height: 30px;
  440. color: ${p => p.theme.textColor};
  441. `;
  442. const OnboardingStep = styled(motion.div)`
  443. flex-grow: 1;
  444. display: flex;
  445. flex-direction: column;
  446. `;
  447. const AdaptivePageCorners = styled(PageCorners)`
  448. --corner-scale: 1;
  449. @media (max-width: ${p => p.theme.breakpoints.small}) {
  450. --corner-scale: 0.5;
  451. }
  452. `;
  453. const StyledStepper = styled(Stepper)`
  454. justify-self: center;
  455. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  456. display: none;
  457. }
  458. `;
  459. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  460. animate: MotionProps['animate'];
  461. className?: string;
  462. }
  463. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  464. <motion.div
  465. className={className}
  466. animate={animate}
  467. transition={testableTransition()}
  468. variants={{
  469. initial: {opacity: 0, visibility: 'hidden'},
  470. visible: {
  471. opacity: 1,
  472. visibility: 'visible',
  473. transition: testableTransition({delay: 1}),
  474. },
  475. hidden: {
  476. opacity: 0,
  477. transitionEnd: {
  478. visibility: 'hidden',
  479. },
  480. },
  481. }}
  482. >
  483. <Button {...props} icon={<IconArrow direction="left" />} priority="link">
  484. {t('Back')}
  485. </Button>
  486. </motion.div>
  487. ))`
  488. position: absolute;
  489. top: 40px;
  490. left: 20px;
  491. button {
  492. font-size: ${p => p.theme.fontSizeSmall};
  493. }
  494. `;
  495. const SkipOnboardingLink = styled(Link)`
  496. margin: auto ${space(4)};
  497. `;
  498. const UpsellWrapper = styled('div')`
  499. grid-column: 3;
  500. margin-left: auto;
  501. `;
  502. const OnboardingWrapper = styled('main')`
  503. flex-grow: 1;
  504. display: flex;
  505. flex-direction: column;
  506. `;
  507. export default Onboarding;