relocation.tsx 11 KB

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