UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

67 lines 2.56 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import { useEffect, useState } from 'react'; import { EventBus } from "../utils/index.js"; export function createGlobalState(_initialState, _customResult) { var initialState; var customResult; if (typeof _customResult === 'function') { initialState = _initialState; customResult = _customResult; } else if (typeof _initialState === 'function') { initialState = undefined; customResult = _initialState; } else { initialState = _initialState; customResult = undefined; } var bus = new EventBus(); var currentGlobalState = initialState; var getGlobalState = function getGlobalState() { return currentGlobalState; }; var setGlobalState = function setGlobalState(nextGlobalState) { if (typeof nextGlobalState === 'function') { nextGlobalState = nextGlobalState(currentGlobalState); } if (nextGlobalState !== currentGlobalState) { var _prevGlobalState = currentGlobalState; currentGlobalState = nextGlobalState; bus.emit('setGlobalState', nextGlobalState, _prevGlobalState); } }; var setGlobalStatePartial = function setGlobalStatePartial(nextGlobalState) { if (typeof nextGlobalState === 'function') { nextGlobalState = nextGlobalState(currentGlobalState); } nextGlobalState = _extends({}, currentGlobalState, nextGlobalState); var prevGlobalState = currentGlobalState; currentGlobalState = nextGlobalState; bus.emit('setGlobalState', nextGlobalState, prevGlobalState); }; var watchGlobalState = function watchGlobalState(callback) { return bus.on('setGlobalState', callback); }; var watchGlobalStateImmediate = function watchGlobalStateImmediate(callback) { callback(initialState, undefined); return bus.on('setGlobalState', callback); }; var useCustomResult = typeof customResult === 'function'; var useGlobalState = function useGlobalState() { var _useState = useState(currentGlobalState), state = _useState[0], setState = _useState[1]; useEffect(function () { return watchGlobalState(setState); }, []); return useCustomResult ? customResult({ state: state, setState: setGlobalState }) : [state, setGlobalState]; }; useGlobalState.getState = getGlobalState; useGlobalState.setState = setGlobalState; useGlobalState.setStatePartial = setGlobalStatePartial; useGlobalState.watchState = watchGlobalState; useGlobalState.watchStateImmediate = watchGlobalStateImmediate; return useGlobalState; }