Skip to content

packages/core/src/features/machines/assign.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { MachineAction, MachineActionContext, MachineEvent } from './types.js';
2 
3 const assignments = new WeakMap<Function, (context: MachineActionContext<object, MachineEvent, unknown>) => object>();
4 
5 /** @internal Returns the context patch represented by an assign action. */
6 export function assignmentOf(action: Function): ((context: MachineActionContext<object, MachineEvent, unknown>) => object) | undefined {
7   return assignments.get(action);
8 }
9 
10 /**
11  * Creates an action that shallowly merges a context patch. Earlier assignments in the same
12  * transition are visible to later actions. Context itself remains application-owned data.
13  *
14  * @example
15  * ```ts
16  * const collect = assign(({ context }) => ({ coins: context.coins + 1 }));
17  * ```
18  * @param update - Produces the shallow context patch for this transition.
19  * @returns An action accepted by state entry, exit, and transition action lists.
20  * @see {@link MachineAction}
21  */
22 export function assign<Context extends object, Event extends MachineEvent, Input>(
23   update: (context: MachineActionContext<Context, Event, Input>) => Partial<Context>,
24 ): MachineAction<Context, Event, Input> {
25   const action: MachineAction<Context, Event, Input> = () => {};
26   assignments.set(action, update as unknown as (context: MachineActionContext<object, MachineEvent, unknown>) => object);
27   return action;
28 }
29 

Documentation built with @pibbl/core 0.0.2, revision 272a94a. ALPHA — NOT FOR PRODUCTION USE.