relocation.tsx 11 KB

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