Skip to content

Commit

Permalink
fix(fsm): run postTransition__ in resetToInitialState_ and constructor
Browse files Browse the repository at this point in the history
BREAKING CHANGE: event 'reset' fired on calling resetToInitialState and the first time in class constructor
  • Loading branch information
alimd committed Nov 6, 2024
1 parent fcb9541 commit 00ca9c1
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions packages/fsm/src/base.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import {packageTracer} from '@alwatr/nanolib';
import {AlwatrObservable, type AlwatrObservableConfig} from '@alwatr/observable';

import type {ActionName, ActionRecord, StateEventDetail, StateRecord} from './type.js';
import type {ActionName, ActionRecord, MachineEvent, MachineState, StateEventDetail, StateRecord} from './type.js';

__dev_mode__: packageTracer.add(__package_name__, __package_version__);

export interface AlwatrFluxStateMachineConfig<S extends string> extends AlwatrObservableConfig {
export interface AlwatrFluxStateMachineConfig<S extends MachineState> extends AlwatrObservableConfig {
initialState: S;
}

/**
* Flux (Finite) State Machine Base Class
*/
export abstract class AlwatrFluxStateMachineBase<S extends string, E extends string> extends AlwatrObservable<{state: S}> {
export abstract class AlwatrFluxStateMachineBase<S extends MachineState, E extends MachineEvent> extends AlwatrObservable<{state: S}> {
/**
* States and transitions config.
*/
Expand All @@ -30,15 +30,24 @@ export abstract class AlwatrFluxStateMachineBase<S extends string, E extends str
constructor(config: AlwatrFluxStateMachineConfig<S>) {
config.loggerPrefix ??= 'flux-state-machine';
super(config);
this.message_ = {state: this.initialState_ = config.initialState};

this.initialState_ = config.initialState;
this.message_ = {state: this.initialState_};
this.resetToInitialState_();
}

/**
* Reset machine to initial state without notify.
*/
protected resetToInitialState_(): void {
this.logger_.logMethod?.('resetToInitialState_');
const from = this.message_.state;
this.message_ = {state: this.initialState_};
this.postTransition__({
from,
event: 'reset' as E,
to: this.initialState_,
});
}

/**
Expand Down

0 comments on commit 00ca9c1

Please sign in to comment.