config.tsx 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import React from "react";
  2. import { defaultConfig, defaultJson } from "src/constants/data";
  3. import { ReducerAction, useConfigReducer } from "src/reducer/reducer";
  4. import { ReactComponent, StorageConfig } from "src/typings/global";
  5. export interface AppConfig {
  6. json: string;
  7. settings: StorageConfig;
  8. }
  9. export const initialStates: AppConfig = {
  10. json: JSON.stringify(defaultJson),
  11. settings: defaultConfig,
  12. };
  13. interface Config {
  14. states: AppConfig;
  15. dispatch: React.Dispatch<ReducerAction>;
  16. }
  17. const defaultContext: Config = {
  18. states: initialStates,
  19. dispatch: () => {},
  20. };
  21. const ConfigContext: React.Context<Config> =
  22. React.createContext(defaultContext);
  23. const useConfig = () => React.useContext(ConfigContext);
  24. const WithConfig: ReactComponent = ({ children }) => {
  25. const [states, dispatch] = React.useReducer(useConfigReducer, initialStates);
  26. const value = { states, dispatch };
  27. return (
  28. <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>
  29. );
  30. };
  31. const withConfig = <P extends object>(
  32. Component: React.ComponentType<P>
  33. ): React.FC => {
  34. return (props) => (
  35. <WithConfig>
  36. <Component {...(props as P)} />
  37. </WithConfig>
  38. );
  39. };
  40. export { WithConfig, useConfig, ConfigContext, withConfig };