relocation.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import {useCallback, 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 type {ButtonProps} from 'sentry/components/button';
  6. import {Button} from 'sentry/components/button';
  7. import LoadingError from 'sentry/components/loadingError';
  8. import LoadingIndicator from 'sentry/components/loadingIndicator';
  9. import LogoSentry from 'sentry/components/logoSentry';
  10. import Redirect from 'sentry/components/redirect';
  11. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  12. import {IconArrow} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import ConfigStore from 'sentry/stores/configStore';
  15. import {space} from 'sentry/styles/space';
  16. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import testableTransition from 'sentry/utils/testableTransition';
  19. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  20. import useApi from 'sentry/utils/useApi';
  21. import {useSessionStorage} from 'sentry/utils/useSessionStorage';
  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. // @ts-expect-error TS(2538): Type 'MouseEvent<HTMLDivElement, MouseEvent>' cann... Remove this comment to see the full error message
  229. goToStep(onboardingSteps[i]);
  230. }}
  231. />
  232. )}
  233. </Header>
  234. );
  235. const backButtonView =
  236. stepId === 'in-progress' ? null : (
  237. <Back
  238. onClick={() => goToStep(onboardingSteps[stepIndex - 1]!)}
  239. animate={stepIndex > 0 ? 'visible' : 'hidden'}
  240. />
  241. );
  242. const isLoading =
  243. existingRelocationState !== LoadingState.FETCHED ||
  244. publicKeysState !== LoadingState.FETCHED;
  245. const contentView = isLoading ? (
  246. <LoadingIndicator />
  247. ) : (
  248. <AnimatePresence mode="wait" onExitComplete={updateAnimationState}>
  249. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  250. {stepObj.Component && (
  251. <stepObj.Component
  252. active
  253. data-test-id={`onboarding-step-${stepObj.id}`}
  254. existingRelocationUUID={existingRelocation}
  255. stepIndex={stepIndex}
  256. onUpdateRelocationState={({
  257. orgSlugs,
  258. regionUrl,
  259. promoCode,
  260. }: MaybeUpdateRelocationState) => {
  261. setRelocationState({
  262. orgSlugs: orgSlugs === undefined ? relocationState.orgSlugs : orgSlugs,
  263. regionUrl:
  264. regionUrl === undefined ? relocationState.regionUrl : regionUrl,
  265. promoCode:
  266. promoCode === undefined ? relocationState.promoCode : promoCode,
  267. });
  268. }}
  269. onComplete={(uuid?) => {
  270. if (uuid) {
  271. setExistingRelocation(uuid);
  272. }
  273. if (stepObj) {
  274. goNextStep(stepObj);
  275. }
  276. }}
  277. publicKeys={publicKeys}
  278. relocationState={relocationState}
  279. route={props.route}
  280. router={props.router}
  281. location={props.location}
  282. />
  283. )}
  284. </OnboardingStep>
  285. </AnimatePresence>
  286. );
  287. const hasErr =
  288. existingRelocationState === LoadingState.ERROR ||
  289. publicKeysState === LoadingState.ERROR;
  290. const errView = hasErr ? (
  291. <LoadingError
  292. data-test-id="loading-error"
  293. message={t('Failed to load information from server - check your connection?')}
  294. onRetry={() => {
  295. if (existingRelocationState === LoadingState.ERROR) {
  296. fetchExistingRelocation();
  297. }
  298. if (publicKeysState === LoadingState.ERROR) {
  299. fetchPublicKeys();
  300. }
  301. }}
  302. />
  303. ) : null;
  304. return (
  305. <OnboardingWrapper data-test-id="relocation-onboarding">
  306. <SentryDocumentTitle title={stepObj.title} />
  307. {headerView}
  308. <Container>
  309. {backButtonView}
  310. {contentView}
  311. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  312. {errView}
  313. </Container>
  314. </OnboardingWrapper>
  315. );
  316. }
  317. const Container = styled('div')`
  318. flex-grow: 1;
  319. display: flex;
  320. flex-direction: column;
  321. position: relative;
  322. background: #faf9fb;
  323. padding: 120px ${space(3)};
  324. width: 100%;
  325. margin: 0 auto;
  326. p,
  327. a {
  328. line-height: 1.6;
  329. }
  330. `;
  331. const Header = styled('header')`
  332. background: ${p => p.theme.background};
  333. padding-left: ${space(4)};
  334. padding-right: ${space(4)};
  335. position: sticky;
  336. height: 80px;
  337. align-items: center;
  338. top: 0;
  339. z-index: 100;
  340. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  341. display: grid;
  342. grid-template-columns: 1fr 1fr 1fr;
  343. justify-items: stretch;
  344. `;
  345. const LogoSvg = styled(LogoSentry)`
  346. width: 130px;
  347. height: 30px;
  348. color: ${p => p.theme.textColor};
  349. `;
  350. const OnboardingStep = styled((props: React.ComponentProps<typeof motion.div>) => (
  351. <motion.div
  352. initial="initial"
  353. animate="animate"
  354. exit="exit"
  355. variants={{animate: {}}}
  356. transition={testableTransition({
  357. staggerChildren: 0.2,
  358. })}
  359. {...props}
  360. />
  361. ))`
  362. flex-grow: 1;
  363. display: flex;
  364. flex-direction: column;
  365. `;
  366. const AdaptivePageCorners = styled(PageCorners)`
  367. --corner-scale: 1;
  368. @media (max-width: ${p => p.theme.breakpoints.small}) {
  369. --corner-scale: 0.5;
  370. }
  371. `;
  372. const StyledStepper = styled(Stepper)`
  373. justify-self: center;
  374. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  375. display: none;
  376. }
  377. `;
  378. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  379. animate: MotionProps['animate'];
  380. className?: string;
  381. }
  382. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  383. <motion.div
  384. className={className}
  385. animate={animate}
  386. transition={testableTransition()}
  387. variants={{
  388. initial: {opacity: 0, visibility: 'hidden'},
  389. visible: {
  390. opacity: 1,
  391. visibility: 'visible',
  392. transition: testableTransition({delay: 1}),
  393. },
  394. hidden: {
  395. opacity: 0,
  396. transitionEnd: {
  397. visibility: 'hidden',
  398. },
  399. },
  400. }}
  401. >
  402. <Button {...props} icon={<IconArrow direction="left" />} priority="link">
  403. {t('Back')}
  404. </Button>
  405. </motion.div>
  406. ))`
  407. position: absolute;
  408. top: 40px;
  409. left: 20px;
  410. button {
  411. font-size: ${p => p.theme.fontSizeSmall};
  412. }
  413. `;
  414. const OnboardingWrapper = styled('main')`
  415. flex-grow: 1;
  416. display: flex;
  417. flex-direction: column;
  418. `;
  419. export default RelocationOnboarding;