UNPKG

@flexnative/theme-context

Version:
82 lines 2.9 kB
/** * @file ThemeProvider.tsx * @author Redon Alla <redon.alla@gmail.com> * @createDate 2023-06-04 21:29:02 * @modifyDate 2025-03-02 18:36:42 * @description Provides theming capabilities to the application through a React Context. * * This file defines the `ThemeProvider` component, which is responsible for * managing the application's theme and making it available to child components * via a React Context. It allows for dynamic theme switching, color scheme * management, and persisting theme preferences. */ import React from 'react'; import ThemeContext from './ThemeContext'; import { defaultTheme } from './utilities'; /** * ThemeProvider Component * * Provides a React Context for managing the application's theme. This component * allows you to define, switch, and persist themes and color schemes. * * @template TColors - An optional type to extend the base colors with custom color properties. * @extends React.PureComponent<ThemeProviderProps<TColors>, StateProps<TColors>> * @example * ```typescript * // Example of extending the BaseColors * interface MyColors { * myCustomColor: ColorValue; * } * * // Example of using the ThemeProvider * <ThemeProvider<MyColors> * onLoad={async () => { * // Implement your logic to load the theme from storage * const savedTheme = await AsyncStorage.getItem('theme'); * if (savedTheme) { * this.setState({ theme: JSON.parse(savedTheme) }); * } * return Promise.resolve(); * }} * onChangeColorScheme={async (scheme) => { * // Implement your logic to persist the color scheme * await AsyncStorage.setItem('colorScheme', scheme); * console.log('colorScheme saved:', scheme); * return Promise.resolve(); * }} * onChangeTheme={async (theme) => { * // Implement your logic to persist the theme * await AsyncStorage.setItem('theme', JSON.stringify(theme)); * console.log('Theme saved:', theme); * return Promise.resolve(); * }} * setColors={async (colors) => { * //Implement your logic to update only the colors of the theme. * const newTheme = {...this.state.theme, colors} * this.onChangeTheme(newTheme) * return Promise.resolve() * }} * > * <MyApp /> * </ThemeProvider> * ``` */ export default class ThemeProvider extends React.PureComponent { constructor(props) { super(props); this.state = { theme: props.theme ?? defaultTheme() }; } async componentDidMount() { await this.onLoad(); } render() { return (React.createElement(ThemeContext.Provider, { value: { state: this.state.theme, setTheme: this.onChangeTheme.bind(this), setColorScheme: this.onChangeColorScheme.bind(this), } }, this.props.children)); } } //# sourceMappingURL=ThemeProvider.js.map