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

Implement conditional actions #1076

Merged
merged 4 commits into from
Mar 23, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
118 changes: 16 additions & 102 deletions packages/core/src/StateNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
isBuiltInEvent,
partition,
updateHistoryValue,
updateContext,
warn,
isArray,
isFunction,
Expand All @@ -24,7 +23,8 @@ import {
toSCXMLEvent,
mapContext,
toTransitionConfigArray,
normalizeTarget
normalizeTarget,
evaluateGuard
} from './utils';
import {
Event,
Expand All @@ -38,7 +38,6 @@ import {
HistoryValue,
StateNodeDefinition,
TransitionDefinition,
AssignAction,
DelayedTransitionDefinition,
ActivityDefinition,
StateNodeConfig,
Expand All @@ -50,20 +49,13 @@ import {
ActionObject,
Mapper,
PropertyMapper,
SendAction,
NullEvent,
Guard,
GuardPredicate,
GuardMeta,
MachineConfig,
PureAction,
InvokeCreator,
DoneEventObject,
SingleOrArray,
LogAction,
SendActionObject,
SpecialTargets,
RaiseAction,
SCXML,
RaiseActionObject,
ActivityActionObject,
Expand All @@ -87,14 +79,12 @@ import {
doneInvoke,
error,
toActionObject,
resolveSend,
initEvent,
toActionObjects,
resolveLog,
resolveRaise
resolveActions
} from './actions';
import { IS_PRODUCTION } from './environment';
import { DEFAULT_GUARD_TYPE, STATE_DELIMITER } from './constants';
import { STATE_DELIMITER } from './constants';
import {
getValue,
getConfiguration,
Expand Down Expand Up @@ -824,7 +814,8 @@ class StateNode<

try {
guardPassed =
!cond || this.evaluateGuard(cond, resolvedContext, _event, state);
!cond ||
evaluateGuard(this.machine, cond, resolvedContext, _event, state);
} catch (err) {
throw new Error(
`Unable to evaluate guard '${cond!.name ||
Expand Down Expand Up @@ -920,38 +911,6 @@ class StateNode<

return true;
}
private evaluateGuard(
guard: Guard<TContext, TEvent>,
context: TContext,
_event: SCXML.Event<TEvent>,
state: State<TContext, TEvent>
): boolean {
const { guards } = this.machine.options;
const guardMeta: GuardMeta<TContext, TEvent> = {
state,
cond: guard,
_event
};

// TODO: do not hardcode!
if (guard.type === DEFAULT_GUARD_TYPE) {
return (guard as GuardPredicate<TContext, TEvent>).predicate(
context,
_event.data,
guardMeta
);
}

const condFn = guards[guard.type];

if (!condFn) {
throw new Error(
`Guard '${guard.type}' is not implemented on machine '${this.machine.id}'.`
);
}

return condFn(context, _event.data, guardMeta);
}

private getActions(
transition: StateTransition<TContext, TEvent>,
Expand Down Expand Up @@ -1177,57 +1136,12 @@ class StateNode<
}
}

const [assignActions, otherActions] = partition(
actions,
(action): action is AssignAction<TContext, TEvent> =>
action.type === actionTypes.assign
);

const updatedContext = assignActions.length
? updateContext(currentContext, _event, assignActions, currentState)
: currentContext;

const resolvedActions = flatten(
otherActions.map(actionObject => {
switch (actionObject.type) {
case actionTypes.raise:
return resolveRaise(actionObject as RaiseAction<TEvent>);
case actionTypes.send:
const sendAction = resolveSend(
actionObject as SendAction<TContext, TEvent>,
updatedContext,
_event,
this.machine.options.delays
) as ActionObject<TContext, TEvent>; // TODO: fix ActionTypes.Init

if (!IS_PRODUCTION) {
// warn after resolving as we can create better contextual message here
warn(
!isString(actionObject.delay) ||
typeof sendAction.delay === 'number',
// tslint:disable-next-line:max-line-length
`No delay reference for delay expression '${actionObject.delay}' was found on machine '${this.machine.id}'`
);
}

return sendAction;
case actionTypes.log:
return resolveLog(
actionObject as LogAction<TContext, TEvent>,
updatedContext,
_event
);
case actionTypes.pure:
return (
(actionObject as PureAction<TContext, TEvent>).get(
updatedContext,
_event.data
) || []
);
default:
return toActionObject(actionObject, this.options.actions);
}
})
const [resolvedActions, updatedContext] = resolveActions(
this,
currentState,
currentContext,
_event,
actions
);

const [raisedEvents, nonRaisedActions] = partition(
Expand Down Expand Up @@ -1297,7 +1211,7 @@ class StateNode<
!resolvedStateValue || stateTransition.source
? currentState
: undefined,
actions: resolvedStateValue ? nonRaisedActions : [],
actions: resolvedStateValue ? nonRaisedActions : ([] as any[]),
activities: resolvedStateValue
? activities
: currentState
Expand All @@ -1315,8 +1229,9 @@ class StateNode<
done: isDone
});

nextState.changed =
_event.name === actionTypes.update || !!assignActions.length;
const didUpdateContext = currentContext !== updatedContext;

nextState.changed = _event.name === actionTypes.update || didUpdateContext;

// Dispose of penultimate histories to prevent memory leaks
const { history } = nextState;
Expand Down Expand Up @@ -1360,7 +1275,6 @@ class StateNode<
maybeNextState.changed ||
(history
? !!maybeNextState.actions.length ||
!!assignActions.length ||
typeof history.value !== typeof maybeNextState.value ||
!stateValuesEqual(maybeNextState.value, history.value)
: undefined);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/actionTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ export const errorExecution = ActionTypes.ErrorExecution;
export const errorPlatform = ActionTypes.ErrorPlatform;
export const error = ActionTypes.ErrorCustom;
export const update = ActionTypes.Update;
export const decide = ActionTypes.Decide;
export const pure = ActionTypes.Pure;
110 changes: 108 additions & 2 deletions packages/core/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,29 @@ import {
LogActionObject,
DelayFunctionMap,
SCXML,
ExprWithMeta
ExprWithMeta,
DecideConditon,
DecideAction
} from './types';
import * as actionTypes from './actionTypes';
import {
getEventType,
isFunction,
isString,
toEventObject,
toSCXMLEvent
toSCXMLEvent,
partition,
flatten,
updateContext,
warn,
toGuard,
evaluateGuard,
toArray
} from './utils';
import { isArray } from './utils';
import { State } from './State';
import { StateNode } from './StateNode';
import { IS_PRODUCTION } from './environment';

export { actionTypes };

Expand Down Expand Up @@ -505,3 +517,97 @@ export function escalate<
}
);
}

export function decide<TContext, TEvent extends EventObject>(
conds: DecideConditon<TContext, TEvent>[]
): DecideAction<TContext, TEvent> {
return {
type: ActionTypes.Decide,
conds
};
}

export function resolveActions<TContext, TEvent extends EventObject>(
machine: StateNode<TContext, any, TEvent>,
currentState: State<TContext, TEvent> | undefined,
currentContext: TContext,
_event: SCXML.Event<TEvent>,
actions: ActionObject<TContext, TEvent>[]
): [ActionObject<TContext, TEvent>[], TContext] {
const [assignActions, otherActions] = partition(
actions,
(action): action is AssignAction<TContext, TEvent> =>
action.type === actionTypes.assign
);

let updatedContext = assignActions.length
? updateContext(currentContext, _event, assignActions, currentState)
: currentContext;

const resolvedActions = flatten(
otherActions.map(actionObject => {
switch (actionObject.type) {
case actionTypes.raise:
return resolveRaise(actionObject as RaiseAction<TEvent>);
case actionTypes.send:
const sendAction = resolveSend(
actionObject as SendAction<TContext, TEvent>,
updatedContext,
_event,
machine.options.delays
) as ActionObject<TContext, TEvent>; // TODO: fix ActionTypes.Init

if (!IS_PRODUCTION) {
// warn after resolving as we can create better contextual message here
warn(
!isString(actionObject.delay) ||
typeof sendAction.delay === 'number',
// tslint:disable-next-line:max-line-length
`No delay reference for delay expression '${actionObject.delay}' was found on machine '${machine.id}'`
);
}

return sendAction;
case actionTypes.log:
return resolveLog(
actionObject as LogAction<TContext, TEvent>,
updatedContext,
_event
);
case actionTypes.decide:{
const decideAction = actionObject as DecideAction<TContext, TEvent>
const matchedActions = decideAction.conds.find(
condition => {
const guard = toGuard(condition.cond, machine.options.guards)
return !guard || evaluateGuard(machine, guard, updatedContext, _event, currentState as any)
}
)?.actions;

if (!matchedActions) {
return []
}

const resolved = resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions)))
Andarist marked this conversation as resolved.
Show resolved Hide resolved
updatedContext = resolved[1]
return resolved[0]
}
case actionTypes.pure:{
const matchedActions = (
(actionObject as PureAction<TContext, TEvent>).get(
updatedContext,
_event.data
))
if (!matchedActions) {
return []
}
const resolved = resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions)))
updatedContext = resolved[1]
return resolved[0]
}
default:
return toActionObject(actionObject, machine.options.actions);
}
})
);
return [resolvedActions, updatedContext];
}
Loading