@xmachines/play-tanstack-solid-router
API / @xmachines/play-tanstack-solid-router
TanStack Solid Router adapter for XMachines Universal Player Architecture
This package integrates TanStack Solid Router with the atoms. The logic then drives the navigation through the Solid.js reactivity.
Overview
@xmachines/play-tanstack-solid-router connects a Play actor to TanStack Solid Router through TanStackSolidRouterBridge.
The bridge extends RouterBridgeBase from @xmachines/play-router. Each adapter therefore behaves in the same way in every framework:
- The actor route atom (
actor.currentRoute) drives the router navigation. - Each router history event sends a
play.routeintent to the actor. - The actor keeps the ownership of each guarded state transition (Actor Authority).
RouterBridgeBasestops a circular update.
Installation
pnpm add @tanstack/solid-router solid-jspnpm add @xmachines/play-tanstack-solid-router @xmachines/play-router @xmachines/core @xmachines/play @xmachines/play-atom@xmachines/play-router names @xmachines/core, @xmachines/play and @xmachines/play-atom as peers, so the command installs them with this package.
Peer dependencies:
@tanstack/solid-router^1.168.7solid-js^1.8.0
Current Exports
TanStackSolidRouterBridge— the primary adapter classPlayRouterProvider— the Solid component that manages the bridge lifecyclePlayRouterProviderProps,TanStackRouterInstance(types)RoutableActor—currentRoute,initialRouteandsend, from@xmachines/play-router. It names no view: routing implies no rendering. A renderer callback that readscurrentViewdeclares its own actor type, and the constraint keeps it wholeRouteMap,RouteMapping,RouteMapOptions(re-exported from@xmachines/play-router)createRouteMap(re-exported from@xmachines/play-router/xstate)TanStackRouterLike(type)RouterBridge,PlayRouteEvent(types)
Quick Start
import { createRouter, createRootRoute, createRoute } from "@tanstack/solid-router";import { createMachine } from "xstate";import { definePlayer, compose, PlayerActor } from "@xmachines/play-xstate";import { formatPlayRouteTransitions, withRouting } from "@xmachines/play-xstate/routing";import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router/xstate";import { TanStackSolidRouterBridge } from "@xmachines/play-tanstack-solid-router";import { createRouteMap } from "@xmachines/play-router/xstate";const machine = createMachine( formatPlayRouteTransitions({ id: "app", initial: "home", states: { home: { id: "home", meta: { route: "/" } }, about: { id: "about", meta: { route: "/about" } }, }, }),);
const routeMap = createRouteMap(machine);
// Mirror the machine's routable states as TanStack routesconst rootRoute = createRootRoute();const tanstackRoutes = getRoutableRoutes(extractMachineRoutes(machine)).map((route) => createRoute({ getParentRoute: () => rootRoute, path: route.fullPath.replace(/:(\w+)/g, "$$$1"), component: () => null, }),);const router = createRouter({ routeTree: rootRoute.addChildren(tanstackRoutes) });
// The bridge needs the routing capabilityconst actor = definePlayer({ machine, actor: compose(PlayerActor, withRouting) })();actor.start();
const bridge = new TanStackSolidRouterBridge(router, actor, routeMap);bridge.connect();
// laterbridge.disconnect();Solid convenience wrapper
Use PlayRouterProvider when you want a component to manage the bridge lifecycle:
import { PlayRouterProvider } from "@xmachines/play-tanstack-solid-router";import { RouterProvider } from "@tanstack/solid-router";
// actor, router, and routeMap from the Quick Start above<PlayRouterProvider actor={actor} router={router} routeMap={routeMap} renderer={(currentActor, currentRouter) => ( <RouterProvider router={currentRouter}>{/* your app here */}</RouterProvider> )}/>;API
TanStackSolidRouterBridge
The primary adapter class. It extends RouterBridgeBase.
class TanStackSolidRouterBridge { constructor(router: TanStackRouterLike, actor: RoutableActor, routeMap: RouteMap); connect(): void; disconnect(): void;}Behavior:
connect()— subscribes torouter.history, sets the actor state fromrouter.history.locationfor a deep link, and then watchesactor.currentRoutefor a state-driven navigation.disconnect()— cancels the subscription to the history and stops all the synchronization.- It navigates with
router.navigate({ to: path }). - It subscribes with
router.history.subscribe. This covers PUSH, POP, BACK, FORWARD, REPLACE, and GO, and it works when no<RouterProvider>is mounted. - It waits for the
router.load()of a history event before it synchronizes the actor. A mounted<RouterProvider>defers the refresh ofrouter.latestLocation, and without the wait TanStack drops the corrective navigation for a refused URL. See the@xmachines/play-tanstack-routerREADME for the details.
PlayRouterProvider
This Solid component creates a TanStackSolidRouterBridge, connects it, and cleans it up for you.
interface PlayRouterProviderProps<TActor extends RoutableActor = RoutableActor> { /** The actor to sync with TanStack Solid Router. */ actor: TActor; /** The TanStack Router instance returned by `createRouter`. */ router: TanStackRouterInstance; /** Bidirectional route map for state ID ↔ URL path lookups. */ routeMap: RouteMap; /** Renderer callback receives the same concrete actor type that was passed in. */ renderer: (actor: TActor, router: TanStackRouterInstance) => JSX.Element;}The component creates the bridge synchronously, during its own evaluation, because this is the execution model of Solid. It disconnects the bridge in onCleanup, when Solid disposes of the component.
RouteMap, and createRouteMap of @xmachines/play-router/xstate
They map each state ID to a URL path, and each URL back to a state ID. This package exports RouteMap, and it re-exports createRouteMap never: the barrel names no state machine.
const routeMap = new RouteMap([ { stateId: "home", path: "/" }, { stateId: "profile", path: "/profile/:userId" }, { stateId: "settings", path: "/settings/:section?" },]);
routeMap.getStateIdByPath("/profile/123"); // "profile"routeMap.getPathByStateId("home"); // "/"routeMap.getStateIdByPath("/unknown"); // nullOr build from a machine directly:
import { createRouteMap } from "@xmachines/play-router/xstate";const routeMap = createRouteMap(machine); // machine: your routable machine (states carry meta.route)getStateIdByPath returns null, not undefined, for a path that it cannot match.
Usage Patterns
Dynamic Routes with Parameters
const routeMap = new RouteMap([ { stateId: "post", path: "/users/:userId/posts/:postId" }, { stateId: "settings", path: "/settings/:section?" },]);
// Params are extracted and forwarded in the play.route event:// { type: "play.route", to: "#post", params: { userId: "123", postId: "456" }, query: {} }Protected Routes and Guards
The auth guards are inside the state machine only. Unauthorized content therefore never appears, not even for a moment:
const machineConfig = { states: { dashboard: { meta: { route: "/dashboard" }, always: { guard: ({ context }) => !context.isAuthenticated, target: "login", }, }, },};A user navigates to /dashboard, and the user is not authenticated:
- TanStack Router updates the location.
- The bridge receives the change and sends
play.routeto the actor. - The actor evaluates the guard. The guard refuses the transition, and the actor moves to
login. - The bridge reads the new actor route (
/login). - The bridge calls
router.navigate({ to: "/login" }).
Full App Example
import { createRouter, RouterProvider, createRootRoute, createRoute } from "@tanstack/solid-router";import { onCleanup } from "solid-js";import { PlayRouterProvider } from "@xmachines/play-tanstack-solid-router";import { createRouteMap } from "@xmachines/play-router/xstate";import { definePlayer, compose, PlayerActor } from "@xmachines/play-xstate";import { withRouting } from "@xmachines/play-xstate/routing";import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router/xstate";import { authMachine } from "./auth-machine.js"; // your routable machine (states carry meta.route)
const createPlayer = definePlayer({ machine: authMachine, actor: compose(PlayerActor, withRouting),});const actor = createPlayer();actor.start();
const routeMap = createRouteMap(authMachine);const routeTree = extractMachineRoutes(authMachine);const routes = getRoutableRoutes(routeTree);
const rootRoute = createRootRoute({ component: () => { onCleanup(() => actor.stop()); return ( <PlayRouterProvider actor={actor} router={router} routeMap={routeMap} renderer={(currentActor, currentRouter) => ( /* your shell/renderer here */ <div /> )} /> ); },});
const tanstackRoutes = routes.map((route) => createRoute({ getParentRoute: () => rootRoute, path: route.fullPath.replace(/:(\w+)/g, "$$$1"), component: () => null, }),);
export const router = createRouter({ routeTree: rootRoute.addChildren(tanstackRoutes) });
export default function App() { return <RouterProvider router={router} />;}Architecture
Bridge-first data flow:
RouterBridgeBase.connect()does the first synchronization between the actor and the router. It sends both the pathname and the query string ofrouter.history.locationto the actor.- Each actor route update, through the
actor.currentRouteatom, calls the TanStack navigation (router.navigate({ to })). - The bridge subscribes to the TanStack history updates. It converts each update into a
play.routeevent, then sends the event to the actor. - The guards of the actor accept or refuse each transition. The infrastructure reflects the state that results.
The routing infrastructure therefore stays passive, and the state machine keeps the control of the business logic.
Related Packages
- @xmachines/play-router — core router primitives and
RouterBridgeBase - @xmachines/play-tanstack-react-router — the same adapter for TanStack Router (React)
- @xmachines/play-solid — SolidJS renderer
- @xmachines/play-solid-router — native
@solidjs/routeradapter - @xmachines/play-xstate — XState v5 player factory
Learn More
- Demo
- SolidJS renderer
- Routing guide — the URLPattern language that a
meta.routepath declares
License
MIT — see LICENSE.