soapbox/app/soapbox/containers/soapbox.tsx

310 wiersze
9.5 KiB
TypeScript
Czysty Zwykły widok Historia

2020-03-27 20:59:38 +00:00
'use strict';
2022-08-02 01:13:02 +00:00
import { QueryClientProvider } from '@tanstack/react-query';
import classNames from 'clsx';
2022-04-21 16:47:28 +00:00
import React, { useState, useEffect } from 'react';
2022-12-20 15:47:46 +00:00
import { Toaster } from 'react-hot-toast';
import { IntlProvider } from 'react-intl';
2022-04-21 17:19:33 +00:00
import { Provider } from 'react-redux';
import { BrowserRouter, Switch, Redirect, Route } from 'react-router-dom';
// @ts-ignore: it doesn't have types
import { ScrollContext } from 'react-router-scroll-4';
2022-12-20 15:47:46 +00:00
import { loadInstance } from 'soapbox/actions/instance';
2020-05-28 22:52:07 +00:00
import { fetchMe } from 'soapbox/actions/me';
import { loadSoapboxConfig, getSoapboxConfig } from 'soapbox/actions/soapbox';
2022-03-21 18:09:01 +00:00
import { fetchVerificationConfig } from 'soapbox/actions/verification';
2022-11-15 20:48:54 +00:00
import * as BuildConfig from 'soapbox/build-config';
import GdprBanner from 'soapbox/components/gdpr-banner';
import Helmet from 'soapbox/components/helmet';
import LoadingScreen from 'soapbox/components/loading-screen';
import { StatProvider } from 'soapbox/contexts/stat-context';
2022-11-15 17:23:36 +00:00
import AuthLayout from 'soapbox/features/auth-layout';
2022-08-12 17:58:35 +00:00
import EmbeddedStatus from 'soapbox/features/embedded-status';
2022-11-15 19:00:40 +00:00
import PublicLayout from 'soapbox/features/public-layout';
2022-11-16 13:32:32 +00:00
import BundleContainer from 'soapbox/features/ui/containers/bundle-container';
import {
ModalContainer,
OnboardingWizard,
2022-05-20 18:29:17 +00:00
WaitlistPage,
} from 'soapbox/features/ui/util/async-components';
import { createGlobals } from 'soapbox/globals';
import {
useAppSelector,
useAppDispatch,
useOwnAccount,
useFeatures,
useSoapboxConfig,
useSettings,
2022-07-22 22:25:52 +00:00
useTheme,
useLocale,
2022-11-26 16:38:16 +00:00
useInstance,
} from 'soapbox/hooks';
2022-04-21 16:47:28 +00:00
import MESSAGES from 'soapbox/locales/messages';
2022-12-18 18:29:31 +00:00
import { normalizeSoapboxConfig } from 'soapbox/normalizers';
2022-08-02 01:13:02 +00:00
import { queryClient } from 'soapbox/queries/client';
import { useCachedLocationHandler } from 'soapbox/utils/redirect';
import { generateThemeCss } from 'soapbox/utils/theme';
2022-05-02 20:55:52 +00:00
import { checkOnboardingStatus } from '../actions/onboarding';
2022-01-10 22:01:24 +00:00
import { preload } from '../actions/preload';
2022-11-15 14:10:14 +00:00
import ErrorBoundary from '../components/error-boundary';
2022-01-10 22:01:24 +00:00
import UI from '../features/ui';
import { store } from '../store';
2020-03-27 20:59:38 +00:00
// Configure global functions for developers
createGlobals(store);
2022-04-19 23:15:42 +00:00
// Preload happens synchronously
2022-04-21 17:19:33 +00:00
store.dispatch(preload() as any);
2022-05-02 20:55:52 +00:00
// This happens synchronously
store.dispatch(checkOnboardingStatus() as any);
2022-04-19 23:15:42 +00:00
/** Load initial data from the backend */
const loadInitial = () => {
2022-04-21 17:19:33 +00:00
// @ts-ignore
2022-04-19 23:15:42 +00:00
return async(dispatch, getState) => {
// Await for authenticated fetch
2022-08-10 12:38:37 +00:00
await dispatch(fetchMe());
// Await for feature detection
await dispatch(loadInstance());
// Await for configuration
await dispatch(loadSoapboxConfig());
2022-04-19 23:15:42 +00:00
const state = getState();
const soapboxConfig = getSoapboxConfig(state);
const pepeEnabled = soapboxConfig.getIn(['extensions', 'pepe', 'enabled']) === true;
2022-03-21 18:09:01 +00:00
if (pepeEnabled && !state.me) {
await dispatch(fetchVerificationConfig());
2022-03-21 18:09:01 +00:00
}
2022-04-19 23:15:42 +00:00
};
};
2022-03-21 18:09:01 +00:00
2022-05-20 17:30:29 +00:00
/** Highest level node with the Redux store. */
2022-04-21 16:47:28 +00:00
const SoapboxMount = () => {
useCachedLocationHandler();
2022-08-02 13:20:07 +00:00
2022-04-21 16:47:28 +00:00
const me = useAppSelector(state => state.me);
2022-11-26 16:38:16 +00:00
const instance = useInstance();
2022-04-21 16:47:28 +00:00
const account = useOwnAccount();
const soapboxConfig = useSoapboxConfig();
2022-04-30 17:02:30 +00:00
const features = useFeatures();
2020-03-27 20:59:38 +00:00
const waitlisted = account && !account.source.get('approved', true);
2022-05-02 20:55:52 +00:00
const needsOnboarding = useAppSelector(state => state.onboarding.needsOnboarding);
const showOnboarding = account && !waitlisted && needsOnboarding;
2022-04-21 16:47:28 +00:00
const singleUserMode = soapboxConfig.singleUserMode && soapboxConfig.singleUserModeProfile;
2020-06-05 02:22:58 +00:00
2022-05-11 19:50:53 +00:00
const pepeEnabled = soapboxConfig.getIn(['extensions', 'pepe', 'enabled']) === true;
2022-05-04 13:08:40 +00:00
// @ts-ignore: I don't actually know what these should be, lol
const shouldUpdateScroll = (prevRouterProps, { location }) => {
return !(location.state?.soapboxModalKey && location.state?.soapboxModalKey !== prevRouterProps?.location?.state?.soapboxModalKey);
};
/** Render the onboarding flow. */
const renderOnboarding = () => (
<BundleContainer fetchComponent={OnboardingWizard} loading={LoadingScreen}>
{(Component) => <Component />}
</BundleContainer>
);
/** Render the auth layout or UI. */
const renderSwitch = () => (
<Switch>
<Redirect from='/v1/verify_email/:token' to='/verify/email/:token' />
{/* Redirect signup route depending on Pepe enablement. */}
{/* We should prefer using /signup in components. */}
{pepeEnabled ? (
<Redirect from='/signup' to='/verify' />
) : (
<Redirect from='/verify' to='/signup' />
)}
{waitlisted && (
2022-05-20 18:29:17 +00:00
<Route render={(props) => (
<BundleContainer fetchComponent={WaitlistPage} loading={LoadingScreen}>
{(Component) => <Component {...props} account={account} />}
</BundleContainer>
)}
/>
)}
{!me && (singleUserMode
? <Redirect exact from='/' to={`/${singleUserMode}`} />
: <Route exact path='/' component={PublicLayout} />)}
{!me && (
<Route exact path='/' component={PublicLayout} />
)}
<Route exact path='/about/:slug?' component={PublicLayout} />
<Route path='/login' component={AuthLayout} />
{(features.accountCreation && instance.registrations) && (
<Route exact path='/signup' component={AuthLayout} />
)}
{pepeEnabled && (
<Route path='/verify' component={AuthLayout} />
)}
<Route path='/reset-password' component={AuthLayout} />
<Route path='/edit-password' component={AuthLayout} />
<Route path='/invite/:token' component={AuthLayout} />
<Route path='/' component={UI} />
</Switch>
);
/** Render the onboarding flow or UI. */
const renderBody = () => {
if (showOnboarding) {
return renderOnboarding();
} else {
return renderSwitch();
}
};
return (
<ErrorBoundary>
<BrowserRouter basename={BuildConfig.FE_SUBDIRECTORY}>
<ScrollContext shouldUpdateScroll={shouldUpdateScroll}>
<Switch>
<Route
path='/embed/:statusId'
render={(props) => <EmbeddedStatus params={props.match.params} />}
/>
<Redirect from='/@:username/:statusId/embed' to='/embed/:statusId' />
<Route>
{renderBody()}
<BundleContainer fetchComponent={ModalContainer}>
{Component => <Component />}
</BundleContainer>
<GdprBanner />
2022-12-20 15:47:46 +00:00
<Toaster position='top-right' containerClassName='top-10' containerStyle={{ top: 75 }} />
</Route>
</Switch>
</ScrollContext>
</BrowserRouter>
</ErrorBoundary>
);
};
interface ISoapboxLoad {
children: React.ReactNode,
}
/** Initial data loader. */
const SoapboxLoad: React.FC<ISoapboxLoad> = ({ children }) => {
const dispatch = useAppDispatch();
const me = useAppSelector(state => state.me);
const account = useOwnAccount();
const swUpdating = useAppSelector(state => state.meta.swUpdating);
const { locale } = useLocale();
const [messages, setMessages] = useState<Record<string, string>>({});
const [localeLoading, setLocaleLoading] = useState(true);
const [isLoaded, setIsLoaded] = useState(false);
/** Whether to display a loading indicator. */
const showLoading = [
me === null,
me && !account,
!isLoaded,
localeLoading,
swUpdating,
].some(Boolean);
// Load the user's locale
useEffect(() => {
MESSAGES[locale]().then(messages => {
setMessages(messages);
setLocaleLoading(false);
}).catch(() => { });
}, [locale]);
// Load initial data from the API
useEffect(() => {
2022-08-10 12:38:37 +00:00
dispatch(loadInitial()).then(() => {
setIsLoaded(true);
}).catch(() => {
setIsLoaded(true);
});
}, []);
// intl is part of loading.
// It's important nothing in here depends on intl.
if (showLoading) {
return <LoadingScreen />;
2020-03-27 20:59:38 +00:00
}
2022-04-21 16:47:28 +00:00
return (
<IntlProvider locale={locale} messages={messages}>
{children}
2022-04-21 16:47:28 +00:00
</IntlProvider>
);
};
2020-03-27 20:59:38 +00:00
interface ISoapboxHead {
children: React.ReactNode,
}
/** Injects metadata into site head with Helmet. */
const SoapboxHead: React.FC<ISoapboxHead> = ({ children }) => {
const { locale, direction } = useLocale();
const settings = useSettings();
const soapboxConfig = useSoapboxConfig();
2022-12-18 18:29:31 +00:00
const demo = !!settings.get('demo');
2022-07-22 22:25:52 +00:00
const darkMode = useTheme() === 'dark';
2022-12-18 18:29:31 +00:00
const themeCss = generateThemeCss(demo ? normalizeSoapboxConfig({ brandColor: '#0482d8' }) : soapboxConfig);
const bodyClass = classNames('bg-white dark:bg-gray-800 text-base h-full', {
'no-reduce-motion': !settings.get('reduceMotion'),
'underline-links': settings.get('underlineLinks'),
'demetricator': settings.get('demetricator'),
});
return (
<>
<Helmet>
<html lang={locale} className={classNames('h-full', { dark: darkMode })} />
<body className={bodyClass} dir={direction} />
{themeCss && <style id='theme' type='text/css'>{`:root{${themeCss}}`}</style>}
{darkMode && <style type='text/css'>{':root { color-scheme: dark; }'}</style>}
<meta name='theme-color' content={soapboxConfig.brandColor} />
</Helmet>
{children}
</>
);
};
2022-05-20 17:30:29 +00:00
/** The root React node of the application. */
const Soapbox: React.FC = () => {
return (
<Provider store={store}>
2022-08-10 12:38:37 +00:00
<QueryClientProvider client={queryClient}>
<StatProvider>
<SoapboxHead>
<SoapboxLoad>
<SoapboxMount />
</SoapboxLoad>
</SoapboxHead>
</StatProvider>
2022-08-10 12:38:37 +00:00
</QueryClientProvider>
</Provider>
);
};
2020-03-27 20:59:38 +00:00
export default Soapbox;