onboarding.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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(api, organization.slug, recentCreatedProject.slug);
  172. onboardingContext.setData({
  173. ...onboardingContext.data,
  174. projects: newProjects,
  175. });
  176. } catch (error) {
  177. handleXhrErrorResponse(t('Unable to delete project in onboarding'))(error);
  178. // we don't give the user any feedback regarding this error as this shall be silent
  179. }
  180. }, [api, organization.slug, recentCreatedProject?.slug, onboardingContext]);
  181. const handleGoBack = useCallback(
  182. (goToStepIndex?: number) => {
  183. if (!stepObj) {
  184. return;
  185. }
  186. const previousStep = defined(goToStepIndex)
  187. ? onboardingSteps[goToStepIndex]
  188. : onboardingSteps[stepIndex - 1];
  189. if (!previousStep) {
  190. return;
  191. }
  192. if (stepObj.cornerVariant !== previousStep.cornerVariant) {
  193. cornerVariantControl.start('none');
  194. }
  195. trackAnalytics('onboarding.back_button_clicked', {
  196. organization,
  197. from: onboardingSteps[stepIndex].id,
  198. to: previousStep.id,
  199. });
  200. // from selected platform to welcome
  201. if (onboardingSteps[stepIndex].id === 'select-platform') {
  202. onboardingContext.setData({...onboardingContext.data, selectedSDK: undefined});
  203. props.router.replace(
  204. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  205. );
  206. return;
  207. }
  208. // from setup docs to selected platform
  209. if (onboardingSteps[stepIndex].id === 'setup-docs' && shallProjectBeDeleted) {
  210. deleteRecentCreatedProject();
  211. }
  212. props.router.replace(
  213. normalizeUrl(`/onboarding/${organization.slug}/${previousStep.id}/`)
  214. );
  215. },
  216. [
  217. stepObj,
  218. stepIndex,
  219. onboardingSteps,
  220. organization,
  221. cornerVariantControl,
  222. props.router,
  223. onboardingContext,
  224. shallProjectBeDeleted,
  225. deleteRecentCreatedProject,
  226. ]
  227. );
  228. const genSkipOnboardingLink = () => {
  229. const source = `targeted-onboarding-${stepId}`;
  230. return (
  231. <SkipOnboardingLink
  232. onClick={() => {
  233. trackAnalytics('growth.onboarding_clicked_skip', {
  234. organization,
  235. source,
  236. });
  237. onboardingContext.setData({...onboardingContext.data, selectedSDK: undefined});
  238. }}
  239. to={normalizeUrl(
  240. `/organizations/${organization.slug}/issues/?referrer=onboarding-skip`
  241. )}
  242. >
  243. {t('Skip Onboarding')}
  244. </SkipOnboardingLink>
  245. );
  246. };
  247. if (!stepObj || stepIndex === -1) {
  248. return (
  249. <Redirect
  250. to={normalizeUrl(`/onboarding/${organization.slug}/${onboardingSteps[0].id}/`)}
  251. />
  252. );
  253. }
  254. const goBackDeletionAlertModalProps: OpenConfirmOptions = {
  255. message: t(
  256. "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?"
  257. ),
  258. priority: 'danger',
  259. confirmText: t("Yes I'm sure. Take me back"),
  260. onConfirm: handleGoBack,
  261. };
  262. return (
  263. <OnboardingWrapper data-test-id="targeted-onboarding">
  264. <SentryDocumentTitle title={stepObj.title} />
  265. <Header>
  266. <LogoSvg />
  267. {stepIndex !== -1 && (
  268. <StyledStepper
  269. numSteps={onboardingSteps.length}
  270. currentStepIndex={stepIndex}
  271. onClick={i => {
  272. if (i < stepIndex && shallProjectBeDeleted) {
  273. openConfirmModal({
  274. ...goBackDeletionAlertModalProps,
  275. onConfirm: () => handleGoBack(i),
  276. });
  277. return;
  278. }
  279. goToStep(onboardingSteps[i]);
  280. }}
  281. />
  282. )}
  283. <UpsellWrapper>
  284. <Hook
  285. name="onboarding:targeted-onboarding-header"
  286. source="targeted-onboarding"
  287. />
  288. </UpsellWrapper>
  289. </Header>
  290. <Container hasFooter={containerHasFooter} heartbeatFooter={heartbeatFooter}>
  291. <Confirm bypass={!shallProjectBeDeleted} {...goBackDeletionAlertModalProps}>
  292. <Back animate={stepIndex > 0 ? 'visible' : 'hidden'} />
  293. </Confirm>
  294. <AnimatePresence exitBeforeEnter onExitComplete={updateAnimationState}>
  295. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  296. {stepObj.Component && (
  297. <stepObj.Component
  298. active
  299. data-test-id={`onboarding-step-${stepObj.id}`}
  300. stepIndex={stepIndex}
  301. onComplete={platform => {
  302. if (stepObj) {
  303. goNextStep(stepObj, platform);
  304. }
  305. }}
  306. orgId={organization.slug}
  307. search={props.location.search}
  308. route={props.route}
  309. router={props.router}
  310. location={props.location}
  311. selectedProjectSlug={selectedProjectSlug}
  312. {...{
  313. genSkipOnboardingLink,
  314. }}
  315. />
  316. )}
  317. </OnboardingStep>
  318. </AnimatePresence>
  319. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  320. </Container>
  321. </OnboardingWrapper>
  322. );
  323. }
  324. const Container = styled('div')<{hasFooter: boolean; heartbeatFooter: boolean}>`
  325. flex-grow: 1;
  326. display: flex;
  327. flex-direction: column;
  328. position: relative;
  329. background: ${p => p.theme.background};
  330. padding: ${p =>
  331. p.heartbeatFooter ? `120px ${space(3)} 0 ${space(3)}` : `120px ${space(3)}`};
  332. width: 100%;
  333. margin: 0 auto;
  334. padding-bottom: ${p => p.hasFooter && '72px'};
  335. margin-bottom: ${p => p.hasFooter && '72px'};
  336. `;
  337. const Header = styled('header')`
  338. background: ${p => p.theme.background};
  339. padding-left: ${space(4)};
  340. padding-right: ${space(4)};
  341. position: sticky;
  342. height: 80px;
  343. align-items: center;
  344. top: 0;
  345. z-index: 100;
  346. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  347. display: grid;
  348. grid-template-columns: 1fr 1fr 1fr;
  349. justify-items: stretch;
  350. `;
  351. const LogoSvg = styled(LogoSentry)`
  352. width: 130px;
  353. height: 30px;
  354. color: ${p => p.theme.textColor};
  355. `;
  356. const OnboardingStep = styled(motion.div)`
  357. flex-grow: 1;
  358. display: flex;
  359. flex-direction: column;
  360. `;
  361. OnboardingStep.defaultProps = {
  362. initial: 'initial',
  363. animate: 'animate',
  364. exit: 'exit',
  365. variants: {animate: {}},
  366. transition: testableTransition({
  367. staggerChildren: 0.2,
  368. }),
  369. };
  370. const Sidebar = styled(motion.div)`
  371. width: 850px;
  372. display: flex;
  373. flex-direction: column;
  374. align-items: center;
  375. `;
  376. Sidebar.defaultProps = {
  377. initial: 'initial',
  378. animate: 'animate',
  379. exit: 'exit',
  380. variants: {animate: {}},
  381. transition: testableTransition({
  382. staggerChildren: 0.2,
  383. }),
  384. };
  385. const AdaptivePageCorners = styled(PageCorners)`
  386. --corner-scale: 1;
  387. @media (max-width: ${p => p.theme.breakpoints.small}) {
  388. --corner-scale: 0.5;
  389. }
  390. `;
  391. const StyledStepper = styled(Stepper)`
  392. justify-self: center;
  393. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  394. display: none;
  395. }
  396. `;
  397. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  398. animate: MotionProps['animate'];
  399. className?: string;
  400. }
  401. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  402. <motion.div
  403. className={className}
  404. animate={animate}
  405. transition={testableTransition()}
  406. variants={{
  407. initial: {opacity: 0, visibility: 'hidden'},
  408. visible: {
  409. opacity: 1,
  410. visibility: 'visible',
  411. transition: testableTransition({delay: 1}),
  412. },
  413. hidden: {
  414. opacity: 0,
  415. transitionEnd: {
  416. visibility: 'hidden',
  417. },
  418. },
  419. }}
  420. >
  421. <Button {...props} icon={<IconArrow direction="left" size="sm" />} priority="link">
  422. {t('Back')}
  423. </Button>
  424. </motion.div>
  425. ))`
  426. position: absolute;
  427. top: 40px;
  428. left: 20px;
  429. button {
  430. font-size: ${p => p.theme.fontSizeSmall};
  431. }
  432. `;
  433. const SkipOnboardingLink = styled(Link)`
  434. margin: auto ${space(4)};
  435. `;
  436. const UpsellWrapper = styled('div')`
  437. grid-column: 3;
  438. margin-left: auto;
  439. `;
  440. const OnboardingWrapper = styled('main')`
  441. flex-grow: 1;
  442. display: flex;
  443. flex-direction: column;
  444. `;
  445. export default Onboarding;