onboarding.tsx 16 KB

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