Skip to content

Commit 064b750

Browse files
authored
feat(phases): Support setting next phase with a function (#972)
1 parent dfdd4c4 commit 064b750

3 files changed

Lines changed: 24 additions & 4 deletions

File tree

src/core/flow.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -730,6 +730,21 @@ test('init', () => {
730730
expect(state.G).toMatchObject({ done: true });
731731
});
732732

733+
test('next', () => {
734+
const flow = Flow({
735+
phases: {
736+
A: { start: true, next: () => 'C' },
737+
B: {},
738+
C: {},
739+
},
740+
});
741+
742+
let state = { ctx: flow.ctx(3) } as State;
743+
state = flow.processEvent(state, gameEvent('endPhase'));
744+
745+
expect(state.ctx.phase).toEqual('C');
746+
});
747+
733748
describe('endIf', () => {
734749
test('basic', () => {
735750
const flow = Flow({ endIf: (G) => G.win });

src/core/flow.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,12 @@ export function Flow({
163163
onEnd: HookWrapper(phaseConfig.turn.onEnd),
164164
endIf: TriggerWrapper(phaseConfig.turn.endIf),
165165
};
166+
167+
if (typeof phaseConfig.next !== 'function') {
168+
const { next } = phaseConfig;
169+
phaseConfig.next = () => next || null;
170+
}
171+
phaseConfig.wrapped.next = HookWrapper(phaseConfig.next);
166172
}
167173

168174
function GetPhase(ctx: { phase: string }): PhaseConfig {
@@ -314,10 +320,8 @@ export function Flow({
314320
logging.error('invalid phase: ' + arg.next);
315321
return state;
316322
}
317-
} else if (phaseConfig.next !== undefined) {
318-
ctx = { ...ctx, phase: phaseConfig.next };
319323
} else {
320-
ctx = { ...ctx, phase: null };
324+
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
321325
}
322326

323327
state = { ...state, ctx };

src/types.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ export interface PhaseConfig<
207207
CtxWithPlugins extends Ctx = Ctx
208208
> {
209209
start?: boolean;
210-
next?: string;
210+
next?: ((G: G, ctx: CtxWithPlugins) => string | void) | string;
211211
onBegin?: (G: G, ctx: CtxWithPlugins) => any;
212212
onEnd?: (G: G, ctx: CtxWithPlugins) => any;
213213
endIf?: (G: G, ctx: CtxWithPlugins) => boolean | void | { next: string };
@@ -219,6 +219,7 @@ export interface PhaseConfig<
219219
) => boolean | void | { next: string };
220220
onBegin?: (state: State<G, CtxWithPlugins>) => any;
221221
onEnd?: (state: State<G, CtxWithPlugins>) => any;
222+
next?: (state: State<G, CtxWithPlugins>) => string | void;
222223
};
223224
}
224225

0 commit comments

Comments
 (0)