@xmachines/play-tanstack-solid-router
v2.1.0
Published
TanStack Solid Router adapter for XMachines Universal Player Architecture
Readme
@xmachines/play-tanstack-solid-router
TanStack Solid Router adapter for XMachines Universal Player Architecture
This package integrates TanStack Solid Router with the TC39 Signals. 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 signal (
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-js
pnpm add @xmachines/play-tanstack-solid-router @xmachines/play-routerPeer dependencies:
@tanstack/solid-router^1.168.7solid-js^1.8.0xstate^5.31.0
Current Exports
TanStackSolidRouterBridge— the primary adapter classPlayRouterProvider— the Solid component that manages the bridge lifecyclePlayRouterProviderProps,TanStackRouterInstance(types)PlayActor— the canonical actor shape (AbstractActor & Routable & Viewable) from@xmachines/play-router. Use it for the type of a renderer callback ofPlayRouterProviderRoutableActor— the deprecated alias ofPlayActor. UsePlayActorfrom@xmachines/play-routerRouteMap,createRouteMap,RouteMapping,RouteMapOptions(re-exported from@xmachines/play-router)TanStackRouterLike(type)RouterBridge,PlayRouteEvent(types)
URLPattern Support
This package matches each route pattern with the URLPattern API, through @xmachines/play-router.
URLPattern is native in Node.js 24+ and in a modern browser (Chrome 95+, Firefox 117+, Safari 16.4+). In an older environment, load a polyfill before you import this package. See @xmachines/play-router for the details.
Quick Start
import { createRouter, createRootRoute, createRoute } from "@tanstack/solid-router";
import { createMachine } from "xstate";
import { definePlayer, formatPlayRouteTransitions } from "@xmachines/play-xstate";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router";
import { TanStackSolidRouterBridge, createRouteMap } from "@xmachines/play-tanstack-solid-router";
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 routes
const 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) });
const actor = definePlayer({ machine })();
actor.start();
const bridge = new TanStackSolidRouterBridge(router, actor, routeMap);
bridge.connect();
// later
bridge.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;
dispose(): void; // alias for disconnect()
}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.
PlayRouterProvider
This Solid component creates a TanStackSolidRouterBridge, connects it, and cleans it up for you.
interface PlayRouterProviderProps<TActor extends PlayActor = PlayActor> {
/** 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
These two exports map each state ID to a URL path, and each URL back to a state ID.
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-tanstack-solid-router";
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, createRouteMap } from "@xmachines/play-tanstack-solid-router";
import { definePlayer } from "@xmachines/play-xstate";
import { extractMachineRoutes, getRoutableRoutes } from "@xmachines/play-router";
import { authMachine } from "./auth-machine.js"; // your routable machine (states carry meta.route)
const createPlayer = definePlayer({ machine: authMachine });
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.currentRoutesignal, 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.
Testing
Run tests for this package in isolation:
pnpm --filter @xmachines/play-tanstack-solid-router testOr from the package directory:
pnpm testBrowser tests (test/browser/**/*.browser.test.ts) run in real Chromium through Playwright. They cover the asynchronous sequences that jsdom cannot reproduce: BACK and FORWARD navigation through router.history.subscribe, echo suppression under real microtask timing, the check of each navigate({ to }) call, and subscriber teardown on disconnect() and on dispose().
# Run browser tests only
pnpm exec vitest --config vitest.browser.config.ts --project play-tanstack-solid-router-browserCoverage thresholds: lines 80%, functions 80%, branches 70%, statements 80%.
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
License
MIT — see LICENSE.
