relocation.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. import {useCallback, useEffect, useRef, useState} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import {browserHistory} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import type {MotionProps} from 'framer-motion';
  6. import {AnimatePresence, motion, useAnimation} from 'framer-motion';
  7. import type {ButtonProps} from 'sentry/components/button';
  8. import {Button} from 'sentry/components/button';
  9. import LoadingError from 'sentry/components/loadingError';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import LogoSentry from 'sentry/components/logoSentry';
  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 Redirect from 'sentry/utils/redirect';
  18. import testableTransition from 'sentry/utils/testableTransition';
  19. import useApi from 'sentry/utils/useApi';
  20. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  21. import PageCorners from 'sentry/views/onboarding/components/pageCorners';
  22. import Stepper from 'sentry/views/onboarding/components/stepper';
  23. import {RelocationOnboardingContextProvider} from 'sentry/views/relocation/relocationOnboardingContext';
  24. import EncryptBackup from './encryptBackup';
  25. import GetStarted from './getStarted';
  26. import InProgress from './inProgress';
  27. import PublicKey from './publicKey';
  28. import type {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,
  70. FETCHING,
  71. ERROR,
  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 [regionUrl, setRegionUrl] = useState('');
  83. const [existingRelocationState, setExistingRelocationState] = useState(
  84. LoadingState.FETCHING
  85. );
  86. const [existingRelocation, setExistingRelocation] = useState('');
  87. const [publicKeys, setPublicKeys] = useState(new Map<string, string>());
  88. const [publicKeysState, setPublicKeysState] = useState(LoadingState.FETCHING);
  89. const fetchExistingRelocation = useCallback(() => {
  90. setExistingRelocationState(LoadingState.FETCHING);
  91. return Promise.all(
  92. regions.map(region =>
  93. api.requestPromise(`/relocations/`, {
  94. method: 'GET',
  95. host: region.url,
  96. })
  97. )
  98. )
  99. .then(responses => {
  100. const response = responses.flat(1);
  101. response.sort((a, b) => {
  102. return (
  103. new Date(a.dateAdded || 0).getTime() - new Date(b.dateAdded || 0).getTime()
  104. );
  105. });
  106. const existingRelocationUUID =
  107. response.find(
  108. candidate =>
  109. candidate.status === 'IN_PROGRESS' || candidate.status === 'PAUSE'
  110. )?.uuid || '';
  111. setExistingRelocation(existingRelocationUUID);
  112. setExistingRelocationState(LoadingState.FETCHED);
  113. if (existingRelocationUUID !== '' && stepId !== 'in-progress') {
  114. browserHistory.push('/relocation/in-progress/');
  115. }
  116. if (existingRelocationUUID === '' && stepId === 'in-progress') {
  117. browserHistory.push('/relocation/get-started/');
  118. }
  119. })
  120. .catch(_error => {
  121. setExistingRelocation('');
  122. setExistingRelocationState(LoadingState.ERROR);
  123. });
  124. }, [api, regions, stepId]);
  125. useEffect(() => {
  126. fetchExistingRelocation();
  127. }, [fetchExistingRelocation]);
  128. const fetchPublicKeys = useCallback(() => {
  129. setPublicKeysState(LoadingState.FETCHING);
  130. return Promise.all(
  131. regions.map(region =>
  132. api.requestPromise(`/publickeys/relocations/`, {
  133. method: 'GET',
  134. host: region.url,
  135. })
  136. )
  137. )
  138. .then(responses => {
  139. setPublicKeys(
  140. new Map<string, string>(
  141. regions.map((region, index) => [region.url, responses[index].public_key])
  142. )
  143. );
  144. setPublicKeysState(LoadingState.FETCHED);
  145. })
  146. .catch(_error => {
  147. setPublicKeys(new Map<string, string>());
  148. setPublicKeysState(LoadingState.ERROR);
  149. });
  150. }, [api, regions]);
  151. useEffect(() => {
  152. fetchPublicKeys();
  153. }, [fetchPublicKeys]);
  154. const cornerVariantTimeoutRed = useRef<number | undefined>(undefined);
  155. useEffect(() => {
  156. return () => {
  157. window.clearTimeout(cornerVariantTimeoutRed.current);
  158. };
  159. }, []);
  160. const cornerVariantControl = useAnimation();
  161. const updateCornerVariant = () => {
  162. // TODO(getsentry/team-ospo#214): Find a better way to delay the corner animation.
  163. window.clearTimeout(cornerVariantTimeoutRed.current);
  164. cornerVariantTimeoutRed.current = window.setTimeout(
  165. () => cornerVariantControl.start(stepIndex === 0 ? 'top-right' : 'top-left'),
  166. 1000
  167. );
  168. };
  169. useEffect(updateCornerVariant, [stepIndex, cornerVariantControl]);
  170. // Called onExitComplete
  171. const updateAnimationState = () => {
  172. if (!stepObj) {
  173. return;
  174. }
  175. };
  176. const goToStep = (step: StepDescriptor) => {
  177. if (!stepObj) {
  178. return;
  179. }
  180. if (step.cornerVariant !== stepObj.cornerVariant) {
  181. cornerVariantControl.start('none');
  182. }
  183. props.router.push(normalizeUrl(`/relocation/${step.id}/`));
  184. };
  185. const goNextStep = useCallback(
  186. (step: StepDescriptor) => {
  187. const currentStepIndex = onboardingSteps.findIndex(s => s.id === step.id);
  188. const nextStep = onboardingSteps[currentStepIndex + 1];
  189. if (step.cornerVariant !== nextStep.cornerVariant) {
  190. cornerVariantControl.start('none');
  191. }
  192. props.router.push(normalizeUrl(`/relocation/${nextStep.id}/`));
  193. },
  194. [onboardingSteps, cornerVariantControl, props.router]
  195. );
  196. if (!stepObj || stepIndex === -1) {
  197. return <Redirect to={normalizeUrl(`/relocation/${onboardingSteps[0].id}/`)} />;
  198. }
  199. const headerView =
  200. stepId === 'in-progress' ? null : (
  201. <Header>
  202. <LogoSvg />
  203. {stepIndex !== -1 && (
  204. <StyledStepper
  205. numSteps={onboardingSteps.length}
  206. currentStepIndex={stepIndex}
  207. onClick={i => {
  208. goToStep(onboardingSteps[i]);
  209. }}
  210. />
  211. )}
  212. </Header>
  213. );
  214. const backButtonView =
  215. stepId === 'in-progress' ? null : (
  216. <Back
  217. onClick={() => goToStep(onboardingSteps[stepIndex - 1])}
  218. animate={stepIndex > 0 ? 'visible' : 'hidden'}
  219. />
  220. );
  221. const isLoading =
  222. existingRelocationState !== LoadingState.FETCHED ||
  223. publicKeysState !== LoadingState.FETCHED;
  224. const contentView = isLoading ? (
  225. <LoadingIndicator />
  226. ) : (
  227. <AnimatePresence exitBeforeEnter onExitComplete={updateAnimationState}>
  228. <OnboardingStep key={stepObj.id} data-test-id={`onboarding-step-${stepObj.id}`}>
  229. {stepObj.Component && (
  230. <stepObj.Component
  231. active
  232. data-test-id={`onboarding-step-${stepObj.id}`}
  233. existingRelocationUUID={existingRelocation}
  234. stepIndex={stepIndex}
  235. onChangeRegionUrl={(regUrl?) => {
  236. if (regUrl) {
  237. setRegionUrl(regUrl);
  238. }
  239. }}
  240. onComplete={(uuid?) => {
  241. if (uuid) {
  242. setExistingRelocation(uuid);
  243. }
  244. if (stepObj) {
  245. goNextStep(stepObj);
  246. }
  247. }}
  248. publicKeys={publicKeys}
  249. regionUrl={regionUrl}
  250. route={props.route}
  251. router={props.router}
  252. location={props.location}
  253. />
  254. )}
  255. </OnboardingStep>
  256. </AnimatePresence>
  257. );
  258. const hasErr =
  259. existingRelocationState === LoadingState.ERROR ||
  260. publicKeysState === LoadingState.ERROR;
  261. const errView = hasErr ? (
  262. <LoadingError
  263. data-test-id="loading-error"
  264. message={t('Failed to load information from server - check your connection?')}
  265. onRetry={() => {
  266. if (existingRelocationState === LoadingState.ERROR) {
  267. fetchExistingRelocation();
  268. }
  269. if (publicKeysState === LoadingState.ERROR) {
  270. fetchPublicKeys();
  271. }
  272. }}
  273. />
  274. ) : null;
  275. return (
  276. <OnboardingWrapper data-test-id="relocation-onboarding">
  277. <RelocationOnboardingContextProvider>
  278. <SentryDocumentTitle title={stepObj.title} />
  279. {headerView}
  280. <Container>
  281. {backButtonView}
  282. {contentView}
  283. <AdaptivePageCorners animateVariant={cornerVariantControl} />
  284. {errView}
  285. </Container>
  286. </RelocationOnboardingContextProvider>
  287. </OnboardingWrapper>
  288. );
  289. }
  290. const Container = styled('div')`
  291. flex-grow: 1;
  292. display: flex;
  293. flex-direction: column;
  294. position: relative;
  295. background: #faf9fb;
  296. padding: 120px ${space(3)};
  297. width: 100%;
  298. margin: 0 auto;
  299. `;
  300. const Header = styled('header')`
  301. background: ${p => p.theme.background};
  302. padding-left: ${space(4)};
  303. padding-right: ${space(4)};
  304. position: sticky;
  305. height: 80px;
  306. align-items: center;
  307. top: 0;
  308. z-index: 100;
  309. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);
  310. display: grid;
  311. grid-template-columns: 1fr 1fr 1fr;
  312. justify-items: stretch;
  313. `;
  314. const LogoSvg = styled(LogoSentry)`
  315. width: 130px;
  316. height: 30px;
  317. color: ${p => p.theme.textColor};
  318. `;
  319. const OnboardingStep = styled(motion.div)`
  320. flex-grow: 1;
  321. display: flex;
  322. flex-direction: column;
  323. `;
  324. OnboardingStep.defaultProps = {
  325. initial: 'initial',
  326. animate: 'animate',
  327. exit: 'exit',
  328. variants: {animate: {}},
  329. transition: testableTransition({
  330. staggerChildren: 0.2,
  331. }),
  332. };
  333. const AdaptivePageCorners = styled(PageCorners)`
  334. --corner-scale: 1;
  335. @media (max-width: ${p => p.theme.breakpoints.small}) {
  336. --corner-scale: 0.5;
  337. }
  338. `;
  339. const StyledStepper = styled(Stepper)`
  340. justify-self: center;
  341. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  342. display: none;
  343. }
  344. `;
  345. interface BackButtonProps extends Omit<ButtonProps, 'icon' | 'priority'> {
  346. animate: MotionProps['animate'];
  347. className?: string;
  348. }
  349. const Back = styled(({className, animate, ...props}: BackButtonProps) => (
  350. <motion.div
  351. className={className}
  352. animate={animate}
  353. transition={testableTransition()}
  354. variants={{
  355. initial: {opacity: 0, visibility: 'hidden'},
  356. visible: {
  357. opacity: 1,
  358. visibility: 'visible',
  359. transition: testableTransition({delay: 1}),
  360. },
  361. hidden: {
  362. opacity: 0,
  363. transitionEnd: {
  364. visibility: 'hidden',
  365. },
  366. },
  367. }}
  368. >
  369. <Button {...props} icon={<IconArrow direction="left" />} priority="link">
  370. {t('Back')}
  371. </Button>
  372. </motion.div>
  373. ))`
  374. position: absolute;
  375. top: 40px;
  376. left: 20px;
  377. button {
  378. font-size: ${p => p.theme.fontSizeSmall};
  379. }
  380. `;
  381. const OnboardingWrapper = styled('main')`
  382. flex-grow: 1;
  383. display: flex;
  384. flex-direction: column;
  385. `;
  386. export default RelocationOnboarding;