Skip to content

@xmachines/play-svelte-demo

Examples / @xmachines/play-svelte-demo

Svelte 5 renderer demo for @xmachines/play-svelte — 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 URL routing
  • Svelte 5 runes and mount API mapped to atoms lifecycle
  • 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-svelte-demo run dev

Then open http://localhost:3003.

Step-by-Step Code Flow

Use this order to understand the implementation:

  1. src/main.ts creates the page’s inspector with createDemoInspector(), calls definePlayer({ machine: authMachine, options: { inspect: inspector.inspect } }) to create a factory, invokes it to get an actor, starts it, and mounts App.svelte via Svelte’s mount with both actor and inspector as props.
  2. The actor is passed to App as a prop.
  3. src/App.svelte calls defineRegistry(authCatalog, { components, actions }) to build the typed registryResult — real async action handlers dispatching to actor.send().
  4. App.svelte delegates to Shell.svelte, passing actor, registryResult, and inspector.
  5. Shell.svelte renders <PlayUIProvider><PlayRenderer /></PlayUIProvider>, <NavBar>, and <DebugPanel> — the latter two observe actor atoms directly via watchAtom inside $effect, and the debug panel’s Show Inspector button calls inspector.show().
  6. HMR cleanup calls actor.stop() via import.meta.hot.dispose.
  7. Browser tests in test/browser/ validate startup and interaction behavior.
// src/main.ts (shape)
const inspector = createDemoInspector();
const createPlayer = definePlayer({
machine: authMachine,
options: { inspect: inspector.inspect },
actor: compose(PlayerActor, withRouting, withView),
});
const actor = createPlayer();
actor.start();
mount(App, { target: document.getElementById("app")!, props: { actor, inspector } });
<!-- src/App.svelte (shape) -->
<script lang="ts">
import Shell from "./components/Shell.svelte";
let { actor, inspector }: { actor: AuthActor; inspector: DemoInspector } = $props();
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
});
</script>
<Shell {actor} {registryResult} {inspector} />

Key Files

  • src/main.ts - actor creation/start and Svelte app mount with actor as prop
  • src/App.svelte - registry construction, delegates rendering to Shell.svelte
  • src/components/Shell.svelte - shared shell with PlayUIProvider + PlayRenderer, NavBar, and DebugPanel (which owns the Show Inspector button)
  • src/components/ - demo view Svelte components bound to catalog component keys
  • test/library-pattern.test.ts - architecture boundary and invariant assertions
  • test/browser/renderer-demo.browser.test.ts - 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 — Svelte 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 Svelte 5 rune reactivity internally to react precisely when actor atoms update, without ad-hoc $state stores 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 Svelte-local render state

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

Adapter Boundaries

PlayRenderer and defineRegistry stay passive infrastructure. Business validity remains actor-owned. The registry maps catalog component keys to Svelte 5 component implementations — the actor owns which key is active. The Shell.svelte component is shared with all Svelte router demos, accepting an optional router prop for prop-shape parity.

Available Scripts

These commands are defined in package.json:

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

Learn More

Type Aliases

Variables

Functions