[d565449] | 1 | "use strict";
|
---|
| 2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
| 3 | exports.createGlobalState = void 0;
|
---|
| 4 | var tslib_1 = require("tslib");
|
---|
| 5 | var react_1 = require("react");
|
---|
| 6 | var hookState_1 = require("../misc/hookState");
|
---|
| 7 | var useEffectOnce_1 = tslib_1.__importDefault(require("../useEffectOnce"));
|
---|
| 8 | var useIsomorphicLayoutEffect_1 = tslib_1.__importDefault(require("../useIsomorphicLayoutEffect"));
|
---|
| 9 | function createGlobalState(initialState) {
|
---|
| 10 | var store = {
|
---|
| 11 | state: initialState instanceof Function ? initialState() : initialState,
|
---|
| 12 | setState: function (nextState) {
|
---|
| 13 | store.state = hookState_1.resolveHookState(nextState, store.state);
|
---|
| 14 | store.setters.forEach(function (setter) { return setter(store.state); });
|
---|
| 15 | },
|
---|
| 16 | setters: [],
|
---|
| 17 | };
|
---|
| 18 | return function () {
|
---|
| 19 | var _a = react_1.useState(store.state), globalState = _a[0], stateSetter = _a[1];
|
---|
| 20 | useEffectOnce_1.default(function () { return function () {
|
---|
| 21 | store.setters = store.setters.filter(function (setter) { return setter !== stateSetter; });
|
---|
| 22 | }; });
|
---|
| 23 | useIsomorphicLayoutEffect_1.default(function () {
|
---|
| 24 | if (!store.setters.includes(stateSetter)) {
|
---|
| 25 | store.setters.push(stateSetter);
|
---|
| 26 | }
|
---|
| 27 | });
|
---|
| 28 | return [globalState, store.setState];
|
---|
| 29 | };
|
---|
| 30 | }
|
---|
| 31 | exports.createGlobalState = createGlobalState;
|
---|
| 32 | exports.default = createGlobalState;
|
---|