Skip to content

Commit

Permalink
Ensure stop transitions are called
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkpiano committed Mar 19, 2024
1 parent cf252d0 commit 007b78d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
22 changes: 6 additions & 16 deletions packages/core/src/stateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1647,22 +1647,6 @@ export function macrostep(
microstates.push(microstate);
}

// Handle stop event
if (event.type === XSTATE_STOP) {
nextSnapshot = cloneMachineSnapshot(
stopChildren(nextSnapshot, event, actorScope),
{
status: 'stopped'
}
);
addMicrostate(nextSnapshot, event, []);

return {
snapshot: nextSnapshot,
microstates
};
}

let nextEvent = event;

// Assume the state is at rest (no raised events)
Expand All @@ -1678,6 +1662,9 @@ export function macrostep(
// `*` shouldn't be matched, likely `xstate.error.*` shouldnt be either
// similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
nextSnapshot = cloneMachineSnapshot<typeof snapshot>(snapshot, {
// TODO: determine if this should be "stop" or "error"
// if event.type === XSTATE_STOP
// Both seem valid...
status: 'error',
error: currentEvent.error
});
Expand Down Expand Up @@ -1730,6 +1717,9 @@ export function macrostep(
addMicrostate(nextSnapshot, nextEvent, enabledTransitions);
}

nextSnapshot.status =
event.type === XSTATE_STOP ? 'stopped' : nextSnapshot.status;

if (nextSnapshot.status !== 'active') {
stopChildren(nextSnapshot, nextEvent, actorScope);
}
Expand Down
18 changes: 18 additions & 0 deletions packages/core/test/actor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from '../src/index.ts';
import { setup } from '../src/setup.ts';
import { sleep } from '@xstate-repo/jest-utils';
import { XSTATE_STOP } from '../src/constants.ts';

describe('spawning machines', () => {
const context = {
Expand Down Expand Up @@ -1011,6 +1012,23 @@ describe('actors', () => {
expect(cleanup2).toBeCalledTimes(1);
});

it('should receive an "xstate.stop" event when stopped', () => {
const spy = jest.fn();
const machine = createMachine({
on: {
[XSTATE_STOP]: {
actions: spy
}
}
});

const actor = createActor(machine).start();

actor.stop();

expect(spy).toHaveBeenCalledTimes(1);
});

describe('with actor logic', () => {
it('should work with a transition function logic', (done) => {
const countLogic = fromTransition((count: number, event: any) => {
Expand Down

0 comments on commit 007b78d

Please sign in to comment.