From bb6c04406bc4798ad4fd06d4fe67ef72c42d3dd7 Mon Sep 17 00:00:00 2001 From: Arctic Ice Studio Date: Tue, 4 Dec 2018 06:11:52 +0100 Subject: [PATCH] Rewrite the `Root` core container as class-based component The `Root` component has been changed from a SFC to a class component to store the currently active state and handle the theme mode toggle logic through a function. It also migrated the currently used simple "styled-component" theme (1) (provided through the ` * @author Sven Greb * @since 0.1.0 */ -const Root = ({ children }) => ( - - - {children} - -); +export default class Root extends Component { + static propTypes = { + children: PropTypes.node.isRequired + }; -Root.propTypes = { - children: PropTypes.node.isRequired -}; + /** + * Constructs the compnent with the given `props` and persists the default theme mode if the key is not already stored + * in the session storage. + * + * @method constructor + * @param {object} props The React component's `props`. + * @since 0.2.0 + */ + constructor(props) { + super(props); + if (!readSessionCache(SESSIONSTORAGE_KEY_THEME_MODE)) { + writeSessionCache(SESSIONSTORAGE_KEY_THEME_MODE, MODE_BRIGHT_SNOW_FLURRY); + } + } -export default Root; + state = { + themeMode: readSessionCache(SESSIONSTORAGE_KEY_THEME_MODE) || MODE_BRIGHT_SNOW_FLURRY + }; + + /** + * Toggles the global theme mode and persists it in the browser's session storage. + * The function is exposed through the global theme mode context provider component. + * + * @method toggleThemeMode + * @return {void} + * @since 0.2.0 + */ + toggleThemeMode = () => { + /* eslint-disable-next-line babel/no-unused-expressions */ + readSessionCache(SESSIONSTORAGE_KEY_THEME_MODE) === MODE_BRIGHT_SNOW_FLURRY + ? writeSessionCache(SESSIONSTORAGE_KEY_THEME_MODE, MODE_DARK_NIGHT_FROST) + : writeSessionCache(SESSIONSTORAGE_KEY_THEME_MODE, MODE_BRIGHT_SNOW_FLURRY); + this.setState(({ themeMode }) => ({ + themeMode: themeMode === MODE_BRIGHT_SNOW_FLURRY ? MODE_DARK_NIGHT_FROST : MODE_BRIGHT_SNOW_FLURRY + })); + }; + + render() { + const { children } = this.props; + const { themeMode } = this.state; + + const themeModeContextValue = { + toggleThemeMode: this.toggleThemeMode, + [THEME_KEY_MODE]: themeMode + }; + const composedTheme = { + ...themeModeContextValue, + ...theme + }; + + return ( + + + + {children} + + + ); + } +} + +export { GlobalThemeMode }; diff --git a/src/components/containers/core/Root/index.js b/src/components/containers/core/Root/index.js index 5fd68692..f110db04 100644 --- a/src/components/containers/core/Root/index.js +++ b/src/components/containers/core/Root/index.js @@ -7,4 +7,7 @@ * License: MIT */ -export { default } from "./Root"; +import Root, { GlobalThemeMode } from "./Root"; + +export { GlobalThemeMode }; +export default Root;