smartstate/ts/smartstate.classes.statepart.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

2019-02-21 20:48:39 +00:00
import * as plugins from './smartstate.plugins';
import { Observable, Subject } from 'rxjs';
import { startWith, takeUntil, map } from 'rxjs/operators';
2019-02-26 17:09:38 +00:00
import { StateAction, IActionDef } from './smartstate.classes.stateaction';
2019-02-21 20:48:39 +00:00
2019-02-26 17:09:38 +00:00
export class StatePart<TStatePartName, TStatePayload> {
name: TStatePartName;
state = new Subject<TStatePayload>();
stateStore: TStatePayload;
2019-02-21 20:48:39 +00:00
2019-02-26 17:09:38 +00:00
constructor(nameArg: TStatePartName) {
2019-02-21 20:48:39 +00:00
this.name = nameArg;
}
/**
* gets the state from the state store
*/
2019-02-26 17:09:38 +00:00
getState(): TStatePayload {
2019-02-21 20:48:39 +00:00
return this.stateStore;
}
/**
* sets the stateStore to the new state
* @param newStateArg
*/
2019-02-26 17:09:38 +00:00
setState(newStateArg: TStatePayload) {
2019-02-21 20:48:39 +00:00
this.stateStore = newStateArg;
this.notifyChange();
}
/**
* notifies of a change on the state
*/
notifyChange() {
this.state.next(this.stateStore);
}
/**
* selects a state or a substate
*/
2019-02-26 17:09:38 +00:00
select<T = TStatePayload>(selectorFn?: (state: TStatePayload) => T): Observable<T> {
2019-02-21 20:48:39 +00:00
if (!selectorFn) {
2019-02-26 17:09:38 +00:00
selectorFn = (state: TStatePayload) => <T>(<any>state);
2019-02-21 20:48:39 +00:00
}
const mapped = this.state.pipe(
startWith(this.getState()),
map(selectorFn)
);
return mapped;
}
2019-02-26 17:09:38 +00:00
/**
* creates an action capable of modifying the state
*/
2019-02-27 01:00:47 +00:00
createAction<TActionPayload>(
actionDef: IActionDef<TStatePayload, TActionPayload>
): StateAction<TStatePayload, TActionPayload> {
2019-02-26 17:09:38 +00:00
return new StateAction(actionDef);
}
2019-02-21 20:48:39 +00:00
/**
* dispatches an action on the statepart level
*/
2019-02-26 17:09:38 +00:00
async dispatchAction<T>(stateAction: StateAction<TStatePayload, T>, actionPayload: T) {
const newState = await stateAction.actionDef(this, actionPayload);
2019-02-21 20:48:39 +00:00
this.setState(newState);
}
}