statelet
Version:
Dead simple state management built on kvkit - composable, reactive, shareable. Supports Standard Schema (Valibot, Zod, ArkType).
58 lines (57 loc) • 1.5 kB
JavaScript
/**
* Create a reactive state container
*/
export function state(initial) {
let current = initial;
const listeners = new Set();
return {
get() {
return current;
},
set(valueOrUpdater) {
const next = typeof valueOrUpdater === 'function'
? valueOrUpdater(current)
: valueOrUpdater;
if (next !== current) {
current = next;
listeners.forEach(callback => callback(current));
}
},
subscribe(callback) {
listeners.add(callback);
callback(current); // Call immediately with current value
return () => {
listeners.delete(callback);
};
}
};
}
/**
* Compose multiple enhancers into a single state
*
* @example
* const myState = compose(
* state({ count: 0 }),
* withLocalStorage('count'),
* withEffect(console.log)
* );
*/
export function compose(base, ...enhancers) {
return enhancers.reduce((current, enhancer) => enhancer(current), base);
}
/**
* Curried version of compose for functional style
*
* @example
* const createCounter = enhance(
* withLocalStorage('count'),
* withEffect(console.log)
* );
*
* const counter = createCounter(state({ count: 0 }));
*/
export function enhance(...enhancers) {
return (base) => compose(base, ...enhancers);
}
// Export all enhancers from the enhancers module
export * from './enhancers';