@molecule/app-routing-solid-router

Provider bond · routing · App (browser) · v1.4.1 · Apache-2.0

Solid Router provider for @molecule/app-routing

npm install @molecule/app-routing-solid-router

npm · Source on GitHub · Implements @molecule/app-routing

How it works

@molecule/app-routing-solid-router is a provider bond on the app (browser) side: it implements the routing core interface (@molecule/app-routing) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { MemoryRouter, Route } from '@solidjs/router'
import { MoleculeProvider } from '@molecule/app-solid'
import { createSolidRouter } from '@molecule/app-routing-solid-router'

;<MemoryRouter
  history={memory}
  root={(props) => (
    <MoleculeProvider router={createSolidRouter({ history: memory })}>
      {props.children}
    </MoleculeProvider>
  )}
>
  <Route path="/users/:id" component={User} />
  <Route path="*rest" component={NotFound} />
</MemoryRouter>

Works with: @molecule/app-bond, @molecule/app-i18n, @molecule/app-routing, @molecule/app-solid

Reference

Solid Router provider for @molecule/app-routing.

Implements the molecule Router over @solidjs/router, so molecule packages navigate the app's real Solid Router. Build it from a component under the router and hand it to MoleculeProvider, so every molecule package shares it:

With HTTP and auth clients bonded, the app's router (createSolidRouter() in the router's root, or MoleculeRouterProvider) replaces the current URL with /login after a credential-free GET receives a 401 and the session is confirmed signed out, as React's BrowserRouter does. location.state.from holds the original location. Set signInPath to use a different sign-in route or pass signInPath: false to opt out.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { MemoryRouter, Route } from '@solidjs/router'
import { MoleculeProvider } from '@molecule/app-solid'
import { createSolidRouter } from '@molecule/app-routing-solid-router'

;<MemoryRouter
  history={memory}
  root={(props) => (
    <MoleculeProvider router={createSolidRouter({ history: memory })}>
      {props.children}
    </MoleculeProvider>
  )}
>
  <Route path="/users/:id" component={User} />
  <Route path="*rest" component={NotFound} />
</MemoryRouter>

Type

provider

Installation

npm install @molecule/app-routing-solid-router @molecule/app-bond @molecule/app-i18n @molecule/app-routing @molecule/app-solid @solidjs/router solid-js

API

Interfaces

ListRouteNavItem

A named list view and its navigation label.

interface ListRouteNavItem extends ListRouteSelection {
  /** Translated label, optionally including an icon. */
  label: JSX.Element
  /** Path parameters for this destination; current route parameters are otherwise retained. */
  params?: RouteParams
  /** Keep the choice visible but prevent navigation. Authorization still belongs in the route. */
  disabled?: boolean
}

ListRouteNavItemState

URL-derived state available to the app's link styling.

interface ListRouteNavItemState<Selection extends string = string> {
  /** The app-owned selection key. */
  selection: Selection
  /** Whether the current URL selects this view. */
  active: boolean
  /** Whether navigation is disabled for this choice. */
  disabled: boolean
}

ListRouteNavProps

Props for URL-backed list navigation; local content panels use the UI package's Tabs instead.

interface ListRouteNavProps<Selection extends string = string> extends Omit<
  JSX.HTMLAttributes<HTMLElement>,
  'children'
> {
  /** Accessible navigation name, translated by the app. */
  'aria-label': string
  /** Every declared view stays visible on every route; labels and targets share one declaration. */
  selections: Record<Selection, ListRouteNavItem>
  /** Tie-breaker or fallback, with the same meaning as useListRoute's defaultSelection. */
  defaultSelection?: NoInfer<Selection>
  /** Pagination query key to remove on selection, defaulting to page. */
  pageParam?: string
  /** Required for protected selections, with the same readiness rules as useListRoute. */
  auth?: ListRouteAuth
  /** Render links in a list, with optional classes for the list and its items. */
  list?: { className?: string; itemClassName?: string }
  /** App-owned styling, resolved from its class map. */
  linkClassName?: string | ((state: ListRouteNavItemState<Selection>) => string | undefined)
  /** Render the list beside the nav using its exact URL state, including resolved item params. */
  children?: (route: ListRouteResult<string, Selection>) => JSX.Element
}

LazyPageOptions

Options for lazyPage.

interface LazyPageOptions {
  /**
   * What the page's area shows while its code loads. Defaults to nothing.
   *
   * Give it as a getter (`get fallback() { return <Spinner /> }`) when the fallback
   * builds DOM of its own: a page's boundary can be shown more than once, and a getter
   * makes a fresh element for each showing.
   */
  fallback?: JSX.Element
}

MemoryRouterProps

Props for MemoryRouter: Solid Router's, with React Router's initialEntries.

interface MemoryRouterProps extends Omit<SolidMemoryRouterProps, 'history'> {
  /** The memory history to run on. One is made from `initialEntries` when it is omitted. */
  history?: SolidMemoryHistory
  /** The paths a new history starts at; the last one is current. Defaults to `['/']`. */
  initialEntries?: string[]
}

MoleculeRouterProviderProps

Props for MoleculeRouterProvider, the same as React's provider plus the memory history a Solid memory router needs (React Router supplies it itself).

interface MoleculeRouterProviderProps {
  /**
   * Child components, rendered inside the router context the hooks read.
   */
  children: JSX.Element

  /**
   * Optional route definitions for named routes.
   */
  routes?: RouteDefinition[]

  /**
   * Callback when router is ready: called once with the bonded router.
   */
  onRouterReady?: (router: Router) => void

  /**
   * The memory history the `<MemoryRouter history={…}>` above this provider uses, from
   * `createSolidMemoryHistory`. Browser routers (`<Router>`, `<HashRouter>`) need none:
   * their entries live in `history.state`. It is required for a memory router to report
   * each entry's state and key.
   */
  history?: SolidMemoryHistory

  /**
   * Path to replace the current location with on a signed-out GET 401. Defaults to
   * `/login`; `false` turns the redirect off.
   */
  signInPath?: string | false
}

SolidMemoryEntry

One entry of a SolidMemoryHistory: the state its navigation carried and its key.

interface SolidMemoryEntry {
  /** The state the navigation that created the entry carried, or `undefined`. */
  state: unknown
  /** The entry's location key: new for every entry, the same each time the entry is current. */
  key: string
}

SolidMemoryHistory

The memory history a Solid <MemoryRouter history={…}> runs on, as createSolidMemoryHistory makes it: Solid's MemoryHistory shape plus each entry's state and key. Solid Router reports no navigation action, so Back, Forward and go on a memory router are only observable through the history's own listen.

interface SolidMemoryHistory {
  /** The current entry's URL (`/users/7?x=1#top`). */
  get(): string
  /** The current entry's state and key. */
  entry(): SolidMemoryEntry
  /** Adds (or, with `replace`, replaces) an entry; Solid Router calls it to navigate. */
  set(change: LocationChange): void
  /** Moves one entry back. */
  back(): void
  /** Moves one entry forward. */
  forward(): void
  /** Moves `delta` entries, clamped to the history. */
  go(delta: number): void
  /**
   * Subscribes to the history's moves; each call passes the entry moved to.
   *
   * @param listener - Called after every `set` and every move.
   * @returns A function that unsubscribes the listener.
   */
  listen(listener: (value: string) => void): () => void
}

SolidRouterOptions

Solid Router-specific options for createSolidRouter.

interface SolidRouterOptions {
  /**
   * Initial route definitions for named routes (`Router.navigateTo`) and route params.
   */
  routes?: RouteDefinition[]

  /**
   * The memory history a Solid Router `<MemoryRouter history={…}>` uses, from
   * `createSolidMemoryHistory`: the router reads each entry's state and key from it
   * and hears its moves as pops. Under the bond's own `MemoryRouter` the history comes
   * from it, and browser routers (`<Router>`, `<HashRouter>`) need none: their entries
   * live in `history.state` and their pops arrive as `popstate`.
   */
  history?: SolidMemoryHistory

  /**
   * Path to replace the current location with on a signed-out GET 401. Defaults to
   * `/login`; `false` turns the redirect off. `useMoleculeRouter`'s routers never apply it.
   */
  signInPath?: string | false
}

UseListRouteResult

What useListRoute returns: each list-state field as an accessor, and the link builder and navigation actions as plain functions — the shape @molecule/app-solid's useListRoute returns (React's ListRouteResult under Solid's value shape).

interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** Current 1-indexed page. */
  readonly page: Accessor<number>
  /** Configured items per page. */
  readonly pageSize: Accessor<number>
  /** Zero-indexed item offset for an API request. */
  readonly offset: Accessor<number>
  /** Current URL filter values, including values supplied by path parameters. */
  readonly filters: Accessor<Record<Filter, string | undefined>>
  /** Matching view, or the configured fallback. */
  readonly selection: Accessor<Selection | undefined>
  /** Decoded current path parameters, also usable as API-only filters. */
  readonly params: Accessor<RouteParams>
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  readonly canLoad: Accessor<boolean>
  /** Readiness for the current view. A public view always stays ready. */
  readonly status: Accessor<ListRouteResult<Filter, Selection>['status']>
  /** Sign-in destination while a signed-out protected view is being redirected. */
  readonly redirectTo: Accessor<string | undefined>
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  readonly href: ListRouteResult<Filter, Selection>['href']
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  readonly navigate: ListRouteResult<Filter, Selection>['navigate']
  /** Change only the page, retaining the current filters and view. */
  readonly setPage: ListRouteResult<Filter, Selection>['setPage']
  /** Patch URL filters and return to page one. */
  readonly setFilters: ListRouteResult<Filter, Selection>['setFilters']
  /** Select a configured view at page one, preserving current route parameters. */
  readonly select: ListRouteResult<Filter, Selection>['select']
}

ListRouteFilter

Where a list filter lives in the URL. Path values take precedence over query values.

interface ListRouteFilter {
  /** Query key; defaults to the filter's name when `param` is absent. */
  query?: string
  /** Path parameter supplied by the current route, such as `category` in `/topics/:category`. */
  param?: string
  /** Value returned when neither URL source supplies a value; omitted from generated queries. */
  defaultValue?: string
}

ListRouteSelection

A selectable list view, expressed in the app's own route contract.

interface ListRouteSelection {
  /** Absolute route pattern, for example `/members/:member/saved`. */
  path: string
  /** Query values identifying this view. An undefined value requires the key to be absent. */
  query?: QueryParams
  /** A protected selection never loads before authentication is confirmed. */
  requiresAuth?: boolean
}

ListRouteAuth

Authentication readiness for protected list selections.

interface ListRouteAuth {
  /** The auth client's status. Unavailable is distinct from a signed-out session. */
  status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'
  /** App-owned sign-in URL. A signed-out protected visit replaces history with this URL. */
  redirectTo: string
}

ListRouteOptions

URL-backed list state configuration; it neither invents nor rewrites the app's route contract.

interface ListRouteOptions<Filter extends string = string, Selection extends string = string> {
  /** Fixed number of items per page; defaults to 20. */
  pageSize?: number
  /** Query key for a 1-indexed page; defaults to `page`. Page one omits the key. */
  pageParam?: string
  /** Route pattern for changing path-backed filters when no selections are configured. */
  path?: string
  /** Filters and their URL sources. API-only filters do not belong here. */
  filters?: Record<Filter, ListRouteFilter>
  /** Named views sharing a list. Both path variants and query variants are supported. */
  selections?: Record<Selection, ListRouteSelection>
  /** Tie-breaker when multiple selections match, or fallback when none matches. */
  defaultSelection?: NoInfer<Selection>
  /** Required when a selection is protected. Public views remain public as auth changes. */
  auth?: ListRouteAuth
}

ListRouteChange

A single atomic list navigation. Filter/selection changes reset page unless explicitly supplied.

interface ListRouteChange<Filter extends string = string, Selection extends string = string> {
  /** Target page, starting at one. */
  page?: number
  /** Patch of URL filter values. Undefined removes a query filter. */
  filters?: Partial<Record<Filter, string | undefined>>
  /** Target view, resolved through its configured path and query values. */
  selection?: Selection
  /** Optional path parameter changes, for example when opening a different member's saved view. */
  params?: RouteParams
}

ListRouteResult

List state and navigation, derived directly from the current location.

interface ListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** Current 1-indexed page; malformed and non-positive URL values read as page one. */
  page: number
  /** Configured items per page. */
  pageSize: number
  /** Zero-indexed item offset for an API request. */
  offset: number
  /** Current URL filter values, including values supplied by path parameters. */
  filters: Record<Filter, string | undefined>
  /** Matching view, or the configured fallback. */
  selection: Selection | undefined
  /** Decoded current path parameters, also usable as API-only filters. */
  params: RouteParams
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: boolean
  /** Readiness for the current view. A public view always stays ready. */
  status: 'ready' | 'loading' | 'unauthenticated' | 'unavailable'
  /** Sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: string | undefined
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  href: (change?: ListRouteChange<Filter, Selection>) => string
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /** Change only the page, retaining the current filters and view. */
  setPage: (page: number, options?: NavigateOptions) => void
  /** Patch URL filters and return to page one. */
  setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /** Select a configured view at page one, preserving current route parameters. */
  select: (selection: Selection, options?: NavigateOptions) => void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

RouteMatch

Result of matching a URL against a route pattern (path, params, query string).

interface RouteMatch<Params extends RouteParams = RouteParams> {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Matched URL pathname.
   */
  pathname: string

  /**
   * Route parameters.
   */
  params: Params

  /**
   * Whether this is an exact match.
   */
  isExact: boolean
}

Options for programmatic navigation (replace vs push, carry state, preserve query/hash).

interface NavigateOptions {
  /**
   * Replace current history entry instead of pushing.
   */
  replace?: boolean

  /**
   * State to pass with navigation.
   */
  state?: unknown

  /**
   * Preserve current query params.
   */
  preserveQuery?: boolean

  /**
   * Preserve current hash.
   */
  preserveHash?: boolean
}

RouteDefinition

Route configuration entry (path pattern, name, auth requirements, roles, children).

interface RouteDefinition {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Route name (for named routes).
   */
  name?: string

  /**
   * Whether the route requires exact matching.
   */
  exact?: boolean

  /**
   * Whether the route requires authentication.
   */
  requiresAuth?: boolean

  /**
   * Required roles/permissions.
   */
  roles?: string[]

  /**
   * Route metadata.
   */
  meta?: Record<string, unknown>

  /**
   * Child routes.
   */
  children?: RouteDefinition[]
}

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

Types

LazyLoadableComponent

Any component lazy can load.

type LazyLoadableComponent = Awaited<ReturnType<Parameters<typeof lazy>[0]>>['default']

SolidRouteParamName

The parameter names a Solid Router path declares: :name, :name? and *rest. A path that is not a literal declares any name.

type SolidRouteParamName<Path extends string> = string extends Path
  ? string
  : Exclude<ScanSolidPath<Path>, ''>

SolidRouteParams

The parameters a Solid Router path declares. Every value is a string, or undefined when the URL leaves the parameter out.

type SolidRouteParams<Path extends string> = Readonly<{
  [Name in SolidRouteParamName<Path>]: string | undefined
}>

SolidPathParam

The parameter names a route path declares for a link, as React Router reads them: :name and the trailing splat, *. A path that is not a literal declares any name.

type SolidPathParam<Path extends string> = keyof LinkPathParams<Path> & string

SolidLinkParams

The parameters a link for a path takes: every required parameter's value, and an optional parameter's value or null to leave it out.

type SolidLinkParams<Path extends string> = Record<SolidRequiredLinkKey<Path>, string> &
  Partial<Record<Exclude<SolidPathParam<Path>, SolidRequiredLinkKey<Path>>, string | null>>

SolidLinkArgs

The arguments a path's href takes: the required parameters when the path declares any, an optional parameter object when every parameter is optional, and none at all for a path without parameters. A path that is not a literal accepts any parameter map.

type SolidLinkArgs<Path extends string> = string extends Path
  ? [params?: Record<string, string | null | undefined>]
  : [SolidPathParam<Path>] extends [never]
    ? []
    : [SolidRequiredLinkKey<Path>] extends [never]
      ? [params?: SolidLinkParams<Path>]
      : [params: SolidLinkParams<Path>]

ListRouteOptionsInput

The options useListRoute takes: a plain object, or an accessor of one when the app's auth status changes on the same mounted component (a new status re-resolves the list, the way React re-renders useListRoute).

type ListRouteOptionsInput<Filter extends string = string, Selection extends string = string> =
  ListRouteOptions<Filter, Selection> | (() => ListRouteOptions<Filter, Selection>)

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

GuardResult

Navigation guard result.

type GuardResult = boolean | string | { path: string; replace?: boolean } | void

Navigation guard function invoked before each navigation. Return false to cancel, a string/path to redirect, or void to allow.

type NavigationGuard = (
  to: RouteLocation,
  from: RouteLocation | null,
) => GuardResult | Promise<GuardResult>
  • to — The target route location being navigated to.
  • from — The current route location being navigated away from, or null on initial load.

RouteChangeListener

Callback invoked on each route change with the new location and the navigation action that triggered it.

type RouteChangeListener = (location: RouteLocation, action: NavigationAction) => void

Functions

ListRouteNav(props)

Render every declared list view as a router link. The URL selects the active choice, and selecting any view resets pagination through useListRoute. Native link behavior (new-tab clicks, keyboard activation and history) is preserved. This is a navigation landmark, not an ARIA tablist with local panels. No active-value state or change handler is needed. When children are supplied, they render after the navigation landmark. Put loading and empty results in that branch so a pending list never removes the filter controls.

function ListRouteNav<Selection extends string>(props: ListRouteNavProps<Selection>): JSX.Element
  • props — Named destinations, translated labels, optional auth and native nav attributes.

Returns: The navigation landmark with all its choices, followed by any rendered content.

defineRoute(path, page)

Register a literal Solid Router path and give its page the params that path declares.

Create the route at module scope and pass it to a router's children or routes. A render callback builds the page from the params, or pass { Component: EditPage } to give the page a typed params prop automatically. The render callback runs once when the page mounts and returns its JSX. Read params inside JSX or an effect so the page follows URL changes. The params object is Solid's reactive one, so reading it outside a tracking scope does not update. Values arrive percent-decoded, as they do in the other routing bonds, although Solid Router itself hands out the raw URL text.

Use the returned href for links and post-save navigation. It builds the destination from the same path that mounts the page, with the parameter names required by that path, exactly as React Router's bond builds it. Pass values from the saved response when identity can change.

function defineRoute<const Path extends string>(
  path: Path,
  page:
    | ((params: NoInfer<SolidRouteParams<Path>>) => JSX.Element)
    | {
        Component: (props: { params: NoInfer<SolidRouteParams<Path>> }) => JSX.Element
      },
): SolidRouteDefinition<Path> & { path: Path; href: (...args: SolidLinkArgs<Path>) => string }
  • path — A route path, including any named parameters.
  • page — A render callback building the page, or an object with the page's Component.

Returns: The Solid Router route definition and a function that builds a link to it.

useMoleculeRouter(options)

Gets the molecule Router inside any Solid Router. No MoleculeRouterProvider is required.

When MoleculeRouterProvider is mounted, returns its exact router with its named routes. Otherwise creates ONE router for the calling component's whole life — its location, params and queries follow the native router through every navigation, and subscribe() hears the native router's own links and the back button — without bonding it globally; the router is destroyed when the component is cleaned up. Mount MoleculeRouterProvider for the non-Solid @molecule/app-routing navigate()/ getRouter() bond or onRouterReady.

function useMoleculeRouter(options?: SolidRouterOptions): Router
  • options — Route definitions for a component-owned router's named routes, and the memory history a <MemoryRouter history={…}> above uses (see createSolidRouter); ignored when a provider supplies the router.

Returns: The molecule Router instance.

useMoleculeNavigate()

Gets a navigate function with molecule Router options inside any Solid Router. Mount MoleculeRouterProvider only for named routes, the non-Solid navigate()/getRouter() bond, or onRouterReady.

function useMoleculeNavigate(): Router['navigate']

Returns: The router's navigate function.

useMoleculeQuery()

Gets the current query params as an object inside any Solid Router. Mount MoleculeRouterProvider only for named routes, the non-Solid navigate()/getRouter() bond, or onRouterReady.

function useMoleculeQuery(): Accessor<QueryParams>

Returns: An accessor for the query params, re-read as the location's search changes.

useIsActive(path, exact)

Checks whether a path is currently active inside any Solid Router. Mount MoleculeRouterProvider only for named routes, the non-Solid navigate()/getRouter() bond, or onRouterReady.

function useIsActive(path: string, exact?: boolean): Accessor<boolean>
  • path — Path to check.
  • exact — Whether to require an exact match.

Returns: An accessor for whether the path is active, re-read as the location changes.

lazyPage(load, options)

Load a route's page on demand, inside a Suspense boundary that belongs to the page.

Use it instead of Solid's lazy for every page a <Route> renders. Navigating to a page whose code has not loaded yet then replaces the previous page at once: the previous page unmounts and the new page's own boundary shows fallback until its code arrives. With lazy under one shared <Suspense> around the routes, Solid Router's navigation transition keeps the previous page mounted (hidden) behind that boundary's fallback, so the URL already names the new page while the old page's content is still in the DOM, and a check such as getByRole('heading') finds the old page's headings. Layout routes (an app shell around the router's children) stay mounted either way.

function lazyPage<Page extends LazyLoadableComponent>(
  load: () => Promise<{ default: Page }>,
  options?: LazyPageOptions,
): LazyPageComponent<Page>
  • load — Loads the page module, as for Solid's lazy: () => import('./pages/Article.js').then((m) => ({ default: m.Article })).
  • options — Optional fallback shown in the page's area while its code loads.

Returns: A component to use as a route's component: <Route path="/article/:slug" component={Article} />. Its props are the page's own, without the undefined an optional props parameter (function Draft({ initial }: DraftProps = {})) adds.

createSolidMemoryHistory(initialEntries)

Creates a memory history for a Solid <MemoryRouter>. Pass the same object to createSolidRouter({ history }) so the molecule router reads each entry's state and key, and hears Back and Forward as pops.

function createSolidMemoryHistory(initialEntries?: string[]): SolidMemoryHistory
  • initialEntries — The starting entries; the last one is current. Defaults to /.

Returns: The history, with the shape Solid's MemoryRouter takes.

MemoryRouter(props)

Solid Router's MemoryRouter on a memory history every molecule hook under it reads: each entry's state and key, and Back and Forward as pops. Under Solid Router's own MemoryRouter only useMoleculeRouter({ history }) sees them.

function MemoryRouter(props: MemoryRouterProps): JSX.Element
  • props — Solid Router's MemoryRouter props, plus initialEntries.

Returns: The router.

MoleculeRouterProvider(props)

Provider component that creates ONE molecule Router over the Solid Router the call sits inside, for its whole mounted life, and bonds it as the active singleton via @molecule/app-routing's setRouter. Subscribers and guards registered on the router survive navigation: @molecule/app-routing's getRouter() keeps returning it, onRouterReady fires once, and Solid Router's own links and the back button reach router.subscribe().

Bonding happens while the component renders, before its children, so a page's first render already reads this router — no manual setRouter wiring required. It also renders @molecule/app-solid's RouterProvider with the router, so that binding's routing primitives read it. It provides no routed view: Solid Router gives a route's component its nested route as props.children, so a layout or guard used as a route component gets its page as children. Mount it as the router's root (as in the example). The bond's own routing hooks work without it. A MoleculeRouterProvider inside another one uses the outer one's router: it registers its routes there and calls onRouterReady with it.

function MoleculeRouterProvider(props: MoleculeRouterProviderProps): JSX.Element
  • props — The provider props (see MoleculeRouterProviderProps): children (rendered inside the router context), routes (optional named-route definitions; pass a stable array — later identities register onto the same router), onRouterReady (optional callback invoked ONCE with the router after it is bonded, e.g. to register guards), history (the memory history the mounted <MemoryRouter> uses) and signInPath (the sign-in path a signed-out GET 401 sends the visitor to; false turns it off).

Returns: The rendered provider wrapping children with the router context.

createSolidRouter(options)

Creates a molecule Router over the Solid Router the call sits inside.

Call it inside a Solid Router context — a component under <Router>, <HashRouter> or <MemoryRouter>, typically the router's root component — and bond the result so every molecule package shares the native router:

function createSolidRouter(options?: SolidRouterOptions): Router
  • options — Route definitions and, for a memory router, its history.

Returns: A molecule Router driving that Solid Router.

useConsumedSearchParam(name)

Consume a credential query parameter into component state and remove only that parameter from the address through the native router. The value survives local updates, failed-submit retries and later query-only navigation; a newly arriving value on the same mounted route is consumed too. Path, hash, unrelated query values and router location state are retained.

The bond's router owns the URL replacement, so the native location and window.location agree. Its replace keeps the entry's app-owned state fields, including ones the native router does not model.

function useConsumedSearchParam(name: string): [string, (value: string) => void]
  • name — The credential query key to consume, for example token or code.

Returns: The consumed value and its setter, in the binding's tuple shape: index 0 is the live value ('' before first consumption), index 1 sets it.

useListRoute(options)

Own URL-backed pagination, filters and selected views without mirrored state or navigation effects. Works inside any Solid Router (<Router>, <HashRouter>, <MemoryRouter>); no data-router feature or MoleculeRouterProvider is needed — a provider supplies named routes and the non-Solid @molecule/app-routing bond, nothing this hook requires. Ordinary links, direct visits and Back/Forward all read the same URL. Page links retain path parameters and unrelated queries; changing filters or views resets the page atomically. Protected views wait for auth and redirect only a confirmed signed-out session, with state.returnTo set.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: ListRouteOptionsInput<Filter, Selection>,
): UseListRouteResult<Filter, Selection>
  • options — App-owned filter sources, view paths, pagination and optional auth readiness, or an accessor of them (a new auth status re-resolves the list).

Returns: Reactive list state plus link builders and navigation actions. Gate data queries with canLoad.

parseSearchParams(searchParams)

Converts URLSearchParams into QueryParams. A key that appears more than once becomes an array of its values, in order.

function parseSearchParams(searchParams: URLSearchParams): QueryParams
  • searchParams — The search params to read.

Returns: The query params.

stringifyQuery(params)

Serializes QueryParams into a query string with a leading ?, percent-encoding keys and values (a space is %20). Undefined values are left out; an array writes its key once per value.

function stringifyQuery(params: QueryParams): string
  • params — The query params.

Returns: The query string, or '' when there is nothing to write.

matchPath(pattern, pathname, exact)

Matches a route pattern against a pathname. :name captures one segment and * matches anything. The whole pathname must match unless exact is false, which also accepts a pathname that only starts with the pattern.

function matchPath<Params extends RouteParams = RouteParams>(
  pattern: string,
  pathname: string,
  exact?: boolean,
): RouteMatch<Params> | null
  • pattern — The pattern, such as /users/:id or /files/*.
  • pathname — The pathname to match.
  • exact — Whether the whole pathname must match (default true).

Returns: The match with its params, or null.

generatePath(pattern, params)

Builds a path from a pattern by putting each :name param in its place, percent-encoded. A pattern given no params is returned as it is.

function generatePath(pattern: string, params?: RouteParams): string
  • pattern — The pattern, such as /users/:id.
  • params — The param values.

Returns: The path.

resolvePath(to, fromPathname)

Resolves a path against the pathname it is relative to: an absolute to is returned as it is; otherwise to is joined to fromPathname's parent, with .. moving up and . staying.

function resolvePath(to: string, fromPathname: string): string
  • to — The path to resolve.
  • fromPathname — The pathname it is relative to.

Returns: The resolved pathname.

normalizePath(path)

Removes trailing slashes from a path, keeping / itself.

function normalizePath(path: string): string
  • path — The path.

Returns: The path without trailing slashes.

Constants

provider

Typed provider constant for the bond registry.

A Solid Router needs a component context (useLocation and friends read it), so no router can be built at import time: provider is @molecule/app-routing's own browser router, correct only where no Solid Router is mounted. Wire createSolidRouter() from a component under the router instead (see its example).

const provider: Router

Core Interface

Implements @molecule/app-routing interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setRouter } from '@molecule/app-routing'
import { provider } from '@molecule/app-routing-solid-router'

export function setupRoutingSolidRouter(): void {
  setRouter(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-bond ^1.0.1
  • @molecule/app-i18n ^1.0.1
  • @molecule/app-routing ^1.5.0
  • @molecule/app-solid ^3.10.0 || ^4.0.0
  • @solidjs/router ^0.16.1
  • solid-js ^1.8.0

Runtime Dependencies

  • @molecule/app-bond

  • @molecule/app-i18n

  • @molecule/app-routing

  • @molecule/app-solid

  • @solidjs/router

  • solid-js

  • Call createSolidRouter() inside the router's root component (any component under <Router>, <HashRouter> or <MemoryRouter>): it reads the native router through useLocation(), useNavigate() and useParams(), which need that context.

  • Do NOT wire the exported provider const in a Solid app: it is the core's plain browser router for use where no Solid Router is mounted.

  • A route with parameters? Declare its page with defineRoute. The route path is the source of truth for the page's parameter names: :name, :name? and *rest each arrive as string | undefined. For example:

    import { defineRoute } from '@molecule/app-routing-solid-router'
    
    const shelves = [
      defineRoute('/shelves/:shelf', ({ shelf }) => <Shelf name={shelf} view="all" />),
      defineRoute('/shelves/:shelf/saved', ({ shelf }) => <Shelf name={shelf} view="saved" />),
    ]
    

    Keep the returned route when links or a save handler need its destination. For const detail = defineRoute('/shelves/:shelf', { Component: ShelfDetail }), use detail.href({ shelf: saved.slug }) to navigate to the saved record.