Skip to content

Commit

Permalink
feat(phases): Support setting next phase with a function (#972)
Browse files Browse the repository at this point in the history
  • Loading branch information
jorbascrumps authored Aug 3, 2021
1 parent dfdd4c4 commit 064b750
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
15 changes: 15 additions & 0 deletions src/core/flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,21 @@ test('init', () => {
expect(state.G).toMatchObject({ done: true });
});

test('next', () => {
const flow = Flow({
phases: {
A: { start: true, next: () => 'C' },
B: {},
C: {},
},
});

let state = { ctx: flow.ctx(3) } as State;
state = flow.processEvent(state, gameEvent('endPhase'));

expect(state.ctx.phase).toEqual('C');
});

describe('endIf', () => {
test('basic', () => {
const flow = Flow({ endIf: (G) => G.win });
Expand Down
10 changes: 7 additions & 3 deletions src/core/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ export function Flow({
onEnd: HookWrapper(phaseConfig.turn.onEnd),
endIf: TriggerWrapper(phaseConfig.turn.endIf),
};

if (typeof phaseConfig.next !== 'function') {
const { next } = phaseConfig;
phaseConfig.next = () => next || null;
}
phaseConfig.wrapped.next = HookWrapper(phaseConfig.next);
}

function GetPhase(ctx: { phase: string }): PhaseConfig {
Expand Down Expand Up @@ -314,10 +320,8 @@ export function Flow({
logging.error('invalid phase: ' + arg.next);
return state;
}
} else if (phaseConfig.next !== undefined) {
ctx = { ...ctx, phase: phaseConfig.next };
} else {
ctx = { ...ctx, phase: null };
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
}

state = { ...state, ctx };
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export interface PhaseConfig<
CtxWithPlugins extends Ctx = Ctx
> {
start?: boolean;
next?: string;
next?: ((G: G, ctx: CtxWithPlugins) => string | void) | string;
onBegin?: (G: G, ctx: CtxWithPlugins) => any;
onEnd?: (G: G, ctx: CtxWithPlugins) => any;
endIf?: (G: G, ctx: CtxWithPlugins) => boolean | void | { next: string };
Expand All @@ -219,6 +219,7 @@ export interface PhaseConfig<
) => boolean | void | { next: string };
onBegin?: (state: State<G, CtxWithPlugins>) => any;
onEnd?: (state: State<G, CtxWithPlugins>) => any;
next?: (state: State<G, CtxWithPlugins>) => string | void;
};
}

Expand Down

0 comments on commit 064b750

Please sign in to comment.