Skip to content

Commit

Permalink
feat(@xstate/fsm): execute actions
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkpiano committed Oct 4, 2019
1 parent 63d3d1d commit 53f3380
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
2 changes: 2 additions & 0 deletions packages/xstate-fsm/README.md
Expand Up @@ -213,6 +213,8 @@ An object that represents the state of a machine with the following schema:

Creates an instance of an interpreted machine, also known as a **service**. This is a stateful representation of the running machine, which you can subscribe to, send events to, start, and stop.

Actions will also be executed by the interpreter.

| Argument | Type | Description |
| --------- | ------------ | ------------------------------ |
| `machine` | StateMachine | The machine to be interpreted. |
Expand Down
13 changes: 10 additions & 3 deletions packages/xstate-fsm/src/index.ts
Expand Up @@ -36,6 +36,12 @@ function createMatcher(value) {
return stateValue => value === stateValue;
}

function toEventObject<TEvent extends EventObject>(
event: TEvent['type'] | TEvent
): TEvent {
return (typeof event === 'string' ? { type: event } : event) as TEvent;
}

export function createMachine<
TContext extends object,
TEvent extends EventObject = EventObject,
Expand All @@ -60,9 +66,7 @@ export function createMachine<
typeof state === 'string'
? { value: state, context: fsmConfig.context! }
: state;
const eventObject = (typeof event === 'string'
? { type: event }
: event) as TEvent;
const eventObject = toEventObject(event);
const stateConfig = fsmConfig.states[value];

if (!IS_PRODUCTION) {
Expand Down Expand Up @@ -167,6 +171,9 @@ export function interpret<
return;
}
state = machine.transition(state, event);
state.actions.forEach(
({ exec }) => exec && exec(state.context, toEventObject(event))
);
listeners.forEach(listener => listener(state));
},
subscribe: (listener: StateMachine.StateListener<typeof state>) => {
Expand Down
31 changes: 31 additions & 0 deletions packages/xstate-fsm/test/fsm.test.ts
Expand Up @@ -176,4 +176,35 @@ describe('interpreter', () => {

toggleService.send('TOGGLE');
});

it('should execute actions', done => {
let executed = false;

const actionMachine = createMachine({
initial: 'active',
states: {
active: {
on: {
TOGGLE: {
target: 'inactive',
actions: () => {
executed = true;
}
}
}
},
inactive: {}
}
});

const actionService = interpret(actionMachine).start();

actionService.subscribe(() => {
if (executed) {
done();
}
});

actionService.send('TOGGLE');
});
});

0 comments on commit 53f3380

Please sign in to comment.