Skip to content

@xmachines/play-react-demo

Examples / @xmachines/play-react-demo

React renderer demo for @xmachines/play-react — actor + PlayRenderer without a router.

License: MIT

What This Demonstrates

  • Shared auth machine reused without framework-specific business logic
  • PlayRenderer rendering actor-projected views with a typed defineRegistry catalog
  • Auth machine states drive view switching via auth.login / auth.logout events only — no play.route routing
  • Canonical atoms lifecycle surfaced through React’s rendering model
  • Non-browser invariant tests plus browser renderer coverage
  • Stately inspector attached at creation via options.inspect — the debug panel’s Show Inspector button opens the live machine in its own window
  • json-render 0.20 showcase pages driven purely by spec:
    • Overview — two data planes side by side: /context/tasks (machine context via the read-only /context projection; repeat + key, $item-filtered lists, per-row actions sending inspectable machine events) next to ephemeral store state (pushState/removeState/setState built-ins driving filter chips and toggles that survive context updates)
    • Stats — nested repeats (repeat.statePath: { $item: "members" }) over /context/teams
    • Settings — declarative field validation, the validateForm built-in, a confirm-gated resetForm host action, and onSuccess/onError chains
    • Contact — a chained named action: submit validates, then routes home on success or writes "$error.message" to state on failure

Running the Demo

From the repository root:

Terminal window
pnpm install
pnpm --filter @xmachines/play-react-demo run dev

Then open http://localhost:3001.

Step-by-Step Code Flow

Use this order to understand the implementation:

  1. src/main.tsx mounts <App />.
  2. src/App.tsx creates the page’s inspector with createDemoInspector() and the actor at module scope via definePlayer({ machine: authMachine, options: { inspect: inspector.inspect }, actor: compose(PlayerActor, withRouting, withView) })() — both created once when the module is first evaluated.
  3. defineRegistry(authCatalog, { components, actions }) builds the typed registryResult — real async action handlers dispatching to actor.send().
  4. <PlayUIProvider actor={actor} registryResult={registryResult}><PlayRenderer /></PlayUIProvider> observes actor.currentView and renders the active spec.
  5. A NavBar component observes actor atoms directly for nav visibility.
  6. <DebugPanel actor={actor} inspector={inspector} /> shows live state, auth status, and current route, plus the Show Inspector button.
  7. Browser tests in test/browser/ validate startup and interaction behavior.
// src/main.tsx (shape)
createRoot(document.getElementById("root")!).render(<App />);
// src/App.tsx (shape)
// Both actor and registryResult are module-scope singletons — created once,
// never recreated, no useMemo needed inside the component.
const inspector = createDemoInspector();
const actor: AuthActor = definePlayer({
machine: authMachine,
options: { inspect: inspector.inspect },
actor: compose(PlayerActor, withRouting, withView),
})();
actor.start();
const registryResult = defineRegistry(authCatalog, {
components: demoComponents, // one shared map — Home…NavBar plus the 0.20 Panel/Field/Button leaves
actions: createAuthActionHandlers(actor), // login/logout/route + task events + form actions
});
export function App() {
return (
<div className="demo-app" data-demo-shell>
<header className="demo-header">
<h1 className="demo-title">XMachines Play React Demo</h1>
<NavBar actor={actor} />
</header>
<main className="demo-content" data-demo-content>
<PlayUIProvider actor={actor} registryResult={registryResult}>
<PlayRenderer />
</PlayUIProvider>
</main>
<DebugPanel actor={actor} inspector={inspector} />
</div>
);
}

Key Files

  • src/main.tsx - React entry point that mounts <App />
  • src/App.tsx - actor lifecycle, registry construction, and PlayUIProvider + PlayRenderer composition
  • src/catalog.ts - catalog definition using defineCatalog from @xmachines/json-render-core with @xmachines/json-render-react/schema
  • src/components/ - demo view components bound to catalog component keys (Home, Login, Dashboard, Profile, etc.)
  • test/library-pattern.test.ts - architecture boundary and invariant assertions
  • test/browser/renderer-demo.browser.test.tsx - browser-mode renderer coverage

State Machine & Architecture Details

The demo utilizes XMachines architectural invariants:

  1. Actor Authority: View components dispatch auth.login and auth.logout events to the actor. The actor evaluates guards and transitions — React never decides which view to render.
  2. Passive Infrastructure: PlayRenderer observes actor.currentView atoms only. It holds no business state and makes no routing decisions.
  3. Atom-Only Reactivity: The bridge leverages React’s rendering model to react precisely when actor atoms update, without polluting the component tree with useState or useEffect for business logic.

Watcher Lifecycle and Cleanup Contract

This demo follows the canonical watcher lifecycle used across all @xmachines framework adapters:

  1. The atom notifies the subscription, synchronously, from the set that changed it
  2. watchAtom queues one microtask, and it drops each duplicate notification of that batch
  3. The microtask reads the actor atoms and projects React render state

One subscription lives for the whole watch, and no caller arms a watcher again. Cleanup is explicit: actor.stop() is called on component unmount via useEffect, and PlayRenderer handles internal watcher teardown natively.

Adapter Boundaries

PlayRenderer and defineRegistry stay passive infrastructure. Business validity remains actor-owned. The registry maps catalog component keys to React component implementations — the actor owns which key is active. The demo intentionally omits URL routing to isolate the renderer contract.

Available Scripts

These commands are defined in package.json:

CommandDescription
pnpm --filter @xmachines/play-react-demo run devStart Vite dev server (http://localhost:3001/)
pnpm --filter @xmachines/play-react-demo run buildBuild production bundle
pnpm --filter @xmachines/play-react-demo run previewPreview built bundle
pnpm --filter @xmachines/play-react-demo run testRun Vitest test suite
pnpm --filter @xmachines/play-react-demo run test:browserRun browser-focused Vitest suite

Learn More

Type Aliases

Variables

Functions