---
description: Render FastHTML markup in isolated previews with current styles, behaviors,
  canned htmx routes, and reusable component examples
output-file: demo.html
title: demo

---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

[`demo`](demo.md#demo) renders ordinary FastHTML markup in an isolated document with the registry's current styles, behaviors, and browser helpers from `reg.hdrs()`, matching a served app. Previews work in notebooks and generated docs without an asset server.

```python
from answerui.registry import hypelt
from fastcore.test import *
from fasthtml.common import P, Details, Summary
from answerui.controls import Btn
from answerui.overlays import Dropdown
```

## Rendering previews

Each preview document includes a stylesheet, behavior script, browser helpers, the icon `spritesheet`, and HTMX 4. FastHTML's `def_hdrs` returns the default app headers: charset and viewport meta tags, HTMX 4 with FastHTML's `htmx-config`, and FastHTML's helper script. [`demo_html`](demo.md#demo_html) passes `surreal=False` to omit Surreal.

htmx comes before the behavior script in `<head>` because the behavior script registers with htmx. Both load before the page body, which includes `spritesheet`. Pass `css` to substitute a custom stylesheet without changing the registry, or `registry` to use another registry's stylesheet, behavior script, and browser helpers instead of `reg`.

[`demo_html`](demo.md#demo_html) sets inline `min-block-size: auto` on `body` to override any full-viewport minimum height rule from the stylesheet. Without that override, an auto-resizing iframe would grow without end.

When FastHTML serves a page, it renames `get`, `post`, `put`, `delete`, `patch`, and `link` to `hx-get`, `hx-post`, `hx-put`, `hx-delete`, `hx-patch`, and `href`, turning each value into a URL. In a preview, [`demo_html`](demo.md#demo_html) renames those same attributes while keeping each path unchanged. Pass `routes` as a dict mapping `'METHOD path'` keys such as `'GET /saved'` to canned FastHTML responses. On HTMX 4's config-request event (using `htmx.config.metaCharacter`), an inline script cancels the network request and swaps the canned markup into the target using the request context's swap style.

---

### demo\_html

```python
def demo_html(
    *fts, # Markup to render
    registry:answerui.registry.Registry=Registry(40 rules, 37 elements), # Registry providing styles, behaviors, and browser helpers
    css=None, # Custom CSS string; None uses the styles from registry.hdrs()
    routes=None, # Canned htmx responses as {'METHOD path': markup}
):
```

*A standalone HTML document containing markup, CSS, behaviors, browser helpers, icon spritesheet, and FastHTML's default headers*

In notebooks, [`demo`](demo.md#demo) renders the preview inside an iframe. That isolates the preview from the host notebook's CSS, such as Solveit's styles, in both directions. The iframe's `srcdoc` attribute holds the complete document from [`demo_html`](demo.md#demo_html). Unless you pass `height`, an inline `ResizeObserver` script resizes the iframe to fit its content. Pass `width` to preview a narrow viewport. A replay button above the iframe reloads `srcdoc` to restart dynamic components such as a self-dismissing notice.

Because the iframe contains the full stylesheet and scripts, storing its HTML in every notebook output would bloat the file. [`demo`](demo.md#demo) returns a [`Preview`](demo.md#preview) object with two representations: the iframe as `text/html` for live display, and the markup alone as `text/markdown` for saved notebooks and language models.

---

### demo

```python
def demo(
    *fts, # Markup to render
    registry:answerui.registry.Registry=Registry(40 rules, 37 elements), # Registry providing styles, behaviors, and browser helpers
    css=None, # Custom CSS string; None uses the styles from registry.hdrs()
    height=None, # Fixed iframe height (e.g. '10rem') for top-layer content ResizeObserver cannot measure; None resizes to content
    width=None, # Fixed iframe width, e.g. '24rem', to preview a narrow viewport; None fills the cell
    routes=None, # Canned htmx responses as {'METHOD path': markup}
):
```

*Render markup in an isolated, replayable notebook preview*

---

### Preview

```python
def Preview(
    fts, frame
):
```

*A rendered preview: the iframe as HTML for live display, and the markup as Markdown for saved notebooks and models*

A preview does not require a registered component. Here `css=''` replaces the registry's stylesheet with an empty one, showing a native element exactly as the browser draws it:

```python
demo(Details(Summary('More information'), P('This disclosure is a native details element.')), css='')
```

Let's recreate the notice from the earlier notebooks with one `hypelt` call that registers its styles and behaviors together. Clicking its `dismiss` button removes the notice. With `autodismiss` set, the `init` handler removes the notice after that many milliseconds (4000 by default) once htmx loads it.

```python
notice_css = r"""
display: block;
padding: .75rem 1rem;
background: #f4f4f6;
border: 1px solid #ccc;
border-radius: 8px;
"""
NoticeBox = hypelt('NoticeBox', css=notice_css, layer='components', on={
    ('& [dismiss]', 'click'): r"el.closest('notice-box').remove()",
    ('&[autodismiss]', 'init'): r"await new Promise(r => setTimeout(r, +el.getAttribute('autodismiss') || 4000)); el.remove()"},
    doc='A dismissible notice.')
```

Click Dismiss, then click the replay button to restore the notice:

```python
demo(NoticeBox('Changes saved. ', Button('Dismiss', type='button', dismiss=True)))
```

`_repr_mimebundle_` returns both representations with `{'nbdev': {'strip': ['text/html']}}` metadata. `nbdev-clean` uses that metadata to strip the iframe HTML from saved notebook outputs and keep the Markdown:

```python
bundle, meta = demo(NoticeBox('Changes saved.'))._repr_mimebundle_()
meta
```

```output
{'nbdev': {'strip': ['text/html']}}
```

This notice disappears after four seconds:

```python
demo(NoticeBox('This notice disappears after four seconds.', autodismiss=4000), height='4rem')
```

Here the Save button requests `/saved`. The canned response returns a `NoticeBox` and a [`Dropdown`](overlays.md#dropdown) (a trigger and a panel). The routes script swaps the complete fragment into place as a served route would. Click Save, open Next action, then click the replay button to reset the preview.

```python
demo(Button('Save', type='button', get='/saved', hx_swap='outerHTML'),
    routes={'GET /saved': (NoticeBox('Saved.'), Dropdown('Next action', Btn('Keep'), Btn('Remove')))})
```

Here we pass a candidate stylesheet via `css` that replaces the notice's grey background with pale yellow. The registered behaviors still apply.

```python
candidate_css = NoticeBox.rules['base'].compiled_css.replace('#f4f4f6', '#fff4cc')
demo(NoticeBox('Trying a warmer surface. ', Button('Dismiss', type='button', dismiss=True)), css=candidate_css)
```

To register an application override for all later previews and application pages, call `NoticeBox.rule`. It adds CSS to the `app` layer without changing the notice's base definition or behaviors:

```python
NoticeBox.rule('corners', 'border-radius: 1rem;', doc='Rounder notice corners.')
demo(NoticeBox('The current stylesheet includes the application override.'))
```

## Reusable examples

Use the [`example`](demo.md#example) decorator to attach a no-argument markup function to a hyperelement as `NoticeBox.example`. Calling `NoticeBox.demo()` renders that markup with the hyperelement's registry.

Attaching another example replaces the previous one. To show multiple variants, return them together from one function.

---

### Hyperelement.demo

```python
def demo(
    *, css=None, # Custom CSS string; None uses the styles from registry.hdrs()
    height=None, # Fixed iframe height (e.g. '10rem') for top-layer content ResizeObserver cannot measure; None resizes to content
    width=None, # Fixed iframe width, e.g. '24rem', to preview a narrow viewport; None fills the cell
    routes=None, # Canned htmx responses as {'METHOD path': markup}
):
```

*Render this hyperelement's example with its registry's current styles and behaviors*

---

### example

```python
def example(
    h
):
```

*Decorator that stores a no-argument markup function as `h.example`, for `h.demo()` to render*

```python
@example(NoticeBox)
def notice_example():
    return Div(NoticeBox('Changes saved. ', Button('Dismiss', type='button', dismiss=True)),
        NoticeBox('This notice stays visible.'), style='display:grid;gap:1rem')
```

The example itself is ordinary markup:

```python
to_xml(NoticeBox.example())
```

```output
'<div style="display:grid;gap:1rem">\n<notice-box>Changes saved. <button type="button" dismiss>Dismiss</button></notice-box><notice-box>This notice stays visible.</notice-box></div>\n'
```

`NoticeBox.demo()` renders it with the current styles and behaviors:

```python
NoticeBox.demo()
```

`NoticeBox.example()` returns fresh FastHTML markup that can be inspected or reused in a larger composition. `NoticeBox.demo()` accepts [`demo`](demo.md#demo)'s options, such as `height` and `css`. Each call to `NoticeBox.demo()` builds a new document from the current example, styles, and behaviors. Clicking the replay button instead restarts interactions by reloading the existing `srcdoc` in the iframe without running Python.

Because each shipped component's notebook exports its `@example` function, importing the component's module attaches the example without rendering anything.

Registering `corners` again replaces the earlier rule in place. The next `NoticeBox.demo()` builds its document with the square corners:

```python
NoticeBox.rule('corners', 'border-radius: 0;', doc='Square notice corners.')
NoticeBox.demo()
```

Calling `hypelt` again with the same name updates the existing `NoticeBox` in place, keeping its example:

```python
NoticeBox = hypelt('NoticeBox', css=notice_css, layer='components', doc='A persistent notice.')
test_is(NoticeBox.example, notice_example)
NoticeBox.demo()
```
