# App and running

> API reference for pyzed.App: the application class, run, screenshot, post, load_font and the window options of a Python desktop app.

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

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

            Everything you need to start an application. See also the
            [architecture](https://albakore.github.io/pyzed/guides/architecture/) guide.

See also [multiple windows](https://albakore.github.io/pyzed/guides/windows/) and [async and subscriptions](https://albakore.github.io/pyzed/guides/async/).

## Application

### `App`

Base class for applications (Elm architecture, like Iced). It is also the **main
window**, so it inherits everything from [`Window`](#window). Override `view()` and, if you use
messages, `update(message)`. State lives in instance attributes.

| Class attribute | Default | Description |
| --- | --- | --- |
| `title` | `"Pyzed"` | Window title. Can be a callable (or property) that returns the text. |
| `size` | `(1280, 800)` | Initial window size. |
| `font_size` | `14` | Default text size. |
| `theme` | `themes.ONE_DARK` | A `Theme`, the name of a registered theme or `themes.auto(light, dark)`. Change it at any time. |
| `style` | `None` | The global style: a `pz.Style` for the whole window. Its text color, size, background, border color and radius become theme tokens. See [Styles](https://albakore.github.io/pyzed/theming/styles/#the-global-style). |
| `system_dark` | `True` | Whether the system is in dark mode (updated by the runtime). |
| `tab_focus` | `True` | Tab and Shift+Tab move the focus between the fields of the window. See [Accessibility](https://albakore.github.io/pyzed/guides/accessibility/). |
| `splash` | `None` | A [`Splash`](#splash) window shown before the main window opens. |
| `rendering` | `None` | A [`Rendering`](#rendering): GPU or CPU, graphics API, GPU and vsync. `None` reads `[tool.pyzed.rendering]` of the project's `pyproject.toml`. |

The remaining window options (`min_size`, `resizable`, `decorations`, `icon`, `scale`…) are on `Window`.

| Method | Description |
| --- | --- |
| `view()` | Returns the widget tree. Called after every message. |
| `update(message)` | Receives messages. Can return a `Command`, a list of them, a coroutine, a generator (regular or async) or another message. |
| `on_start()` | Optional. Runs once at startup; can return a `Command` or a coroutine. |
| `on_key(combo)` | Optional. Receives every key as `"ctrl-shift-p"`, `"escape"`, `"up"`… |
| `on_key_up(key)` | Optional. Receives key releases by name (`"left"`, `"space"`). |
| `subscriptions()` | Optional. Returns the active subscriptions (`pz.every`, `pz.listen`). Re-evaluated after every `update`. |
| `resolved_theme()` | The concrete `Theme` in use (resolves names and `themes.auto`). |
| `run()` | Opens the window and blocks until the app exits. |
| `screenshot(path, *, size=None, scale=2.0, wait=0.1)` | Renders the current state to a PNG without a window. |

If `view()` raises an exception, the window shows the traceback instead of closing.

**Methods and properties**

#### `App.subscriptions`

```python
App.subscriptions()
```

Timers and streams that should run right now (re-evaluated after every update).

#### `App.run`

```python
App.run(*, reload=None, watch=())
```

Opens the window and blocks until the app exits.

#### `App.screenshot`

```python
App.screenshot(path, *, size=None, scale=2.0, wait=0.1)
```

Renders the current state off-screen (no GPU or display needed) into a PNG.

### `run`

```python
run(app, *, reload=None, watch=())
```

Runs an app: opens the window and blocks until it is closed. Accepts the class or an instance.

| Parameter | Description |
| --- | --- |
| `app` | An `App` instance (or the class, which is instantiated with no arguments). |
| `reload` | Hot reload: saving a project file updates the running window and keeps its state. `None` follows `PYZED_RELOAD` (set by `pyzed dev`). |
| `watch` | Extra folders or files to watch for hot reload. |

### `screenshot`

```python
screenshot(app, path, *, size=None, scale=2.0, wait=0.1)
```

Renders `app` offscreen (no window, no GPU) and saves a PNG. Useful for tests and documentation.

| Parameter | Description |
| --- | --- |
| `app` | An `App` instance (or the class, which is instantiated with no arguments). |
| `path` | Path of the output PNG. |
| `size` | Logical size `(width, height)`. Defaults to `app.size`. |
| `scale` | PNG scale factor (2.0 = retina). |
| `wait` | Seconds to wait before capturing (for `on_start` tasks). |

```python
pz.screenshot(MyApp, "docs/ui.png", size=(800, 600))
```

### `post`

```python
post(message)
```

Sends a message to the running app from **any thread**. Raises `RuntimeError` if no app is running.

| Parameter | Description |
| --- | --- |
| `message` | Any Python value, or a callable. |

```python
def worker():
    for i in range(100):
        time.sleep(0.05)
        pz.post(("progress", i / 100))

threading.Thread(target=worker, daemon=True).start()
```

### `UNCHANGED`

```python
UNCHANGED(...)
```

Return it from a callback that changed nothing on screen (a pointer move you only record, a focus change): the window is not rebuilt. Any other return value redraws as usual. See the [performance guide](https://albakore.github.io/pyzed/guides/performance/).

```python
def pointer_moved(self, x, y):
    self.pointer = (x, y)
    return pz.UNCHANGED  # nothing visible changed: no rebuild
```

### `load_font`

```python
load_font(source)
```

Loads an extra font (path to a `.ttf`/`.otf` or its bytes) so you can use it by family name: `text("hello", font="JetBrains Mono")`.

| Parameter | Description |
| --- | --- |
| `source` | Path to the font file, or `bytes`. |

## Windows

### `Window`

An extra window with its own `view()`, title, size and theme. Open it by returning
`window.open()` (or `Command.open_window(window)`). Inside it, `self.app` is the app, so
windows share state; the messages it produces go to its `update()`, which by default
forwards them to `app.update()`.

| Attribute | Default | Description |
| --- | --- | --- |
| `title` | `"Pyzed"` | Text or callable. |
| `size` | `(800, 600)` | Initial size. |
| `min_size`, `max_size` | `None` | Size limits. |
| `position` | `None` | `"center"` or `(x, y)`. |
| `resizable` | `True` | Whether it can be resized. |
| `decorations` | `True` | `False` removes the system frame (custom title bar with `drag()`). |
| `transparent`, `maximized`, `fullscreen` | `False` | Initial state. |
| `scale` | `1.0` | UI scale. |
| `theme` | `None` | Its own theme; `None` uses the app's. |
| `style` | `None` | Its own global style; `None` uses the app's. |
| `icon` | `None` | The window's icon (title bar, taskbar): a path to an image or its bytes. Set it on `pz.Window` to give every window the same one. See [Icons and metadata](https://albakore.github.io/pyzed/packaging/icons-metadata/#the-window-icon). |
| `app_id` | `None` | Linux: the app id the desktop matches with a `.desktop` file (`com.acme.shop`). |
| `app` | — | The app that owns the window (assigned when it opens). |
| `window_size` | — | Current size in logical pixels (updated by the runtime). |
| `window_position` | — | Where the window is on the screen, its outer top-left corner (updated by the runtime; `None` on Wayland). |

| Method | Description |
| --- | --- |
| `view()` | Required. Returns the window's widget tree. |
| `update(message)` | Receives the window's messages (by default forwards them to the app). |
| `open()` / `close()` / `drag()` | Commands to open it, close it or start moving it. |
| `is_open` | Whether it is open. |
| `resolved_theme()` | The concrete `Theme` it uses. |
| `on_open()` | When it opens. |
| `on_close()` | When the user asks to close it; return `False` to prevent it. |
| `on_resize(width, height)` | When it is resized. |
| `on_key(combo)`, `subscriptions()` | As in `App`. |
| `on_file_hover(path)`, `on_file_drop(path)`, `on_file_leave()` | Files dragged from the system over the window, dropped on it (once per file) or taken away. By default they go to the `ui.DropZone` they land on. |

**Methods and properties**

#### `Window.view`

```python
Window.view()
```

Returns the window's root widget; subclasses must override it.

#### `Window.update`

```python
Window.update(message)
```

Handles a message produced in this window (forwards to the app by default).

#### `Window.on_close`

```python
Window.on_close()
```

Called when the user asks to close the window. Return `False` to keep it open.

#### `Window.on_file_hover`

```python
Window.on_file_hover(path)
```

A file dragged from the system is over the window: lights up the `ui.DropZone` it would land on.

#### `Window.on_file_drop`

```python
Window.on_file_drop(path)
```

A file was dropped on the window from the system (once per file): goes to a `ui.DropZone`.

#### `Window.on_file_leave`

```python
Window.on_file_leave()
```

The files dragged over the window left it without being dropped.

#### `Window.is_open`

```python
Window.is_open  # property
```

Whether the window is currently open.

#### `Window.open`

```python
Window.open()
```

A command that opens this window: `return settings.open()`.

#### `Window.close`

```python
Window.close()
```

A command that closes this window: `on_press=self.close`.

#### `Window.drag`

```python
Window.drag()
```

A command that starts moving the window (for custom title bars).

#### `Window.minimize`

```python
Window.minimize()
```

A command that minimizes the window.

#### `Window.toggle_maximize`

```python
Window.toggle_maximize()
```

A command that maximizes the window, or restores it when it is maximized.

#### `Window.frame_menus`

```python
Window.frame_menus()
```

The menus on the left of a custom frame's title bar (`frame = "custom"`): a list of `ui.Menu`.

#### `Window.resolved_theme`

```python
Window.resolved_theme()
```

The concrete theme this window uses right now (with its global style's colors and sizes).

#### `Window.resolved_style`

```python
Window.resolved_style()
```

The global style of this window: `pz.set_style` with its own (or the app's) `style` on top.

### `Splash`

```python
class Splash
```

A splash screen: a frameless window with an image, centered on the screen, shown while the app starts. Give it to `App.splash`; it stays up for `duration` seconds at least, then the main window opens and the splash closes. See [Splash screen](https://albakore.github.io/pyzed/packaging/build/#splash-screen).

| Parameter | Description |
| --- | --- |
| `image` | Path to the picture (PNG, JPEG...) or its bytes. |
| `duration` | Seconds it stays up, at least. |
| `size` | Window size; default: the image's, scaled down to fit 900 × 600. |
| `text` | Text written over the bottom of the image (for example `"Loading…"`). |
| `color` | Color of the text. |
| `background` | Color behind the image (for pictures with transparency). |
| `title` | Window title (the taskbar shows it). |
| `icon` | Window icon. |

```python
class Shop(pz.App):
    splash = pz.Splash("assets/splash.png", duration=1.5, text="Loading…")
```

### `Rendering`

```python
@dataclass
class Rendering(renderer='auto', gpu_api='auto', power='auto', vsync='auto')
```

How the app draws its windows: on the GPU or the CPU, which graphics API, which GPU and vsync. Each field is `"auto"` by default (Pyzed decides). Give it to `App.rendering`, or set the same keys in `[tool.pyzed.rendering]` of the project's `pyproject.toml`, which `pz.run`, the designer and `pyzed build` read. See [Rendering](https://albakore.github.io/pyzed/editor/settings/#rendering).

| Parameter | Description |
| --- | --- |
| `renderer` | `"auto"`, `"gpu"` (needed by shaders) or `"cpu"` (tiny-skia: starts faster, less memory, works everywhere). |
| `gpu_api` | `"auto"`, `"vulkan"`, `"metal"`, `"dx12"` or `"gl"`. |
| `power` | `"auto"`, `"high"` (the dedicated GPU) or `"low"` (the integrated one, saves battery). |
| `vsync` | `"auto"`, `"on"` (no tearing) or `"off"` (draws as fast as it can). |

```python
class Game(pz.App):
    rendering = pz.Rendering(renderer="gpu", vsync="off")
```

**Methods and properties**

#### `Rendering.from_table`

```python
@classmethod
Rendering.from_table(table)
```

Builds the settings from a `[tool.pyzed.rendering]` table, ignoring unknown keys and values.

#### `Rendering.to_table`

```python
Rendering.to_table()
```

The settings that are not `"auto"`, as written to `pyproject.toml`.

#### `Rendering.custom`

```python
Rendering.custom  # property
```

Whether any setting is not `"auto"`.

#### `Rendering.env`

```python
Rendering.env()
```

The environment variables that carry these settings to Iced and wgpu.

#### `Rendering.apply`

```python
Rendering.apply(environ=None)
```

Sets the variables of `env()` that are not set yet (yours win); returns the ones it set.

## Async and subscriptions

### `every`

```python
every(seconds, message, *, key=None)
```

A subscription that sends `message` to `update` every `seconds` seconds (like Iced's `time::every`). If `message` is a callable, it is called. Return it from `subscriptions()`.

| Parameter | Description |
| --- | --- |
| `seconds` | Interval in seconds (greater than 0). |
| `message` | Any Python value, or a callable. |
| `key` | Key that identifies the subscription (defaults to the message or the function). |

```python
def subscriptions(self):
    return [pz.every(1, "tick")] if self.running else []
```

### `listen`

```python
listen(function, *, key=None)
```

A subscription that runs `function()` (a generator or async generator) while it is active and sends every value it yields to `update`. Ideal for websockets and streams.

| Parameter | Description |
| --- | --- |
| `function` | Generator function (regular or `async def`). |
| `key` | Key that identifies the subscription (defaults to the message or the function). |

```python
async def feed():
    async for message in websocket:
        yield message

def subscriptions(self):
    return [pz.listen(feed)]
```

### `frames`

```python
frames(callback, *, key=None, max_fps=240.0)
```

A subscription that calls `callback(dt)` once per displayed frame (in sync with the screen, usually 60 times a second), with `dt` the seconds since the previous frame (at most 0.25). Made for games and simulations: move things by `speed * dt`. See [Making games](https://albakore.github.io/pyzed/games/).

| Parameter | Description |
| --- | --- |
| `callback` | Callable that receives `dt` (a `float`). |
| `key` | Key that identifies the subscription (defaults to the message or the function). |
| `max_fps` | Highest rate where the display does not wait for vsync (software rendering). Default 240. |

```python
def subscriptions(self):
    return [] if self.paused else [pz.frames(self.tick)]

def tick(self, dt):
    self.x += game.axis("left", "right") * 300 * dt
```

### `pressed`

```python
pressed()
```

The keys held down right now, as a `frozenset` of names without modifiers (`"left"`, `"space"`, `"a"`…). Empty when no window is open. Poll it every frame for continuous movement; `on_key` is for one-off presses.

### `is_pressed`

```python
is_pressed(*keys, held=None)
```

Whether any of `keys` is held down. `held` replaces `pressed()` (handy in tests).

| Parameter | Description |
| --- | --- |
| `keys` | Key names, such as `"left"`, `"a"`. |
| `held` | Optional set of keys to use instead of `pressed()`. |

```python
if pz.is_pressed("space") and self.cooldown <= 0:
    self.fire()
```

### `Subscription`

What `every` and `listen` return. It is identified by its `key`: as long as `subscriptions()` keeps returning one with the same key, it keeps running; when it disappears, it stops.

### `spawn`

```python
spawn(awaitable)
```

Schedules a coroutine on Pyzed's asyncio loop without waiting for its result and returns a `concurrent.futures.Future`. To receive the result in the UI, return the coroutine from `update` or use `Command.perform`.

| Parameter | Description |
| --- | --- |
| `awaitable` | The coroutine. |

### `asyncio_loop`

```python
asyncio_loop()
```

The asyncio loop (on a background thread) where Pyzed runs every coroutine. It starts the first time it is used.

## Events and components

### `on`

```python
on(widget, *, cursor=None, **handlers)
```

Attaches common event handlers to a widget; same as `widget.on(...)`. Events: `click`, `double_click`, `right_click`, `middle_click`, `mouse_down`, `mouse_up`, `mouse_enter`, `mouse_leave`, `mouse_move`, `scroll`, `drag_start`, `drag`, `drag_end`, `focus`, `blur`, `key_down`, `key_up`, `resize`. See [Events](https://albakore.github.io/pyzed/guides/events/).

| Parameter | Description |
| --- | --- |
| `widget` | The widget (a string is wrapped in a container). |
| `cursor` | Mouse cursor over the widget, such as `"pointer"` or `"grab"`. |
| `handlers` | `event=handler` pairs. A handler that takes an argument gets a `pz.Event`; a non-callable value is a message for `update`; `None` removes it. |

```python
pz.container(card, padding=12).on(click=self.select, drag=lambda e: self.move(e.dx, e.dy))
```

### `Event`

```python
class Event
```

What happened, passed to event handlers: `type`, `x`, `y` (relative to the widget), `dx`, `dy` (scroll or drag movement), `width`, `height`, `button`, `key`, `shift`, `ctrl`, `alt`, `logo`, `window_x`, `window_y`, `screen_x`, `screen_y` (the pointer in the window and on the screen), and `value`/`source` for custom events.

| Parameter | Description |
| --- | --- |
| `type` | Event name. |
| `x` | Pointer x, relative to the widget. |
| `y` | Pointer y, relative to the widget. |
| `dx` | Horizontal scroll (lines) or drag movement. |
| `dy` | Vertical scroll (lines) or drag movement. |
| `width` | Widget width. |
| `height` | Widget height. |
| `button` | `"left"`, `"right"`, `"middle"`... |
| `key` | Key combo, such as `"ctrl-s"`. |
| `shift` | Shift held. |
| `ctrl` | Control held. |
| `alt` | Alt held. |
| `logo` | Cmd/Windows key held. |
| `value` | Value of a custom event. |
| `source` | Component that emitted it. |
| `window_x` | Pointer x in the window (outside it when a drag is released outside). |
| `window_y` | Pointer y in the window. |
| `screen_x` | Pointer x on the screen, or `None` where the platform does not say where windows are (Wayland). `event.screen` gives `(screen_x, screen_y)`. |
| `screen_y` | Pointer y on the screen, or `None`. |

**Methods and properties**

#### `Event.position`

```python
Event.position  # property
```

`(x, y)`.

#### `Event.size`

```python
Event.size  # property
```

`(width, height)`.

#### `Event.screen`

```python
Event.screen  # property
```

`(screen_x, screen_y)`, or `None` when the platform does not report window positions.

### `Dock`

```python
class Dock
```

An editor-style workspace: a `center` with `pz.DockPanel`s docked left, right, bottom or top. Users resize a side by dragging its inner edge and move a panel by dragging its tab onto a drop zone (or from the tab's right-click menu). `on_layout` receives the layout as a dict to save; pass it back as `layout=`. See [Layout](https://albakore.github.io/pyzed/guides/layout/#docks-and-resizable-panels).

| Parameter | Description |
| --- | --- |
| `args` | Props by position: `center`, `panels`, `layout`. |
| `key` | Key that identifies the subscription (defaults to the message or the function). |
| `kwargs` | Props and handlers by name, plus `key=`. |

```python
pz.Dock(center=editor, panels=[
    pz.DockPanel("project", "Project", tree, icon="folder", side="left"),
    pz.DockPanel("terminal", "Terminal", terminal, icon="terminal", side="bottom"),
], layout=self.layout, on_layout=lambda e: setattr(self, "layout", e.value))
```

**Methods and properties**

#### `Dock.side_of`

```python
Dock.side_of(panel)
```

Returns the side a panel is docked on: its saved position if valid, else `panel.side`.

#### `Dock.groups`

```python
Dock.groups()
```

Returns the panels grouped by side (every side present, possibly with an empty list).

#### `Dock.snapshot`

```python
Dock.snapshot()
```

Returns the layout as a plain dict (`positions`, `sizes`, `active`, `hidden`).

#### `Dock.changed`

```python
Dock.changed()
```

Emits `layout` with the current snapshot.

#### `Dock.move`

```python
Dock.move(panel_id, side)
```

Docks a panel on another side and makes it the active tab there.

#### `Dock.select`

```python
Dock.select(side, panel_id)
```

Makes `panel_id` the active tab on `side` (a tab click) and emits `layout`.

#### `Dock.toggle`

```python
Dock.toggle(side)
```

Shows or hides a whole side.

#### `Dock.resized`

```python
Dock.resized(side, size)
```

Records the new `size` (pixels) of `side` after its edge is dragged and emits `layout`.

#### `Dock.start_drag`

```python
Dock.start_drag(panel_id)
```

Starts dragging a panel's tab: the drop zones show and the tab menu closes.

#### `Dock.end_drag`

```python
Dock.end_drag()
```

Ends a tab drag and hides the drop zones, remembering the panel for a late `drop`.

#### `Dock.drop`

```python
Dock.drop(side)
```

Moves the dragged panel to `side` when released on that drop zone; no-op without one.

#### `Dock.tab`

```python
Dock.tab(panel, side, active, t)
```

Builds a panel's tab in a side's header.

#### `Dock.move_menu`

```python
Dock.move_menu(panel, side, t)
```

Builds the right-click menu that moves `panel` to any side other than `side`.

#### `Dock.side_view`

```python
Dock.side_view(side, panels, t)
```

Builds one side: a header with the panels' tabs above the active panel's content.

#### `Dock.drop_zones`

```python
Dock.drop_zones(t)
```

Builds the four drop zones (one per side) shown over the dock while a tab is dragged.

### `DockPanel`

```python
class DockPanel
```

A panel for `pz.Dock`.

| Parameter | Description |
| --- | --- |
| `id` | Stable id (used in the saved layout). |
| `title` | Tab title. |
| `content` | The panel's widget. |
| `icon` | Lucide icon for the tab. |
| `side` | Starting side: `"left"`, `"right"`, `"bottom"` or `"top"`. |

### `Component`

```python
class Component
```

Base class for custom components, like React components: annotated class attributes are props, other attributes are state kept between renders, `render()` returns widgets and `events` declares custom events raised with `self.emit(name, value)`. Calling the class returns a widget. Components appear in the designer's toolbox. See [Custom components](https://albakore.github.io/pyzed/guides/components/).

| Parameter | Description |
| --- | --- |
| `args` | Props, in declaration order (or the children, when the class has a `children` prop). |
| `key` | Key that identifies the subscription (defaults to the message or the function). |
| `kwargs` | Props by name, `on_<event>=` handlers (custom, lifecycle or common events), `key=` to keep state when items move, and `style=`, `class_=`, `id=` and `animate=`. |

```python
class Rating(pz.Component):
    value: int = 0
    events = {"change": "A star was picked."}

    def render(self):
        return pz.row([pz.text("★").on(click=lambda i=i: self.emit("change", i)) for i in range(1, 6)])

Rating(value=3, on_change=lambda e: print(e.value))
```

**Methods and properties**

#### `Component.refresh`

```python
Component.refresh()
```

Draws the component again on the next `view()`, even if its props and state are the same.

#### `Component.create`

```python
@classmethod
Component.create(*args, **kwargs)
```

A standalone instance (not rendered, no lifecycle), handy in tests: `c.render()`.

#### `Component.setup`

```python
Component.setup()
```

Called once before the first render (props are already set): initialize state here.

#### `Component.render`

```python
Component.render()
```

Returns the widgets of this component (called on every render).

#### `Component.provide`

```python
Component.provide()
```

Values to share with every component this one renders (read with `pz.use_context`).

#### `Component.context`

```python
Component.context(name, default=None)
```

The closest shared value called `name` (see `pz.provide`).

#### `Component.on_mount`

```python
Component.on_mount()
```

Called after the first render; may return a `Command` or a message.

#### `Component.on_unmount`

```python
Component.on_unmount()
```

Called when the component is no longer rendered.

#### `Component.emit`

```python
Component.emit(name, value=None)
```

Raises the custom event `name`: calls the handler the parent passed as `on_<name>`.

#### `Component.handles`

```python
Component.handles(name)
```

Whether the parent passed a handler for the custom event `name`.

#### `Component.describe`

```python
@classmethod
Component.describe()
```

The first paragraph of the docstring on one line, in Markdown (shown in the designer).

#### `Component.designer_spec`

```python
@classmethod
Component.designer_spec()
```

This component as an entry of the designer's toolbox (`pyzed.designer.Component`).

### `Color`

```python
class Color
```

Type hint for a component prop that holds a color (a theme token or `"#rrggbb"`): the designer shows a color picker for it. A plain `str` at run time.

```python
tint: pz.Color = "accent"
```

### `Icon`

```python
class Icon
```

Type hint for a component prop that holds a Lucide icon name: the designer shows an icon picker for it. A plain `str` at run time.

```python
mark: pz.Icon = "star"
```

### `Multiline`

```python
class Multiline
```

Type hint for a component prop that holds long text: the designer shows a text area for it. A plain `str` at run time.

```python
notes: pz.Multiline = ""
```

### `FilePath`

```python
class FilePath
```

Type hint for a component prop that holds a file path: the designer shows the path with a button that opens the system's file dialog (a `pathlib.Path` annotation does the same). A plain `str` at run time.

```python
logo: pz.FilePath = ""
```

### `FolderPath`

```python
class FolderPath
```

Type hint for a component prop that holds a folder: the designer shows the path with a button that opens the system's folder dialog. A plain `str` at run time.

```python
output: pz.FolderPath = ""
```

### `Range`

```python
@dataclass
class Range(min, max, step=1)
```

Limits of a number prop, used with `typing.Annotated`: the designer shows a number box limited to them. See [Custom components](https://albakore.github.io/pyzed/guides/components/#in-the-designer).

| Parameter | Description |
| --- | --- |
| `min` | Lowest value. |
| `max` | Highest value. |
| `step` | Step of the + and - buttons. |

```python
level: Annotated[int, pz.Range(0, 10)] = 3
```

### `provide`

```python
provide(**values)
```

A context manager that shares values with every component rendered inside, like React's context. Read them with `pz.use_context(name)` or `self.context(name)`. A component's `provide()` method does the same for what it renders. See [Children, context and styles](https://albakore.github.io/pyzed/guides/components/#children-context-and-styles).

| Parameter | Description |
| --- | --- |
| `values` | The values, by name. |

```python
with pz.provide(user=self.user):
    page = Dashboard()
```

### `use_context`

```python
use_context(name, default=None)
```

The closest value shared as `name` with `pz.provide` or a component's `provide()`.

| Parameter | Description |
| --- | --- |
| `name` | The value's name. |
| `default` | Returned when nothing shares it. |

### `state`

```python
state(default=None, *, doc='')
```

Declares a private state variable on a component class: the parent cannot pass it, and every instance starts with its own copy of the default (lists and dicts are safe). The designer lists it next to the props. See [Custom components](https://albakore.github.io/pyzed/guides/components/).

| Parameter | Description |
| --- | --- |
| `default` | Initial value, copied for each instance. |
| `doc` | Description shown in the designer. |

```python
class Counter(pz.Component):
    step: int = 1
    count: int = pz.state(0)
```

### `State`

```python
class State
```

The default of a state variable declared on the class (see `state`).

### `StateInfo`

```python
class StateInfo
```

A state variable declared with `pz.state`: its name, annotation, default and description.

### `PropInfo`

```python
class PropInfo
```

A prop: its name, type annotation (may be a string) and default.

**Methods and properties**

#### `PropInfo.required`

```python
PropInfo.required  # property
```

Whether the prop has no default and must be passed.

### `find`

```python
find(type_name)
```

The component class registered as `type_name` (see `Component.type_name`).

### `registered`

```python
registered()
```

Every `Component` subclass defined so far that should appear in the designer.

### `render_pass`

```python
render_pass(owner)
```

Tracks the components rendered while `owner` (a window) runs its `view()`.

Components not rendered again are unmounted at the end. The runtime does this for
every window; use it yourself only to render components outside a window.

### `EventInfo`

```python
class EventInfo
```

Documentation of one event: its group and what it reports.

### `accepts_argument`

```python
accepts_argument(handler)
```

Whether `handler` takes the event: it has a required positional parameter or `*args`.

Parameters with defaults do not count, so `lambda i=i: ...` is called with nothing.
The answer is cached per function.

### `LIFECYCLE_EVENTS`

Names of the lifecycle events every component raises (`mount`, `unmount`...).

### `CATALOG`

Every event name Pyzed knows, mapped to its `EventInfo` (what raises it and what `event.value` holds).

### `COMMON`

The events every widget accepts through `widget.on(...)` (click, hover, focus, keys...).

## Hot reload

### `enable`

```python
enable(app, paths=(), *, interval=0.25)
```

Starts hot reload for `app` (a running `App` instance) and returns the reloader.

### `current`

```python
current()
```

The active `Reloader`, or `None` when hot reload is off.

### `is_reloading`

```python
is_reloading()
```

True while modules are being re-executed by a reload.

### `enabled_by_env`

```python
enabled_by_env()
```

Whether `PYZED_RELOAD` asks for hot reload (`1`, `true`, `yes` or `on`).

### `Reloader`

```python
class Reloader
```

Watches the project's files and reloads changed code into a running app.

`app` is the running `App` instance. `paths` are extra folders or files to
watch; by default the folder of the module that defines the app's class is watched.
`interval` is how often, in seconds, files are checked for changes.

Most programs never create one directly: `pz.run(app, reload=True)` does it.

**Methods and properties**

#### `Reloader.watch`

```python
Reloader.watch(path, callback)
```

Calls `callback(path)` on the UI thread whenever `path` changes.

#### `Reloader.project_modules`

```python
Reloader.project_modules()
```

The loaded modules whose files belong to the project, by file path.

#### `Reloader.scan`

```python
Reloader.scan()
```

Checks every watched file once and returns the ones that changed.

#### `Reloader.start`

```python
Reloader.start()
```

Starts the watcher thread and makes this the current reloader.

#### `Reloader.stop`

```python
Reloader.stop()
```

Stops watching files.

#### `Reloader.reload`

```python
Reloader.reload(changed)
```

Reloads the code in `changed` files now (call it on the UI thread).

### `ReloadError`

```python
class ReloadError
```

Raised by `view()` while the last reload failed; the window shows its message.

### `Change`

```python
@dataclass
class Change(name, changed=[], added=[], removed=[], new_state=[], updated_state=[])
```

What one reload changed in a class (see `Reloader.changes`).

### `remember`

```python
remember(obj)
```

Records the initial plain values of `obj` (once), so a reload can tell what the app changed.

The runtime calls it for the app, each window and each component; call it for other
objects created after hot reload started only if you need their defaults updated too.

## Languages

### `t`

```python
t(key, *, language=None, default=None, **values)
```

The text for `key` in the current language, formatted with `values`. Falls back from `"es_AR"` to `"es"`, then to the fallback language, then to the key. See [Languages](https://albakore.github.io/pyzed/guides/i18n/).

| Parameter | Description |
| --- | --- |
| `key` | Dotted key, like `"menu.open"`. |
| `language` | Look it up in another language. |
| `default` | Returned when the key is missing (default: the key). |
| `values` | Values for `{name}` placeholders; `count=` also picks the plural form. |

```python
i18n.add("es", {"greeting": "¡Hola, {name}!", "files": {"one": "{count} archivo", "other": "{count} archivos"}})
i18n.set_language("es")
pz.t("greeting", name="Kev"), pz.t("files", count=3)
```

### `add`

```python
add(language, catalog)
```

Adds or overrides texts for a language. Nested tables become dotted keys; `{"one": ..., "other": ...}` tables are plural forms.

| Parameter | Description |
| --- | --- |
| `language` | Language code, like `"es"` or `"pt_BR"`. |
| `catalog` | Dict of texts. |

### `load`

```python
load(folder)
```

Loads every `<language>.json` and `<language>.toml` in `folder`; returns the languages found.

| Parameter | Description |
| --- | --- |
| `folder` | Folder with the catalog files. |

### `set_language`

```python
set_language(language)
```

Switches the language. The app shows it on its next render, so call it from a handler.

| Parameter | Description |
| --- | --- |
| `language` | Language code, like `"es"`. |

### `language`

```python
language()
```

The current language, normalized (`"es_ar"`).

### `languages`

```python
languages()
```

The languages with a catalog.

### `set_fallback`

```python
set_fallback(language)
```

The language used when a text is missing (default `"en"`).

| Parameter | Description |
| --- | --- |
| `language` | Language code. |

### `on_change`

```python
on_change(listener)
```

Calls `listener(language)` after every switch; returns a function that removes it.

| Parameter | Description |
| --- | --- |
| `listener` | Callable that receives the new language. |

### `system_language`

```python
system_language(default='en')
```

The operating system's language (`LANG`, `LC_ALL` or the locale).

| Parameter | Description |
| --- | --- |
| `default` | Returned when the system reports none. |

### `has`

```python
has(key, *, language=None)
```

Whether `key` has a text in the language or its fallbacks.

| Parameter | Description |
| --- | --- |
| `key` | Dotted key. |
| `language` | Language to check (default: the current one). |

### `normalize`

```python
normalize(language)
```

`"es-AR"`, `"es_AR.UTF-8"` -> `"es_ar"`.

## Built-in reference

### `Browser`

```python
class Browser
```

What a reference viewer shows: the search text, the page open and the back/forward history.

`ui.reference_browser(browser)` draws it; its buttons and links call the methods below.

**Methods and properties**

#### `Browser.open`

```python
Browser.open(id)
```

Shows the page `id` (returns `False` when there is no such page).

#### `Browser.open_symbol`

```python
Browser.open_symbol(symbol)
```

Shows the page about a name written in code; returns whether one was found.

#### `Browser.back`

```python
Browser.back()
```

Goes to the previous page.

#### `Browser.forward`

```python
Browser.forward()
```

Goes to the next page after going back.

#### `Browser.set_query`

```python
Browser.set_query(query)
```

Changes the search text.

#### `Browser.toggle`

```python
Browser.toggle(section)
```

Folds or unfolds a section of the class list.

#### `Browser.results`

```python
Browser.results()
```

The entries matching the search text.

#### `Browser.page`

```python
Browser.page()
```

The page shown (`None` before one is opened).

#### `Browser.follow`

```python
Browser.follow(url)
```

Handles a link of a page: internal links open their page; returns the URL to open otherwise.

### `Entry`

```python
@dataclass
class Entry(id, title, section, group='', summary='', icon='book-open', kind='function')
```

One page of the reference, as search results and the class list show it.

### `Page`

```python
@dataclass
class Page(entry, body, url=None)
```

A full page: the entry it belongs to and its body in Markdown.

**Methods and properties**

#### `Page.id`

```python
Page.id  # property
```

The entry's id.

#### `Page.title`

```python
Page.title  # property
```

The entry's title.

### `Provider`

```python
@dataclass
class Provider(name, entries, page, lookup=None)
```

A section of the reference that comes from somewhere else than the library's API pages.

`entries(lang)` lists its pages, `page(id, lang)` builds one (`None` when the id is not
its own) and `lookup(symbol)` turns a name written in code into one of its ids.

### `register`

```python
register(provider)
```

Adds a section to the reference (it replaces one with the same `name`).

### `entries`

```python
entries(lang=None)
```

Every page of the reference, in class-list order (designer controls first, then the library).

### `sections`

```python
sections(lang=None)
```

The class list: `[(section, [(group, [entries]), ...]), ...]` in order.

### `search`

```python
search(query, lang=None, limit=60)
```

Entries matching `query`: exact names first, then names that start with it, then the rest.

Every word must appear in the title, group or summary (`"tab bar"` finds `ui.tab_bar`).

### `page`

```python
page(id, lang=None)
```

The page with `id` (`KeyError` when there is none).

### `lookup`

```python
lookup(symbol)
```

The id of the page about a name written in code (`"pz.text"`, `"ui.button"`, `"Theme"`...).

### `languages`

```python
languages()
```

The languages the API descriptions are available in.

### `tables_as_lists`

```python
tables_as_lists(markdown)
```

Markdown tables turned into bullet lists (`- first cell: the other cells`).

For viewers whose tables don't wrap long cells, such as `ui.reference_browser` in a narrow tab.
Code blocks are left alone.

### `display_name`

```python
display_name(name)
```

`"pyzed.text"` -> `"pz.text"`, `"pyzed.ui.button"` -> `"ui.button"`.

### `summary`

```python
summary(markdown)
```

The first sentence of a Markdown text, without formatting (for lists and search results).

## Forms and validation

### `validation_errors`

```python
validation_errors(error)
```

Turns a validation error into `{field: message}`, ready for `ui.field(..., error=)`. Accepts a Pydantic or SQLModel `ValidationError`, a Django `ValidationError`, the JSON of a FastAPI 422 response (`{"detail": [...]}`) or its `detail` list. Nested fields are joined with dots and errors that belong to no field use the key `""`. Only the first message of each field is kept. See [Integrations](https://albakore.github.io/pyzed/integrations/overview/#validation-errors-on-each-field).

| Parameter | Description |
| --- | --- |
| `error` | The error, or the JSON of the response. |

```python
try:
    item = ItemIn.model_validate(self.draft)
except ValidationError as error:
    self.errors = pz.validation_errors(error)

ui.field("Price", ui.input(self.draft["price"], self.set_price), error=self.errors.get("price"))
```
