# Routing (pyzed.routing)

> API reference for pyzed.routing: Next.js-style routes in folders for Python desktop apps, with RouterApp, Router, links, navigation hooks, not_found and redirect.

Source: https://albakore.github.io/pyzed/reference/routing/

<!-- Generated by docs/scripts/gen_api.py. Edit docs/scripts/api_docs_en.py. -->

Pages as folders of `app/`, like Next.js' App Router: `page.py`, `layout.py`, `template.py`,
`loading.py`, `error.py`, `not_found.py`, `[id]`, `[...slug]`, `[[...slug]]` and `(group)`.
See the [Routing section](https://albakore.github.io/pyzed/routing/).

```python
pz.run(pz.RouterApp("app", title="Shop"))
```

## The router

### `RouterApp`

```python
class RouterApp
```

An app whose window shows its routes:

```python
pz.run(pz.RouterApp("app", title="Shop"))

class Shop(pz.RouterApp):           # or subclass it
    routes = "app"
    title = "Shop"
    size = (1100, 720)
```

The window's title follows the page (its `title` or `metadata`, with the root layout's
`title_template`); the app's own `title` is used when the page has none. Alt+Left/Right,
the mouse's back and forward buttons and Android's back button move in the history.
`on_navigate(location)` runs after every navigation.

```python
class Shop(pz.RouterApp):
routes = "app"
title = "Shop"
```

### `Router`

```python
class Router
```

Routes in folders, like Next.js' App Router, or in a dict; see `pyzed.routing`.

`routes` is the `app/` folder (a relative path is looked for next to the file that creates the
router, then in the current folder), or a dict such as `{"/": home, "/users/[id]": user}`.
`initial` is the first location and `stale_time` how many seconds the data of a page stays
fresh: after that, going to it again (not back or forward) loads it again. `middleware` is a
function (or a list) that runs before every navigation, before the `middleware.py` files of the
folders (see `pz.middleware`).

```python
self.router = pz.Router("app")
# in view(): return self.router.view()
```

## Links and hooks

### `link`

```python
link(href, content=None, *, replace=False, prefetch=True, router=None, size=None)
```

A link to `href` (`<Link>` in Next.js): text in the accent color, or any widget, that navigates
when clicked.

`href` is a path (`"/products/3"`), relative to the current page (`"../"`, `"reviews"`), a
query (`"?page=2"`) or `("/users/[id]", {"id": 7})`. `replace` replaces the history entry
instead of adding one; `prefetch` starts the page's `load` when the mouse is over the link.

```python
pz.link("/products/3", "See the monitor")
```

### `nav_link`

```python
nav_link(href, label, *, icon=None, exact=None, router=None, description=None)
```

A row for a sidebar or a menu (`ui.list_item`) that goes to `href` and shows as selected while
that page, or a page under it, is open (`exact=True`: only that page; the root `/` is exact).

```python
pz.nav_link("/settings", "Settings", icon="settings")
```

### `use_router`

```python
use_router()
```

The router drawing this view (`useRouter()`): `use_router().push("/cart")`.

Outside a view (a callback, a form's handler) it is the router that drew last.

```python
pz.use_router().push("/cart")
```

### `use_pathname`

```python
use_pathname()
```

The current path, like `/products/3` (`usePathname()`).

### `use_params`

```python
use_params()
```

The parameters of the current page: `{"id": "3"}` for `/products/[id]` (`useParams()`).

### `use_search_params`

```python
use_search_params()
```

The current query as a dict, `get_all(key)` for repeated keys (`useSearchParams()`).

## Inside pages

### `not_found`

```python
not_found()
```

Stops drawing the page (or its `load`) and shows the closest `not_found` file, like Next.js'
`notFound()`:

```python
async def load(params):
    product = await shop.get(params["id"])
    if product is None:
        pz.not_found()
    return product
```

### `redirect`

```python
redirect(href, *, push=False)
```

Goes to `href` instead of the page being drawn (from a page, a layout or a `load`).

The current history entry is replaced, like Next.js' `redirect()`; `push=True` adds one.

```python
pz.redirect("/login")
```

### `Location`

```python
@dataclass
class Location(pathname='/', search='', hash='')
```

Where the router is: `pathname` (`/products/3`), the `search` query without `?` and the
`hash` without `#`. The same parts as a browser's URL, so a route maps to a web address as is.

### `SearchParams`

```python
class SearchParams
```

The query of the URL (`?tab=reviews&tag=a&tag=b`) as a dict of the first values.

`get_all("tag")` gives every value of a repeated key, `str()` the encoded query.

## Middleware

### `middleware`

```python
middleware(function=None, *, matcher=None)
```

Marks a function as middleware for `Router(middleware=[...])`, with the addresses it runs for:

```python
@pz.middleware(matcher="/admin/:path*")
def admins_only(request):
    if not session.is_admin:
        return request.redirect("/")
```

A plain function works too; `matcher` only narrows where it runs.

```python
@pz.middleware(matcher="/admin/:path*")
def admins_only(request):
    if not session.is_admin:
        return request.redirect("/")
```

### `rewrite`

```python
rewrite(href)
```

In middleware: keeps the address but shows the route at `href` (`NextResponse.rewrite`).

Return it, or raise it: `return pz.rewrite("/maintenance")`.

```python
return pz.rewrite("/maintenance")
```

### `Request`

```python
@dataclass
class Request(location, previous, action, router, route=None, params={}, locals={})
```

A navigation that middleware can let through, send elsewhere or stop.

`location` is where it goes (`pathname`, `query`, `hash` and `href` are its parts),
`previous` where the router is now (`None` at the start), `action` what started it (`"start"`,
`"push"`, `"replace"`, `"back"`, `"forward"` or `"refresh"`), `route` the pattern that
answers it (`"/products/[id]"`, `None` when no page does) and `params` its values.
`locals` is a dict the pages, layouts and `load` functions of that location receive as `locals`.

## Data and state

### `action`

```python
action(function=None, *, refresh=True, invalidate=None, on_done=None, on_error=None)
```

Makes `function` an :class:`Action` (see `pyzed.actions`): `@pz.action` or
`@pz.action(refresh=False, invalidate="/products")`.

```python
@pz.action(invalidate="/orders")
async def place(item):
    await api.place(item)
```

### `Action`

```python
class Action
```

A function that changes data, with its state: `pending`, `result`, `error` and `calls`.

Calling it starts the function and returns a `concurrent.futures.Future`; `run(...)`
calls it and waits (for tests and scripts). `reset()` clears `result` and `error`.

### `Store`

```python
class Store
```

Values shared by the whole app (see `pyzed.store`).

Fields are annotated class attributes with their defaults; `Cart(items=[...])` sets some.
`subscribe(callback)` calls `callback(store)` after each change, `batch()` groups several
changes into one, `reset()` goes back to the defaults and `to_dict()` gives the values.
Changing a list or dict in place (`cart.items.append(x)`) is seen by the next drawing; call
`changed()` after it so subscribers (and `persist`) hear about it too.

```python
class Cart(pz.Store):
    items: list = []

cart = Cart()
```

## Notifications

### `notify`

```python
notify(
    title,
    body='',
    *,
    icon=None,
    image=None,
    actions=None,
    href=None,
    on_click=None,
    on_action=None,
    on_close=None,
    urgency='normal',
    sound=True,
    timeout=None,
    tag=None,
)
```

Shows a native desktop notification and returns it (see `pyzed.notifications`).

`icon` and `image` are paths or PNG bytes. `actions` are buttons, as `{id: label}` or a
list of labels; an id that starts with `/` (or `?`) opens that page. `href` is the page a
click opens; `on_click(notification)`, `on_action(id)` and `on_close(reason)` run on the UI
thread. `urgency` is `"low"`, `"normal"` or `"critical"` (stays until answered),
`sound` `True` (the system's), `False` or a sound's name, and `timeout` the seconds on
screen (`0`: until dismissed; `None`: the system's default). A new notification with the
`tag` of one still shown replaces it, like a download's progress.

```python
pz.notify("Order shipped", "On its way", href="/orders/3")
```

### `DesktopNotification`

```python
class DesktopNotification
```

A notification shown with `pz.notify`: `close()` takes it away, `update(...)` changes it.

`native` is `False` when it was shown without the system's notifications (no buttons or
clicks then), `closed` once it left the screen and `reason` why: `"expired"`,
`"dismissed"`, `"closed"` or `"unknown"`.
