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

[core] Modeling events with createModel() #1955

Merged
merged 15 commits into from
Mar 17, 2021
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
47 changes: 47 additions & 0 deletions .changeset/fair-lemons-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
'xstate': minor
---

Event creators can now be modeled inside of the 2nd argument of `createModel()`, and types for both `context` and `events` will be inferred properly in `createMachine()` when given the `typeof model` as the first generic parameter.

```ts
import { createModel } from 'xstate/lib/model';

const userModel = createModel(
// initial context
{
name: 'David',
age: 30
},
// creators (just events for now)
{
events: {
updateName: (value: string) => ({ value }),
updateAge: (value: number) => ({ value }),
anotherEvent: () => ({}) // no payload
}
}
);

const machine = createMachine<typeof userModel>({
context: userModel.initialContext,
initial: 'active',
states: {
active: {
on: {
updateName: {
/* ... */
},
updateAge: {
/* ... */
}
}
}
}
});

const nextState = machine.transition(
undefined,
userModel.events.updateName('David')
);
```
18 changes: 18 additions & 0 deletions packages/core/src/Machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Typestate
} from './types';
import { StateNode } from './StateNode';
import { Model, ModelContextFrom, ModelEventsFrom } from './model';

export function Machine<
TContext = any,
Expand Down Expand Up @@ -48,6 +49,23 @@ export function Machine<
) as StateMachine<TContext, TStateSchema, TEvent>;
}

export function createMachine<
TModel extends Model<any, any, any>,
TContext = ModelContextFrom<TModel>,
TEvent extends EventObject = ModelEventsFrom<TModel>,
TTypestate extends Typestate<TContext> = { value: any; context: TContext }
>(
config: MachineConfig<TContext, any, TEvent>,
options?: Partial<MachineOptions<TContext, TEvent>>
): StateMachine<TContext, any, TEvent, TTypestate>;
export function createMachine<
TContext,
TEvent extends EventObject = AnyEventObject,
TTypestate extends Typestate<TContext> = { value: any; context: TContext }
>(
config: MachineConfig<TContext, any, TEvent>,
options?: Partial<MachineOptions<TContext, TEvent>>
): StateMachine<TContext, any, TEvent, TTypestate>;
export function createMachine<
TContext,
TEvent extends EventObject = AnyEventObject,
Expand Down
89 changes: 86 additions & 3 deletions packages/core/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,107 @@ import type {
ExtractEvent,
EventObject
} from './types';
import { mapValues } from './utils';

export interface ContextModel<TContext, TEvent extends EventObject> {
type AnyFunction = (...args: any[]) => any;

type Cast<A1 extends any, A2 extends any> = A1 extends A2 ? A1 : A2;
type Compute<A extends any> = { [K in keyof A]: A[K] } & unknown;
type Prop<T, K> = K extends keyof T ? T[K] : never;

export interface Model<
TContext,
TEvent extends EventObject,
TModelCreators = never
> {
initialContext: TContext;
assign: <TEventType extends TEvent['type'] = TEvent['type']>(
assigner:
| Assigner<TContext, ExtractEvent<TEvent, TEventType>>
| PropertyAssigner<TContext, ExtractEvent<TEvent, TEventType>>,
eventType?: TEventType
) => AssignAction<TContext, ExtractEvent<TEvent, TEventType>>;
events: Prop<TModelCreators, 'events'>;
reset: () => AssignAction<TContext, any>;
}

export type ModelContextFrom<
TModel extends Model<any, any, any>
> = TModel extends Model<infer TContext, any, any> ? TContext : never;

export type ModelEventsFrom<
TModel extends Model<any, any, any>
> = TModel extends Model<any, infer TEvent, any> ? TEvent : never;

type EventCreator<
Self extends AnyFunction,
Return = ReturnType<Self>
> = Return extends object
? Return extends {
type: any;
}
? "An event creator can't return an object with a type property"
: Self
: 'An event creator must return an object';

type EventCreators<Self> = {
[K in keyof Self]: Self[K] extends AnyFunction
? EventCreator<Self[K]>
: 'An event creator must be a function';
};

type ModelCreators<Self> = {
events: EventCreators<Prop<Self, 'events'>>;
};

type FinalEventCreators<Self> = {
[K in keyof Self]: Self[K] extends AnyFunction
? (
...args: Parameters<Self[K]>
) => Compute<ReturnType<Self[K]> & { type: K }>
: never;
};

type FinalModelCreators<Self> = {
events: FinalEventCreators<Prop<Self, 'events'>>;
};

type EventFromEventCreators<EventCreators> = {
[K in keyof EventCreators]: EventCreators[K] extends AnyFunction
? ReturnType<EventCreators[K]>
: never;
}[keyof EventCreators];

export function createModel<TContext, TEvent extends EventObject>(
initialContext: TContext
): ContextModel<TContext, TEvent> {
const model: ContextModel<TContext, TEvent> = {
): Model<TContext, TEvent, never>;
export function createModel<
TContext,
TModelCreators extends ModelCreators<TModelCreators>,
TFinalModelCreators = FinalModelCreators<TModelCreators>
>(
initialContext: TContext,
creators: TModelCreators
): Model<
TContext,
Cast<
EventFromEventCreators<Prop<TFinalModelCreators, 'events'>>,
EventObject
>,
TFinalModelCreators
>;
export function createModel(initialContext: object, creators?): unknown {
const eventCreators = creators?.events;

const model: Model<any, any, any> = {
initialContext,
assign,
events: (eventCreators
? mapValues(eventCreators, (fn, eventType) => (...args: any[]) => ({
...fn(...args),
type: eventType
}))
: undefined) as any,
reset: () => assign(initialContext)
};

Expand Down
7 changes: 4 additions & 3 deletions packages/core/test/interpreter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1980,9 +1980,10 @@ Event: {\\"type\\":\\"SOME_EVENT\\"}"
NEXT: {
target: 'gone',
actions: [
stop((ctx) => ctx.machineRef),
stop((ctx) => ctx.promiseRef),
stop((ctx) => ctx.observableRef)
// TODO: type these correctly in TContext
stop((ctx) => (ctx as any).machineRef),
stop((ctx) => (ctx as any).promiseRef),
stop((ctx) => (ctx as any).observableRef)
]
}
}
Expand Down
69 changes: 69 additions & 0 deletions packages/core/test/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,73 @@ describe('createModel', () => {

expect(resetState.context).toEqual(userModel.initialContext);
});

it('can model events', () => {
const userModel = createModel(
{
name: 'David',
age: 30
},
{
events: {
updateName: (value: string) => ({ value }),
updateAge: (value: number) => {
const payload = {
value
};
(payload as any).type = 'this should be overwritten';
return payload;
},
anotherEvent: () => ({})
}
}
);

// Example of an externally-defined assign action
const assignName = userModel.assign(
{
name: (_, event) => {
return event.value;
}
},
'updateName'
);

const machine = createMachine<typeof userModel>({
context: userModel.initialContext,
initial: 'active',
states: {
active: {
on: {
updateName: {
// pre-defined assign action
actions: assignName
},
updateAge: {
// inline assign action
actions: userModel.assign((_, e) => {
return {
age: e.value
};
})
}
}
}
}
});

let updatedState = machine.transition(
undefined,
userModel.events.updateName('Anyone')
);

expect(updatedState.context.name).toEqual('Anyone');

updatedState = machine.transition(
updatedState,
userModel.events.updateAge(42)
);

expect(updatedState.context.age).toEqual(42);
});
});
4 changes: 2 additions & 2 deletions packages/xstate-react/test/useMachine.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ describe('useMachine (strict mode)', () => {
});

it('should not miss initial synchronous updates', () => {
const m = createMachine<any>({
const m = createMachine<{ count: number }>({
initial: 'idle',
context: {
count: 0
Expand All @@ -749,7 +749,7 @@ describe('useMachine (strict mode)', () => {

const App = () => {
const [state] = useMachine(m);
return state.context.count;
return <>{state.context.count}</>;
};

const { container } = render(<App />);
Expand Down
2 changes: 1 addition & 1 deletion packages/xstate-react/test/useService.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ describe('useService hook', () => {

it('service should accept the 2-argument variant', () => {
const service = interpret(
createMachine<any, { type: 'EVENT'; value: number }>({
createMachine<{ value: number }, { type: 'EVENT'; value: number }>({
initial: 'first',
states: {
first: {
Expand Down