themeAndStyleProvider.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {Component} from 'react';
  2. import ReactDOM from 'react-dom';
  3. import {cache} from '@emotion/css'; // eslint-disable-line emotion/no-vanilla
  4. import {CacheProvider, ThemeProvider} from '@emotion/react'; // This is needed to set "speedy" = false (for percy)
  5. import {loadPreferencesState} from 'app/actionCreators/preferences';
  6. import ConfigStore from 'app/stores/configStore';
  7. import GlobalStyles from 'app/styles/global';
  8. import {Config} from 'app/types';
  9. import {darkTheme, lightTheme, Theme} from 'app/utils/theme';
  10. import withConfig from 'app/utils/withConfig';
  11. type Props = {
  12. config: Config;
  13. };
  14. type State = {
  15. theme: Theme;
  16. };
  17. class Main extends Component<Props, State> {
  18. state: State = {
  19. theme: this.themeName === 'dark' ? darkTheme : lightTheme,
  20. };
  21. componentDidMount() {
  22. loadPreferencesState();
  23. }
  24. componentDidUpdate(prevProps: Props) {
  25. const {config} = this.props;
  26. if (config.theme !== prevProps.config.theme) {
  27. // eslint-disable-next-line
  28. this.setState({
  29. theme: config.theme === 'dark' ? darkTheme : lightTheme,
  30. });
  31. }
  32. }
  33. get themeName() {
  34. return ConfigStore.get('theme');
  35. }
  36. render() {
  37. return (
  38. <ThemeProvider theme={this.state.theme}>
  39. <GlobalStyles
  40. isDark={this.props.config.theme === 'dark'}
  41. theme={this.state.theme}
  42. />
  43. <CacheProvider value={cache}>{this.props.children}</CacheProvider>
  44. {ReactDOM.createPortal(
  45. <meta name="color-scheme" content={this.themeName} />,
  46. document.head
  47. )}
  48. </ThemeProvider>
  49. );
  50. }
  51. }
  52. export default withConfig(Main);