relocation.tsx 11 KB

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