Files
smartstate/ts/smartstate.classes.statepart.ts
Juergen Kunz 02575e8baf
Some checks failed
Default (tags) / security (push) Successful in 42s
Default (tags) / test (push) Successful in 1m8s
Default (tags) / release (push) Failing after 59s
Default (tags) / metadata (push) Successful in 1m8s
fix(core): Fix state initialization, hash detection, and validation - v2.0.25
2025-07-29 19:26:03 +00:00

181 lines
5.3 KiB
TypeScript

import * as plugins from './smartstate.plugins.js';
import { StateAction, type IActionDef } from './smartstate.classes.stateaction.js';
export class StatePart<TStatePartName, TStatePayload> {
public name: TStatePartName;
public state = new plugins.smartrx.rxjs.Subject<TStatePayload>();
public stateStore: TStatePayload | undefined;
private cumulativeDeferred = plugins.smartpromise.cumulativeDefer();
private webStoreOptions: plugins.webstore.IWebStoreOptions;
private webStore: plugins.webstore.WebStore<TStatePayload> | null = null; // Add WebStore instance
constructor(nameArg: TStatePartName, webStoreOptionsArg?: plugins.webstore.IWebStoreOptions) {
this.name = nameArg;
// Initialize WebStore if webStoreOptions are provided
if (webStoreOptionsArg) {
this.webStoreOptions = webStoreOptionsArg;
}
}
/**
* initializes the webstore
*/
public async init() {
if (this.webStoreOptions) {
this.webStore = new plugins.webstore.WebStore<TStatePayload>(this.webStoreOptions);
await this.webStore.init();
const storedState = await this.webStore.get(String(this.name));
if (storedState && this.validateState(storedState)) {
this.stateStore = storedState;
await this.notifyChange();
}
}
}
/**
* gets the state from the state store
*/
public getState(): TStatePayload | undefined {
return this.stateStore;
}
/**
* sets the stateStore to the new state
* @param newStateArg
*/
public async setState(newStateArg: TStatePayload) {
// Validate state structure
if (!this.validateState(newStateArg)) {
throw new Error(`Invalid state structure for state part '${this.name}'`);
}
this.stateStore = newStateArg;
await this.notifyChange();
// Save state to WebStore if initialized
if (this.webStore) {
await this.webStore.set(String(this.name), newStateArg);
}
return this.stateStore;
}
/**
* Validates state structure - can be overridden for custom validation
* @param stateArg
*/
protected validateState(stateArg: any): stateArg is TStatePayload {
// Basic validation - ensure state is not null/undefined
// Subclasses can override for more specific validation
return stateArg !== null && stateArg !== undefined;
}
/**
* notifies of a change on the state
*/
public async notifyChange() {
if (!this.stateStore) {
return;
}
const createStateHash = async (stateArg: any) => {
return await plugins.smarthashWeb.sha256FromString(plugins.smartjson.stringify(stateArg));
};
const currentHash = await createStateHash(this.stateStore);
if (
this.lastStateNotificationPayloadHash &&
currentHash === this.lastStateNotificationPayloadHash
) {
return;
} else {
this.lastStateNotificationPayloadHash = currentHash;
}
this.state.next(this.stateStore);
}
private lastStateNotificationPayloadHash: any;
/**
* creates a cumulative notification by adding a change notification at the end of the call stack;
*/
public notifyChangeCumulative() {
// TODO: check viability
setTimeout(async () => {
if (this.stateStore) {
await this.notifyChange();
}
}, 0);
}
/**
* selects a state or a substate
*/
public select<T = TStatePayload>(
selectorFn?: (state: TStatePayload) => T
): plugins.smartrx.rxjs.Observable<T> {
if (!selectorFn) {
selectorFn = (state: TStatePayload) => <T>(<any>state);
}
const mapped = this.state.pipe(
plugins.smartrx.rxjs.ops.startWith(this.getState()),
plugins.smartrx.rxjs.ops.filter((stateArg): stateArg is TStatePayload => stateArg !== undefined),
plugins.smartrx.rxjs.ops.map((stateArg) => {
try {
return selectorFn(stateArg);
} catch (e) {
// Nothing here
}
})
);
return mapped;
}
/**
* creates an action capable of modifying the state
*/
public createAction<TActionPayload>(
actionDef: IActionDef<TStatePayload, TActionPayload>
): StateAction<TStatePayload, TActionPayload> {
return new StateAction(this, actionDef);
}
/**
* dispatches an action on the statepart level
*/
public async dispatchAction<T>(stateAction: StateAction<TStatePayload, T>, actionPayload: T): Promise<TStatePayload> {
await this.cumulativeDeferred.promise;
const newState = await stateAction.actionDef(this, actionPayload);
await this.setState(newState);
return this.getState();
}
/**
* waits until a certain part of the state becomes available
* @param selectorFn
*/
public async waitUntilPresent<T = TStatePayload>(
selectorFn?: (state: TStatePayload) => T
): Promise<T> {
const done = plugins.smartpromise.defer<T>();
const selectedObservable = this.select(selectorFn);
const subscription = selectedObservable.subscribe(async (value) => {
if (value) {
done.resolve(value);
}
});
const result = await done.promise;
subscription.unsubscribe();
return result;
}
/**
* is executed
*/
public async stateSetup(
funcArg: (statePartArg?: StatePart<any, TStatePayload>) => Promise<TStatePayload>
) {
const resultPromise = funcArg(this);
this.cumulativeDeferred.addPromise(resultPromise);
this.setState(await resultPromise);
}
}