syncbasestore
Version:
Lightweight reactive store with built-in filtering and async state handling
44 lines (43 loc) • 1.46 kB
JavaScript
import { applyFilter } from './filterUtil';
import { getValueAtPath, setValueAtPath } from '../utils/deepUtils';
export class SyncBaseStore {
constructor(initialState) {
this.listeners = new Set();
this.build = this.setState;
this.initialState = initialState;
this.state = structuredClone(initialState);
}
getState(filterDef, filterValue) {
return applyFilter(this.state, filterDef, filterValue);
}
setState(update, filterDef, filterValue) {
const updated = typeof update === 'function'
? update(this.state)
: { ...this.state, ...update };
this.state = { ...this.state, ...updated };
this.notify(filterDef, filterValue);
}
cleanFieldPath(path) {
const initialValue = getValueAtPath(this.initialState, path);
this.state = setValueAtPath(this.state, path, initialValue);
this.notify();
}
clean() {
this.state = this.initialState;
this.notify();
}
subscribe(listener) {
this.listeners.add(listener);
listener(this.state);
return () => this.listeners.delete(listener);
}
getInitialState() {
return structuredClone(this.initialState);
}
notify(filterDef, filterValue) {
const current = applyFilter(this.state, filterDef, filterValue);
for (const listener of this.listeners) {
listener(current);
}
}
}