# Toast

> Notifications stacked in the bottom-right corner. A native Pyzed component for Python desktop GUIs, with a live preview, code examples and its API.

Source: https://albakore.github.io/pyzed/library/toast/

:::tip[In plain words]
A small notification that pops up in a corner and goes away by itself.
:::

`ui.toast` draws a notification with a title, a message, actions and a close button; `kind` is `"info"`, `"success"`, `"warning"` or `"error"`. `ui.toasts(base, items)` stacks them in the bottom-right corner over your view.

`ui.toast` · Category: [Overlays](https://albakore.github.io/pyzed/library/#overlays) · [Full reference →](https://albakore.github.io/pyzed/reference/ui/#toast)

**Code:**

```python
pz.column([
    ui.toast("Saved", "main.py was saved.", kind="success", on_dismiss=on_dismiss),
    ui.toast("Update available", "Pyzed 0.4 is on PyPI.", kind="info",
             actions=[ui.button("What's new", on_open, size="sm")], on_dismiss=on_dismiss),
    ui.toast("Could not connect", kind="error", on_dismiss=on_dismiss),
], spacing=8)
```

## When to use

- To confirm something that happened in the background (saved, copied, connected).
- Messages that need an answer belong in a [Dialog](https://albakore.github.io/pyzed/library/confirm/).

## Usage

```python
import pyzed as pz
from pyzed import ui

import threading

class Notes(pz.App):
    def __init__(self):
        self.messages = []

    def notify(self, title):
        self.messages.append(title)
        threading.Timer(3, pz.post, args=(("expire", title),)).start()  # hide it after 3 s

    def update(self, message):
        if message[0] == "expire":
            self.messages.remove(message[1])

    def view(self):
        items = [ui.toast(m, kind="success", on_dismiss=lambda m=m: self.messages.remove(m))
                 for m in self.messages]
        return ui.toasts(self.main_view(), items)
```

## Variants

:::note[About these captures]
Each capture is recorded by pyzed itself, off-screen at 2x, in One Dark or One Light to match this site's theme, and cropped to the component so it shows at its real size. The pointer hovers, presses or types into it; a component that does not react to the pointer cycles through a few themes. With reduced motion you see the first frame. Open **Code** under a capture to see the snippet that draws it; free names such as `on_save` stand for your own callbacks.
:::

### Kind

```python
ui.toast("Update available", "Pyzed 0.5 is on PyPI.")
```

```python
ui.toast("Saved", "main.py was saved.", kind="success")
```

```python
ui.toast("Low disk space", "2 GB left.", kind="warning")
```

```python
ui.toast("Could not connect", "Check your network.", kind="error")
```

### Content

```python
ui.toast("Copied to clipboard", kind="success")
```

```python
ui.toast("Update available", "Restart to install it.",
         actions=[ui.button("Restart", on_restart, size="sm")], on_dismiss=on_dismiss)
```

```python
ui.toast("Now playing", "Lo-fi beats", icon="music", width=280)
```

### States and events

```python
ui.toast("Uploading", "notes.md", kind="info", progress=0.6, on_dismiss=on_close)
```

```python
ui.toast("Build failed", "Click to see the log", kind="error", on_press=on_press)
```

## Events

Toast has **2 events of its own**, listed below. Like every widget it also has the **18 common events** (`click`, `double_click`, `right_click`, `mouse_enter`, `drag`, `key_down`, `resize`…), attached with `.on(...)`: see [Events](https://albakore.github.io/pyzed/guides/events/) and [Events of every component](https://albakore.github.io/pyzed/library/events/).

| Event | Handler gets | When |
| --- | --- | --- |
| `on_dismiss` | `()` | Message or callable sent on close. |
| `on_press` | `()` | Makes the card clickable. |

**Handler gets** is what Pyzed passes to your callable: `()` means nothing. Any handler can also be a message (a value that is not callable), which goes to `update()`.

### Handling the events

The same events written three ways. **Imperative**: methods of the app change `self`. **Declarative**: the handlers produce messages and one `update()` decides. **Functional**: a pure function draws an immutable state and asks for changes with `set_state(...)`. See [Imperative, declarative and functional](https://albakore.github.io/pyzed/guides/code-styles/).

**Imperative:**

```python
class Notes(pz.App):
    def __init__(self):
        self.messages = ["Saved"]
        self.opened = 0

    def view(self):
        items = [ui.toast(m, kind="success",
                          on_dismiss=lambda m=m: self.messages.remove(m),           # its ✕
                          on_press=lambda: setattr(self, "opened", self.opened + 1))  # the card
                 for m in self.messages]
        return ui.toasts(main_view(), items)
```

**Declarative:**

```python
from dataclasses import dataclass

@dataclass
class Dismiss:
    text: str

class Notes(pz.App):
    messages = ["Saved"]

    def update(self, message):
        match message:
            case Dismiss(text):
                self.messages = [m for m in self.messages if m != text]

    def view(self):
        return ui.toasts(main_view(), [ui.toast(m, kind="success", on_dismiss=Dismiss(m))
                                       for m in self.messages])
```

**Functional:**

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class State:
    messages: tuple = ("Saved",)

def view(state, set_state):
    close = lambda m: set_state(messages=tuple(x for x in state.messages if x != m))
    return ui.toasts(main_view(), [ui.toast(m, kind="success", on_dismiss=lambda m=m: close(m))
                                   for m in state.messages])
```

## Properties and API

### `ui.toast`

```python
toast(
    title,
    message=None,
    *,
    kind='info',
    icon=None,
    on_dismiss=None,
    actions=(),
    width=340,
    progress=None,
    on_press=None,
    theme=None,
)
```

A notification.

| Property | Default | Description |
| --- | --- | --- |
| `title` | *required* | Title. |
| `message` | `None` | Secondary text. |
| `kind` | `"info"` | `"info"`, `"success"`, `"warning"` or `"error"`. |
| `icon` | `None` | Name of a Lucide icon (`pyzed icons` lists them). |
| `actions` | `()` | Extra widgets (usually buttons) shown as actions. |
| `width` | `340` | Width: pixels, `"fill"`, `"shrink"` or `"fill:N"` (proportion). |
| `progress` | `None` | 0 to 1: a thin bar at the bottom (time left, a download). |
| `theme` | `None` | Theme to use instead of the current one (`pyzed.theme.current()`). |

Events: `on_dismiss`, `on_press` ([events](#events)).

[Full reference →](https://albakore.github.io/pyzed/reference/ui/#toast)

### `ui.toasts`

```python
toasts(base, items, *, spacing=8)
```

Shows `items` (usually `toast(...)`) stacked in the bottom-right corner over `base`.

| Property | Default | Description |
| --- | --- | --- |
| `base` | *required* | The UI underneath. |
| `items` | *required* | List of toasts. |
| `spacing` | `8` | Space between children, in pixels. |

[Full reference →](https://albakore.github.io/pyzed/reference/ui/#toasts)

## Related

- [Callout](https://albakore.github.io/pyzed/library/callout/): An inline notice with a title, text and actions.
- [Layer](https://albakore.github.io/pyzed/library/layer/): Draws an overlay over your view; clicking outside dismisses it.
- [Alert](https://albakore.github.io/pyzed/library/alert/): A message with one button.
