Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make stop() accept an expression. Fixes #1457 #1577

Merged
merged 3 commits into from
Oct 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/cyan-pants-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'xstate': minor
---

Expressions can now be used in the `stop()` action creator:

```js
// ...
actions: stop((context) => context.someActor);
```
2 changes: 1 addition & 1 deletion packages/core/src/StateNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1184,7 +1184,7 @@ class StateNode<
const invokeActions = resolvedActions.filter((action) => {
return (
action.type === actionTypes.start &&
(action as ActivityActionObject<TContext, TEvent>).activity.type ===
(action as ActivityActionObject<TContext, TEvent>).activity?.type ===
actionTypes.invoke
);
}) as Array<InvokeActionObject<TContext, TEvent>>;
Expand Down
47 changes: 41 additions & 6 deletions packages/core/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import {
ExprWithMeta,
ChooseConditon,
ChooseAction,
AnyEventObject
AnyEventObject,
Expr
} from './types';
import * as actionTypes from './actionTypes';
import {
Expand All @@ -54,6 +55,7 @@ import {
import { State } from './State';
import { StateNode } from './StateNode';
import { IS_PRODUCTION } from './environment';
import { StopAction, StopActionObject } from '.';

export { actionTypes };

Expand Down Expand Up @@ -386,20 +388,46 @@ export function start<TContext, TEvent extends EventObject>(
/**
* Stops an activity.
*
* @param activity The activity to stop.
* @param actorRef The activity to stop.
*/
export function stop<TContext, TEvent extends EventObject>(
activity: string | ActivityDefinition<TContext, TEvent>
): ActivityActionObject<TContext, TEvent> {
const activityDef = toActivityDefinition(activity);
actorRef:
| string
| ActivityDefinition<TContext, TEvent>
| Expr<TContext, TEvent, string | { id: string }>
): StopAction<TContext, TEvent> {
const activity = isFunction(actorRef)
? actorRef
: toActivityDefinition(actorRef);

return {
type: ActionTypes.Stop,
activity: activityDef,
activity,
exec: undefined
};
}

export function resolveStop<TContext, TEvent extends EventObject>(
action: StopAction<TContext, TEvent>,
context: TContext,
_event: SCXML.Event<TEvent>
): StopActionObject {
const actorRefOrString = isFunction(action.activity)
? action.activity(context, _event.data)
: action.activity;
const resolvedActorRef =
typeof actorRefOrString === 'string'
? { id: actorRefOrString }
: actorRefOrString;

const actionObject = {
type: ActionTypes.Stop as const,
activity: resolvedActorRef
};

return actionObject;
}

/**
* Updates the current context of the machine.
*
Expand Down Expand Up @@ -644,6 +672,13 @@ export function resolveActions<TContext, TEvent extends EventObject>(
updatedContext = resolved[1];
return resolved[0];
}
case actionTypes.stop: {
return resolveStop(
actionObject as StopAction<TContext, TEvent>,
updatedContext,
_event
);
}
default:
return toActionObject(actionObject, machine.options.actions);
}
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import { isInFinalState } from './stateUtils';
import { registry } from './registry';
import { registerService } from './devTools';
import * as serviceScope from './serviceScope';
import { StopActionObject } from '.';

export type StateListener<
TContext,
Expand Down Expand Up @@ -880,7 +881,7 @@ export class Interpreter<
break;
}
case actionTypes.stop: {
this.stopChild(action.activity.id);
this.stopChild((action as StopActionObject).activity.id);
break;
}

Expand Down
16 changes: 15 additions & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ export interface NullEvent {
export interface ActivityActionObject<TContext, TEvent extends EventObject>
extends ActionObject<TContext, TEvent> {
type: ActionTypes.Start | ActionTypes.Stop;
activity: ActivityDefinition<TContext, TEvent>;
activity: ActivityDefinition<TContext, TEvent> | undefined;
exec: ActionFunction<TContext, TEvent> | undefined;
}

Expand Down Expand Up @@ -856,6 +856,20 @@ export interface SendActionObject<
id: string | number;
}

export interface StopAction<TContext, TEvent extends EventObject>
extends ActionObject<TContext, TEvent> {
type: ActionTypes.Stop;
activity:
| string
| { id: string }
| Expr<TContext, TEvent, string | { id: string }>;
}

export interface StopActionObject {
type: ActionTypes.Stop;
activity: { id: string };
}

export type Expr<TContext, TEvent extends EventObject, T> = (
context: TContext,
event: TEvent
Expand Down
1 change: 0 additions & 1 deletion packages/core/test/deep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ describe('deep transitions', () => {
});

it('should exit substate when machine handles event (MACHINE_EVENT)', () => {
// console.log(deepMachine.initialState.value);
const actual = deepMachine
.transition(deepMachine.initialState, 'MACHINE_EVENT')
.actions.map((a) => `${a}`);
Expand Down
64 changes: 63 additions & 1 deletion packages/core/test/interpreter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
createMachine
} from '../src';
import { State } from '../src/State';
import { log, actionTypes, raise } from '../src/actions';
import { log, actionTypes, raise, stop } from '../src/actions';
import { isObservable } from '../src/utils';
import { interval, from } from 'rxjs';
import { map } from 'rxjs/operators';
Expand Down Expand Up @@ -1937,5 +1937,67 @@ Event: {\\"type\\":\\"SOME_EVENT\\"}"
})
.start();
});

it('stopped spawned actors should be cleaned up in parent', (done) => {
const childMachine = Machine({
initial: 'idle',
states: {
idle: {}
}
});

const parentMachine = createMachine<any>({
id: 'form',
initial: 'present',
context: {},
entry: assign({
machineRef: () => spawn(childMachine, 'machineChild'),
promiseRef: () =>
spawn(
new Promise(() => {
// ...
}),
'promiseChild'
),
observableRef: () => spawn(interval(1000), 'observableChild')
}),
states: {
present: {
on: {
NEXT: {
target: 'gone',
actions: [
stop((ctx) => ctx.machineRef),
stop((ctx) => ctx.promiseRef),
stop((ctx) => ctx.observableRef)
]
}
}
},
gone: {
type: 'final'
}
}
});

const service = interpret(parentMachine)
.onDone(() => {
expect(service.children.get('machineChild')).toBeUndefined();
expect(service.children.get('promiseChild')).toBeUndefined();
expect(service.children.get('observableChild')).toBeUndefined();
done();
})
.start();

service.subscribe((state) => {
if (state.matches('present')) {
expect(state.children).toHaveProperty('machineChild');
expect(state.children).toHaveProperty('promiseChild');
expect(state.children).toHaveProperty('observableChild');

service.send('NEXT');
}
});
});
});
});
2 changes: 0 additions & 2 deletions packages/xstate-scxml/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ function actionToSCXML(action: ActionObject<any, any>): XMLElement {
export function transitionToSCXML(
transition: TransitionDefinition<any, any>
): XMLElement {
// console.log(transition.cond!.predicate);

const elements = transition.actions.map(actionToSCXML);

return {
Expand Down