| 1 |
/** |
| 2 |
* Tiny pub/sub store for `useSyncExternalStore`. `set` short-circuits on |
| 3 |
* `equals` so `get` keeps a stable reference while unchanged. |
| 4 |
* |
| 5 |
* @param {*} initialState |
| 6 |
* @param {Function} [equals] Default `Object.is`. |
| 7 |
* @returns {{ get, set, subscribe }} |
| 8 |
*/ |
| 9 |
export function createPubsubStore( initialState, equals = Object.is ) { |
| 10 |
let state = initialState; |
| 11 |
const subscribers = new Set(); |
| 12 |
return { |
| 13 |
get: () => state, |
| 14 |
set: ( next ) => { |
| 15 |
if ( equals( state, next ) ) return; |
| 16 |
state = next; |
| 17 |
subscribers.forEach( ( fn ) => fn() ); |
| 18 |
}, |
| 19 |
subscribe: ( fn ) => { |
| 20 |
subscribers.add( fn ); |
| 21 |
return () => subscribers.delete( fn ); |
| 22 |
}, |
| 23 |
}; |
| 24 |
} |
| 25 |
|