All files / src/configprovider ConfigProvider.tsx

14.29% Statements 2/14
0% Branches 0/1
0% Functions 0/6
16.67% Lines 2/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                  9x   9x                                                                  
import React, { useEffect, useState } from "react";
import EventEmitter from "eventemitter3";
import { ConfigContext, Config, DEFAULT_CLASS_PREFIX } from "./ConfigContext";
 
// setConfig
interface ConfigEventTypes {
  set: [Config];
}
class ConfigEmitter extends EventEmitter<ConfigEventTypes> {}
const configEmitter = new ConfigEmitter();
 
const configStore: Config = {};
 
export function setConfig(config: Config = {}) {
  Object.assign(configStore, config);
  configEmitter.emit("set", configStore);
}
 
// ConfigProvider
export interface ConfigProviderProps extends Config {
  children: React.ReactNode;
}
 
export function ConfigProvider({
  children,
  ...configProps
}: ConfigProviderProps) {
  const [globalConfig, setGlobalConfig] = useState<Config>(configStore);
 
  useEffect(() => {
    const callback = config => {
      setGlobalConfig(curConfig => Object.assign({}, curConfig, config));
    };
    configEmitter.on("set", callback);
    return () => configEmitter.removeListener("set", callback);
  }, []);
 
  // props 优先级高于全局配置
  const config = Object.assign({}, globalConfig, configProps);
 
  return (
    <ConfigContext.Provider value={config}>{children}</ConfigContext.Provider>
  );
}