| 1 | import { useSyncExternalStore } from "react"; |
| 2 | |
| 3 | const createStore = (createState) => { |
| 4 | let state; |
| 5 | const listeners = new Set(); |
| 6 | |
| 7 | const setState = (partial, replace) => { |
| 8 | const nextState = typeof partial === 'function' ? partial(state) : partial |
| 9 | |
| 10 | if (!Object.is(nextState, state)) { |
| 11 | const previousState = state; |
| 12 | |
| 13 | if(!replace) { |
| 14 | state = (typeof nextState !== 'object' || nextState === null) |
| 15 | ? nextState |
| 16 | : Object.assign({}, state, nextState); |
| 17 | } else { |
| 18 | state = nextState; |
| 19 | } |
| 20 | listeners.forEach((listener) => listener(state, previousState)); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | const getState = () => state; |
| 25 | |
| 26 | const subscribe= (listener) => { |
| 27 | listeners.add(listener) |
| 28 | return () => listeners.delete(listener) |
| 29 | } |
| 30 | |
| 31 | const destroy= () => { |
| 32 | listeners.clear() |
| 33 | } |
| 34 | |
| 35 | const api = { setState, getState, subscribe, destroy } |
| 36 | |
| 37 | state = createState(setState, getState, api) |
| 38 | |
| 39 | return api |
| 40 | } |
| 41 | |
| 42 | function useStore(api, selector) { |
| 43 | function getState() { |