# groutcho › Concepts

Declarative routing. A small matching + redirect **core** built on the
web-standard [`URLPattern`], with a pluggable history seam so it works
standalone in vanilla web, and thin bindings over it.

The core owns **all** matching and redirect logic and never touches the DOM —
only `createBrowserHistory` does — so the same engine runs in the browser, Node,
workers, and React Native (Hermes). The bindings are small adapters over one
shared store.

## Concepts

- **Routes** map a name to a `URLPattern` pathname (`/show/:title`,
  `/optional/:opt?`) plus arbitrary metadata (`session`, `role`, a per-route
  `redirect`, and a `page` payload — a component, tag, render fn, whatever your
  layer needs).
- **Redirects** are named functions run against each match. They return where to
  go (a route name, url, or input) or `false`. The engine follows them with
  loop/cycle detection and a `max_redirects` guard.
- **Input is polymorphic**: `match('/show/hi')`, `match('Home')`,
  `match({ route: { name: 'Show', params: { title: 'hi' } } })`,
  `match({ url: '/show/hi' })`.
- **`MatchResult`** carries `{ route, params, url, redirect, original }`.
- **Catch-all params** span multiple segments: `:path+` (one-or-more) or
  `:path*` (zero-or-more). A match exposes both accessors — the raw joined string
  and the split segments — and `buildUrl` accepts either:

  ```ts
  // pattern: '/files/:path+'
  match('/files/docs/2026/report.pdf');
  // params.path      === 'docs/2026/report.pdf'
  // params.pathArray === ['docs', '2026', 'report.pdf']
  buildUrl({ path: ['docs', '2026', 'report.pdf'] }); // -> /files/docs/2026/report.pdf
  buildUrl({ path: 'docs/2026/report.pdf' });         // -> same
  ```

## Core (vanilla)

```ts
import { createRouter } from '@diso.io/groutcho-core';

const store = createRouter({
  routes: {
    Home: { pattern: '/', page: HomeView },
    Show: { pattern: '/show/:title', page: ShowView },
    Signin: { pattern: '/signin', page: SigninView, session: false },
    Dashboard: { pattern: '/dashboard', page: DashboardView, session: true },
    NotFound: { pattern: '/404', page: NotFoundView }
  },
  redirects: {
    NotFound: (match) => (match ? false : 'NotFound'),
    Session: (match) =>
      match?.route?.session === true && !isSignedIn() ? 'Signin' : false
  }
  // history defaults to the browser; pass `history` to override.
});

store.subscribe((match) => render(match)); // re-render on navigation
render(store.getSnapshot());                // initial

store.go('/show/hello'); // updates history + notifies subscribers
```

`createRouter` returns a store with `getSnapshot()` / `subscribe()` (which plug
straight into React's `useSyncExternalStore` and a Lit controller), plus `go`,
`match`, the underlying `router`, and `destroy`. Use `createMemoryHistory()` for
SSR, tests, or React Native.

## hype

```ts
import { useRouter } from '@diso.io/groutcho';
import { define, html } from '@diso.io/hype';

define('my-app', () => {
  const { match } = useRouter({ routes, redirects });
  return html`
    <nav><diso-link to="Home">Home</diso-link></nav>
    <h1>${() => match.value.route?.name}</h1>
    <diso-outlet></diso-outlet>
  `;
});
```

`useRouter(config)` makes the page's router; `<diso-outlet>`, `<diso-link>` and
`useRouter()` anywhere inside find it. See the [package README](hype).

## Lit

```ts
import { RouterController } from '@diso.io/groutcho-lit';

class MyApp extends LitElement {
  router = new RouterController(this, { routes, redirects });
  render() {
    const { match } = this.router;
    return html`
      <nav><diso-link .store=${this.router.store} to="Home">Home</diso-link></nav>
      <diso-outlet .store=${this.router.store}></diso-outlet>
    `;
  }
}
```

Share one store via `@lit/context` (`routerContext`) so nested
`<diso-outlet>` / `<diso-link>` resolve it without prop-drilling. A
route `page` that's a function is called as `(match) => TemplateResult`.

## React

```tsx
import { RouterProvider, useMatch, Link } from '@diso.io/groutcho-react';

function App() {
  return (
    <RouterProvider routes={routes} redirects={redirects}>
      <nav><Link to="Home">Home</Link></nav>
      <Outlet />
    </RouterProvider>
  );
}

function Outlet() {
  const match = useMatch();          // re-renders on navigation
  const Page = match.route?.page as React.ComponentType;
  return Page ? <Page {...match.params} /> : null;
}
```

Built on `useSyncExternalStore`. `RouterProvider` also accepts `children` as a
render-prop, `({ match, store }) => ReactNode`.

See the [monorepo README](../../README.md) for the workspace, develop, and
release flow.

[`URLPattern`]: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern
