Skip to content

Commit

Permalink
Add model.createMachine(...)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkpiano committed Jun 28, 2021
1 parent 99cc26a commit d5e5a71
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
3 changes: 3 additions & 0 deletions packages/core/src/Machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
import { StateNode } from './StateNode';
import { Model, ModelContextFrom, ModelEventsFrom } from './model';

/**
* @deprecated Use `createMachine(...)` instead.
*/
export function Machine<
TContext = any,
TEvent extends EventObject = AnyEventObject
Expand Down
13 changes: 11 additions & 2 deletions packages/core/src/model.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { assign } from './actions';
import { createMachine } from './Machine';
import type {
AssignAction,
Assigner,
PropertyAssigner,
ExtractEvent,
EventObject
EventObject,
MachineConfig,
StateMachine,
MachineOptions
} from './types';
import { mapValues } from './utils';

Expand All @@ -28,6 +32,10 @@ export interface Model<
) => AssignAction<TContext, ExtractEvent<TEvent, TEventType>>;
events: Prop<TModelCreators, 'events'>;
reset: () => AssignAction<TContext, any>;
createMachine: (
config: MachineConfig<TContext, any, TEvent> & { context: TContext },
implementations?: Partial<MachineOptions<TContext, TEvent>>
) => StateMachine<TContext, any, TEvent, any>;
}

export type ModelContextFrom<
Expand Down Expand Up @@ -107,7 +115,8 @@ export function createModel(initialContext: object, creators?): unknown {
type: eventType
}))
: undefined) as any,
reset: () => assign(initialContext)
reset: () => assign(initialContext),
createMachine
};

return model;
Expand Down
6 changes: 3 additions & 3 deletions packages/core/test/model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ describe('createModel', () => {
'updateName'
);

const machine = createMachine<typeof userModel>({
const machine = userModel.createMachine({
context: userModel.initialContext,
initial: 'active',
states: {
Expand Down Expand Up @@ -203,7 +203,7 @@ describe('createModel', () => {
it('should typecheck `createMachine` for model without creators', () => {
const toggleModel = createModel({ count: 0 });

const machine = createMachine<typeof toggleModel>({
const machine = toggleModel.createMachine({
id: 'machine',
initial: 'inactive',
// using context here is crucial to validate that it can be assigned to the inferred TContext
Expand All @@ -225,7 +225,7 @@ describe('createModel', () => {
const toggleModel = createModel({ count: 0 });

// @ts-expect-error
const m = createMachine<typeof toggleModel>({
const m = toggleModel.createMachine({
id: 'machine',
initial: 'inactive',
// missing context:
Expand Down

0 comments on commit d5e5a71

Please sign in to comment.