UNPKG

xaco-store

Version:

A lightweight state management library for Angular using Signals

90 lines (84 loc) 3.08 kB
import * as i0 from '@angular/core'; import { signal, Injectable } from '@angular/core'; const CURRENT_STATE_TEXT = 'Current state:'; const NEXT_STATE_TEXT = 'Next state:'; const ACTION_TEXT = 'Action:'; const PAYLOAD_TEXT = 'Payload:'; function logMiddleware(currentState, nextState, action, payload) { console.log(CURRENT_STATE_TEXT, currentState); console.log(NEXT_STATE_TEXT, nextState); console.log(ACTION_TEXT, action); if (payload) console.log(PAYLOAD_TEXT, payload); } class StoreService { constructor() { this._stores = new Map(); } createStore(key, initialState, actions, middlewares) { if (!this._stores.has(key)) { const state = signal(initialState); this._stores.set(key, { state, readonlyState: state.asReadonly(), initialState, actions, middlewares }); } return this.getStore(key); } getStore(key) { const store = this._stores.get(key); if (!store) { throw new Error(`Store with key "${key}" not found. Create it first using createStore.`); } const actionCreators = Object.keys(store.actions).reduce((acc, actionIndex) => { acc[actionIndex] = (payload) => { const currentState = store.state(); const stateActionResult = store.actions[actionIndex](currentState, payload); if (store.middlewares) { store.middlewares.forEach((middleware) => { middleware(currentState, stateActionResult, actionIndex, payload); }); } store.state.set(stateActionResult); }; return acc; }, {}); return { state: store.readonlyState, resetStore: () => store.state.set(store.initialState), ...actionCreators, }; } getStateSignal(key) { const store = this._stores.get(key); if (!store) { throw new Error(`Store with key "${key}" not found`); } return store.readonlyState; } clearStore(key) { this._stores.delete(key); } clearAllStores() { this._stores.clear(); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: StoreService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: StoreService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: StoreService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); /* * Public API Surface of xaco-store */ /** * Generated bundle index. Do not edit. */ export { StoreService, logMiddleware }; //# sourceMappingURL=xaco-store.mjs.map