Skip to content

Function: definePlayer()

Documentation / @xmachines/play-xstate / definePlayer

function definePlayer<TMachine, TCatalog>(config): PlayerFactory<TMachine>;

Defined in: packages/play-xstate/src/define-player.ts:111

Create a player factory from XState machine and catalog

Factory pattern that accepts an XState v5 machine and optional UI catalog, returning a function that creates PlayerActor instances. This enables creating multiple actor instances from a single configuration, useful for testing, multi-instance scenarios, or server-side rendering.

Architectural Context: Implements Strict Separation (INV-02) by accepting the machine definition (pure business logic) separately from the catalog (UI vocabulary). The machine references component names in meta.view without importing React/framework code.

Type Parameters

Type ParameterDefault typeDescription
TMachine extends AnyStateMachine-XState v5 state machine type
TCatalogRecord<string, unknown>Optional UI component catalog type

Parameters

ParameterTypeDescription
configPlayerConfig<TMachine, TCatalog>Player configuration object

Returns

PlayerFactory<TMachine>

Factory function that creates actor instances with optional input context

Examples

Basic player factory without catalog

import { setup } from "xstate";
import { definePlayer } from "@xmachines/play-xstate";
const machine = setup({}).createMachine({
initial: "idle",
states: {
idle: { meta: { route: "/" } },
active: { meta: { route: "/active" } },
},
});
const createPlayer = definePlayer({ machine });
const actor = createPlayer();
actor.start();

Player factory with catalog and parameter-aware routing

import { setup } from "xstate";
import { defineCatalog } from "@xmachines/play-catalog";
import { definePlayer } from "@xmachines/play-xstate";
import { z } from "zod";
const catalog = defineCatalog({
HomePage: z.object({}),
ProfilePage: z.object({ userId: z.string() }),
});
const machine = setup({
types: {
context: {} as { userId: string },
events: {} as { type: "play.route"; to: string; params?: Record<string, string> },
},
}).createMachine({
initial: "home",
context: { userId: "" },
states: {
home: {
route: {},
meta: {
route: "/",
view: { component: "HomePage" },
},
},
profile: {
route: {},
meta: {
route: "/profile/:userId",
view: { component: "ProfilePage", userId: (ctx) => ctx.userId },
},
},
},
});
const createPlayer = definePlayer({ machine, catalog });
const actor = createPlayer({ userId: "user123" });
actor.start();

Multiple actor instances from single factory

const createPlayer = definePlayer({ machine, catalog });
// Create actors for different users
const alice = createPlayer({ userId: "alice" });
const bob = createPlayer({ userId: "bob" });
alice.start();
bob.start();
// Independent state machines
console.log(alice.state.get() !== bob.state.get());

See