relocation.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import {useCallback, useEffect, useRef, useState} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import type {MotionProps} from 'framer-motion';
  5. import {AnimatePresence, motion, useAnimation} from 'framer-motion';
  6. import type {ButtonProps} from 'sentry/components/button';
  7. import {Button} from 'sentry/components/button';
  8. import LoadingError from 'sentry/components/loadingError';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import LogoSentry from 'sentry/components/logoSentry';
  11. import Redirect from 'sentry/components/redirect';
  12. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  13. import {IconArrow} from 'sentry/icons';
  14. import {t} from 'sentry/locale';
  15. import ConfigStore from 'sentry/stores/configStore';
  16. import {space} from 'sentry/styles/space';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import testableTransition from 'sentry/utils/testableTransition';
  19. import useApi from 'sentry/utils/useApi';
  20. import {useSessionStorage} from 'sentry/utils/useSessionStorage';
  21. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  22. import PageCorners from 'sentry/views/onboarding/components/pageCorners';
  23. import Stepper from 'sentry/views/onboarding/components/stepper';
  24. import EncryptBackup from './encryptBackup';
  25. import GetStarted from './getStarted';
  26. import InProgress from './inProgress';
  27. import PublicKey from './publicKey';
  28. import type {MaybeUpdateRelocationState, RelocationState, StepDescriptor} from './types';
  29. import UploadBackup from './uploadBackup';
  30. type RouteParams = {
  31. step: string;
  32. };
  33. type Props = RouteComponentProps<RouteParams, {}>;
  34. function getRelocationOnboardingSteps(): StepDescriptor[] {
  35. return [
  36. {
  37. id: 'get-started',
  38. title: t('Get Started'),
  39. Component: GetStarted,
  40. cornerVariant: 'top-left',
  41. },
  42. {
  43. id: 'public-key',
  44. title: t("Save Sentry's public key to your machine"),
  45. Component: PublicKey,
  46. cornerVariant: 'top-left',
  47. },
  48. {
  49. id: 'encrypt-backup',
  50. title: t('Encrypt backup'),
  51. Component: EncryptBackup,
  52. cornerVariant: 'top-left',
  53. },
  54. {
  55. id: 'upload-backup',
  56. title: t('Upload backup'),
  57. Component: UploadBackup,
  58. cornerVariant: 'top-left',
  59. },
  60. {
  61. id: 'in-progress',
  62. title: t('Your relocation is in progress'),
  63. Component: InProgress,
  64. cornerVariant: 'top-left',
  65. },
  66. ];
  67. }
  68. enum LoadingState {
  69. FETCHED = 0,
  70. FETCHING = 1,
  71. ERROR = 2,
  72. }
  73. function RelocationOnboarding(props: Props) {
  74. const {
  75. params: {step: stepId},
  76. } = props;
  77. const onboardingSteps = getRelocationOnboardingSteps();
  78. const stepObj = onboardingSteps.find(({id}) => stepId === id);
  79. const stepIndex = onboardingSteps.findIndex(({id}) => stepId === id);
  80. const api = useApi();
  81. const regions = ConfigStore.get('regions');
  82. const [existingRelocationState, setExistingRelocationState] = useState(
  83. LoadingState.FETCHING
  84. );
  85. const [existingRelocation, setExistingRelocation] = useState('');
  86. const [publicKeys, setPublicKeys] = useState(new Map<string, string>());
  87. const [publicKeysState, setPublicKeysState] = useState(LoadingState.FETCHING);
  88. const [relocationState, setRelocationState] = useSessionStorage<RelocationState>(
  89. 'relocationOnboarding',
  90. {
  91. orgSlugs: '',
  92. regionUrl: '',
  93. promoCode: '',
  94. }
  95. );
  96. const fetchExistingRelocation = useCallback(() => {
  97. setExistingRelocationState(LoadingState.FETCHING);
  98. return Promise.all(
  99. regions.map(region =>
  100. api.requestPromise(`/relocations/`, {
  101. method: 'GET',
  102. host: region.url,
  103. })
  104. )
  105. )
  106. .then(responses => {
  107. const response = responses.flat(1);
  108. response.sort((a, b) => {
  109. return (
  110. new Date(a.dateAdded || 0).getTime() - new Date(b.dateAdded || 0).getTime()
  111. );
  112. });
  113. const existingRelocationUUID =
  114. response.find(
  115. candidate =>
  116. candidate.status === 'IN_PROGRESS' || candidate.status === 'PAUSE'
  117. )?.uuid || '';
  118. // The user has a relocation already in flight - whatever page they asked for, show them the
  119. // progress of that relocation instead, since they can only have one relocation in flight at
  120. // a time.
  121. if (existingRelocationUUID !== '' && stepId !== 'in-progress') {
  122. browserHistory.push('/relocation/in-progress/');
  123. }
  124. // The user does not have a relocation in-flight, but tried to view the in progress screen.
  125. // Since we have nothing to show them, take them back to the start of the flow.
  126. if (existingRelocationUUID === '' && stepId === 'in-progress') {
  127. browserHistory.push('/relocation/get-started/');
  128. }
  129. // The user tried to view a later step, but at least one bit of required data was missing in
  130. // their local storage. Take them back to the first screen.
  131. const {orgSlugs, regionUrl} = relocationState;
  132. if (stepId !== 'get-started' && (!orgSlugs || !regionUrl)) {
  133. browserHistory.push('/relocation/get-started/');
  134. }
  135. setExistingRelocation(existingRelocationUUID);
  136. setExistingRelocationState(LoadingState.FETCHED);
  137. })
  138. .catch(_error => {
  139. setExistingRelocation('');
  140. setExistingRelocationState(LoadingState.ERROR);
  141. });
  142. }, [api, regions, relocationState, stepId]);
  143. useEffect(() => {
  144. fetchExistingRelocation();
  145. // eslint-disable-next-line react-hooks/exhaustive-deps
  146. }, []);
  147. const fetchPublicKeys = useCallback(() => {
  148. setPublicKeysState(LoadingState.FETCHING);
  149. return Promise.all(
  150. regions.map(region =>
  151. api.requestPromise(`/publickeys/relocations/`, {
  152. method: 'GET',
  153. host: region.url,
  154. })
  155. )
  156. )
  157. .then(responses => {
  158. setPublicKeys(
  159. new Map<string, string>(
  160. regions.map((region, index) => [region.url, responses[index].public_key])
  161. )
  162. );
  163. setPublicKeysState(LoadingState.FETCHED);
  164. })
  165. .catch(_error => {
  166. setPublicKeys(new Map<string, string>());
  167. setPublicKeysState(LoadingState.ERROR);
  168. });
  169. }, [api, regions]);
  170. useEffect(() => {
  171. fetchPublicKeys();
  172. // eslint-disable-next-line react-hooks/exhaustive-deps
  173. }, []);
  174. const cornerVariantTimeoutRed = useRef<number | undefined>(undefined);
  175. useEffect(() => {
  176. return () => {
  177. window.clearTimeout(cornerVariantTimeoutRed.current);
  178. };
  179. }, []);
  180. const cornerVariantControl = useAnimation();
  181. const updateCornerVariant = () => {
  182. // TODO(getsentry/team-ospo#214): Find a better way to delay the corner animation.
  183. window.clearTimeout(cornerVariantTimeoutRed.current);
  184. cornerVariantTimeoutRed.current = window.setTimeout(
  185. () => cornerVariantControl.start(stepIndex === 0 ? 'top-right' : 'top-left'),
  186. 1000
  187. );
  188. };
  189. useEffect(updateCornerVariant, [stepIndex, cornerVariantControl]);
  190. // Called onExitComplete
  191. const updateAnimationState = () => {
  192. if (!stepObj) {
  193. return;
  194. }
  195. };
  196. const goToStep = (step: StepDescriptor) => {
  197. if (!stepObj) {
  198. return;
  199. }
  200. if (step.cornerVariant !== stepObj.cornerVariant) {
  201. cornerVariantControl.start('none');
  202. }
  203. props.router.push(normalizeUrl(`/relocation/${step.id}/`));
  204. };
  205. const goNextStep = useCallback(
  206. (step: StepDescriptor) => {
  207. const currentStepIndex = onboardingSteps.findIndex(s => s.id === step.id);
  208. const nextStep = onboardingSteps[currentStepIndex + 1];
  209. if (step.cornerVariant !== nextStep.cornerVariant) {
  210. cornerVariantControl.start('none');
  211. }
  212. props.router.push(normalizeUrl(`/relocation/${nextStep.id}/`));
  213. },
  214. [onboardingSteps, cornerVariantControl, props.router]
  215. );
  216. if (!stepObj || stepIndex === -1) {
  217. return <Redirect to={normalizeUrl(`/relocation/${onboardingSteps[0].id}/`)} />;
  218. }
  219. const headerView =
  220. stepId === 'in-progress' ? null : (
  221. <Header>
  222. <LogoSvg />
  223. {stepIndex !== -1 && (
  224. <StyledStepper
  225. numSteps={onboardingSteps.length}
  226. currentStepIndex={stepIndex}
  227. onClick={i => {
  228. goToStep(onboardingSteps[i]);
  229. }}
  230. />
  231. )}
  232. </Header>
  233. );
  234. const backButtonView =
  235. stepId === 'in-progress' ? null : (
  236. <Back
  237. onClick={() => goToStep(onboardingSteps[stepIndex - 1])}
  238. animate={stepIndex > 0 ? 'visible' : 'hidden'}
  239. />
  240. );
  241. const isLoading =
  242. existingRelocationState !== LoadingState.FETCHED ||
  243. publicKeysState !== LoadingState.FETCHED;
  244. const contentView = isLoading ? (
  245. <LoadingIndicator />
  246. ) : (
  247. <AnimatePresence mode="wait" onExitComplete={updateAnimationState}>
  248. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  249. {stepObj.Component && (
  250. <stepObj.Component
  251. active
  252. data-test-id={`onboarding-step-${stepObj.id}`}
  253. existingRelocationUUID={existingRelocation}
  254. stepIndex={stepIndex}
  255. onUpdateRelocationState={({
  256. orgSlugs,
  257. regionUrl,
  258. promoCode,
  259. }: MaybeUpdateRelocationState) => {
  260. setRelocationState({
  261. orgSlugs: orgSlugs === undefined ? relocationState.orgSlugs : orgSlugs,
  262. regionUrl:
  263. regionUrl === undefined ? relocationState.regionUrl : regionUrl,
  264. promoCode:
  265. promoCode === undefined ? relocationState.promoCode : promoCode,
  266. });
  267. }}
  268. onComplete={(uuid?) => {
  269. if (uuid) {
  270. setExistingRelocation(uuid);
  271. }
  272. if (stepObj) {
  273. goNextStep(stepObj);
  274. }
  275. }}
  276. publicKeys={publicKeys}
  277. relocationState={relocationState}
  278. route={props.route}
  279. router={props.router}
  280. location={props.location}
  281. />
  282. )}
  283. </OnboardingStep>
  284. </AnimatePresence>
  285. );
  286. const hasErr =
  287. existingRelocationState === LoadingState.ERROR ||
  288. publicKeysState === LoadingState.ERROR;
  289. const errView = hasErr ? (
  290. <LoadingError
  291. data-test-id="loading-error"
  292. message={t('Failed to load information from server - check your connection?')}
  293. onRetry={() => {
  294. if (existingRelocationState === LoadingState.ERROR) {
  295. fetchExistingRelocation();
  296. }
  297. if (publicKeysState === LoadingState.ERROR) {
  298. fetchPublicKeys();
  299. }
  300. }}
  301. />
  302. ) : null;
  303. return (
  304. <OnboardingWrapper data-test-id="relocation-onboarding">
  305. <SentryDocumentTitle title={stepObj.title} />
  306. {headerView}
  307. <Container>
  308. {backButtonView}
  309. {contentView}
  310. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  311. {errView}
  312. </Container>
  313. </OnboardingWrapper>
  314. );
  315. }
  316. const Container = styled('div')`
  317. flex-grow: 1;
  318. display: flex;
  319. flex-direction: column;
  320. position: relative;
  321. background: #faf9fb;
  322. padding: 120px ${space(3)};
  323. width: 100%;
  324. margin: 0 auto;
  325. p,
  326. a {
  327. line-height: 1.6;
  328. }
  329. `;
  330. const Header = styled('header')`
  331. background: ${p => p.theme.background};
  332. padding-left: ${space(4)};
  333. padding-right: ${space(4)};
  334. position: sticky;
  335. height: 80px;
  336. align-items: center;
  337. top: 0;
  338. z-index: 100;
  339. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  340. display: grid;
  341. grid-template-columns: 1fr 1fr 1fr;
  342. justify-items: stretch;
  343. `;
  344. const LogoSvg = styled(LogoSentry)`
  345. width: 130px;
  346. height: 30px;
  347. color: ${p => p.theme.textColor};
  348. `;
  349. const OnboardingStep = styled(motion.div)`
  350. flex-grow: 1;
  351. display: flex;
  352. flex-direction: column;
  353. `;
  354. OnboardingStep.defaultProps = {
  355. initial: 'initial',
  356. animate: 'animate',
  357. exit: 'exit',
  358. variants: {animate: {}},
  359. transition: testableTransition({
  360. staggerChildren: 0.2,
  361. }),
  362. };
  363. const AdaptivePageCorners = styled(PageCorners)`
  364. --corner-scale: 1;
  365. @media (max-width: ${p => p.theme.breakpoints.small}) {
  366. --corner-scale: 0.5;
  367. }
  368. `;
  369. const StyledStepper = styled(Stepper)`
  370. justify-self: center;
  371. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  372. display: none;
  373. }
  374. `;
  375. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  376. animate: MotionProps['animate'];
  377. className?: string;
  378. }
  379. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  380. <motion.div
  381. className={className}
  382. animate={animate}
  383. transition={testableTransition()}
  384. variants={{
  385. initial: {opacity: 0, visibility: 'hidden'},
  386. visible: {
  387. opacity: 1,
  388. visibility: 'visible',
  389. transition: testableTransition({delay: 1}),
  390. },
  391. hidden: {
  392. opacity: 0,
  393. transitionEnd: {
  394. visibility: 'hidden',
  395. },
  396. },
  397. }}
  398. >
  399. <Button {...props} icon={<IconArrow direction="left" />} priority="link">
  400. {t('Back')}
  401. </Button>
  402. </motion.div>
  403. ))`
  404. position: absolute;
  405. top: 40px;
  406. left: 20px;
  407. button {
  408. font-size: ${p => p.theme.fontSizeSmall};
  409. }
  410. `;
  411. const OnboardingWrapper = styled('main')`
  412. flex-grow: 1;
  413. display: flex;
  414. flex-direction: column;
  415. `;
  416. export default RelocationOnboarding;