Skip to content

Dashboard recipes

Short recipes for the parts of a dashboard that live inside a bigger service: a live log, a queue people act on, a big table, several pages, forms that edit data. If you have not built one yet, start with Your first dashboard, which is a single path from an empty file to a working one.

The recipes below are fragments. Each assumes the imports, build and rows of the ones before it, so copy the idea and not the block. The semula demos in the repo (make demo serves all of them in the Studio, under Full apps) are the complete, runnable versions, and every snippet here is taken from them.

Mount it under your app

Create the UI as its own ASGI app and mount it at a prefix of your service. spa=True makes a deep link such as /ui/projects/auth serve the page, so a URL can be opened or reloaded.

from starlette.applications import Starlette
from starlette.routing import Mount
import indah

ui = indah.create_app(
    session_factory=build,  # called once per open tab
    title="my service",
    theme=indah.Theme(light={"primary": "#1f6feb"}, dark={"primary": "#79b8ff"}),
    density="compact",  # tighter tables across the app
    spa=True,
    proxy_flush=False,  # no window-buffering proxy in front of you
)
app = Starlette(routes=[Mount("/ui", app=ui)])

A mounted app does not run its own lifespan, so start background tasks from the parent's lifespan. Pass proxy_flush=False only when no proxy such as Colab's sits in front.

session_factory may take no argument or one Context. The Context is the per-tab handle for everything below: toasts, live feeds, the current route.

def build(ctx: indah.Context) -> indah.Session:
    ...
    return indah.Session(root)

Try it live. Nothing downloads until you press Run it.

The session Context - A session factory gets a Context: the session id, the connection, the user, the in-app path and toast.
def context(ctx: indah.Context) -> indah.Component:
    return indah.Column(
        children=[
            indah.Text(f"Session id: {ctx.sid[:8]}... (one per browser tab)"),
            indah.Text(f"Arrived from client {ctx.conn.client} at app path {ctx.conn.app_path}"),
            indah.Text(lambda: f"Current in-app path: {ctx.path.value}"),
            indah.Text(f"Signed-in user: {ctx.user.id if ctx.user else 'nobody (auth is off)'}"),
            indah.Button("Toast this session", lambda: ctx.toast(f"Hello, tab {ctx.sid[:4]}")),
        ]
    )

This example needs a server: it shows the Studio's own URL paths and a real request's headers, which a page in the docs does not have. Run make demo to try it. Open in the Studio (make demo, then c/overlays/context)

Context - ctx.sid, ctx.conn and ctx.on_close describe this session and its request (secrets such as cookies are left out here).
def context_page(ctx: indah.Context) -> indah.Component:
    ctx.on_close(lambda: CLOSED.append(ctx.sid))  # runs when this session ends
    seen = sorted(k for k in ctx.conn.headers if k in {"user-agent", "accept-language", "host"})
    return indah.Column(
        children=[
            indah.Text(f"Session id: `{ctx.sid[:6]}...` (never show a full one)", markdown=True),
            indah.Text(
                f"Request path `{ctx.conn.path}`, headers seen: {', '.join(seen)}", markdown=True
            ),
            indah.Text(lambda: f"Sessions closed so far: {len(CLOSED)}", markdown=True),
        ]
    )

This example needs a server: it reads a real request's headers (ConnectionInfo), which the browser runtime does not have. Run make demo to try it. Open in the Studio (make demo, then c/extend/context)

Load data before the first paint

The factory may be async def. It is awaited, so its data is in the very first snapshot and the page never shows a dash and then the number:

async def build(ctx: indah.Context) -> indah.Session:
    stats = await fetch_overview()  # a database or HTTP call
    return indah.Session(indah.Column(children=[indah.Stat(stats["entries"], label="Entries")]))


app = indah.create_app(session_factory=build, factory_timeout=1.0)

If the factory takes longer than factory_timeout (1 second by default), the tab starts on a Skeleton and the real page replaces it, on the same stream, when the factory finishes. factory_placeholder= sets a different placeholder. A factory that raises shows the error and the next connection tries again; a tab that closes while it runs cancels it, and its ctx.on_close callbacks still run. A normal (sync) factory is unchanged. Two things to know: a click on a control that is not on the skeleton does nothing until the real page arrives, and factory_timeout and factory_placeholder apply to the built-in store, not to a store= you pass. See examples/async_start.py and the "Async start" app in the Studio.

Push live data to every tab

A Topic lives at app level. Any task publishes to it, and each tab follows it, so every tab updates while per-tab state (filters, selection) stays per tab.

requests = indah.Topic("requests", replay=1000)  # app level, keeps the last 1000

requests.publish({"id": "01J...", "result": "hit"})  # from a task on the event loop
requests.publish_threadsafe({...})  # from any other thread


def build(ctx):
    rows = ctx.tail(requests, limit=1000)  # a bounded Stream, seeded from history
    waiting = ctx.latest(pending, initial=[])  # a signal with the newest item

A Stream sends only new rows to the browser, so a growing log costs O(new rows), not O(all rows). Both calls are released when the tab closes.

Try it live. Nothing downloads until you press Run it.

Topic: one feed, every tab - A producer in the app's lifespan publishes to a Topic. Each tab follows it with ctx.tail (rows) and ctx.latest (the newest). Open this page in two tabs.
def topic(ctx: indah.Context) -> indah.Component:
    rows = ctx.tail(EVENTS, limit=100)  # a Stream seeded from the topic's history
    newest = ctx.latest(EVENTS)  # a signal holding the newest item
    return indah.Column(
        children=[
            indah.Text(lambda: f"Newest event: {newest.value['id']} ({newest.value['kind']})"),
            indah.Table(rows=rows, key="id", columns=EVENT_COLUMNS, height="16rem", follow=True),
        ]
    )

This example needs a server: Topic needs an app object (ctx.app), which the browser runtime does not have yet. Run make demo to try it. Open in the Studio (make demo, then c/live/topic)

Bounded streams - ctx.tail(topic, limit=5) keeps the newest five and sends only new rows, so a log that never ends costs a constant amount.
def bounded(ctx: indah.Context) -> indah.Component:
    last5 = ctx.tail(EVENTS, limit=5)  # only the newest five are kept, on the server and in the tab
    seen = indah.Signal(0)
    stop = indah.Signal(False)
    ctx.on_close(EVENTS.subscribe(lambda _e: None if stop.value else seen.set(seen.value + 1)))
    return indah.Column(
        children=[
            indah.Text(lambda: f"{seen.value} events seen since you opened this page"),
            indah.Text(lambda: f"{len(last5.value)} kept (limit {last5.limit})"),
            indah.List(
                lambda: [f"{e['id']}  {e['kind']}" for e in last5.value], empty="Waiting..."
            ),
            indah.Switch(stop, label="Pause counting"),
        ]
    )

This example needs a server: ctx.tail reads an app object (ctx.app), which the browser runtime does not have yet. Run make demo to try it. Open in the Studio (make demo, then c/live/bounded)

A refresh loop per tab: ctx.every and ctx.spawn

Work that should run while a tab is open, and stop when it closes, belongs on the context.

def build(ctx):
    count = indah.Signal(0)

    async def refresh():  # a plain function works too
        count.set(await fetch_pending_count())

    ctx.every(5, refresh, immediately=True)  # now, then every 5 seconds
    ctx.spawn(watch_something(ctx))  # any coroutine, for the life of the session

Both are cancelled when the session ends: a closed tab, an eviction or an idle reaping. An exception is logged once and the loop carries on (it logs again only after a successful call), so one bad fetch does not stop the refresh. Call them from the session factory or a handler, where an event loop is running; a plain function you pass to every runs on that loop, so keep it short.

Try it live. Nothing downloads until you press Run it.

ctx.every and ctx.spawn - A refresh loop and a background task that belong to this tab: ctx.every calls a function on a timer and ctx.spawn runs a coroutine. Both stop when the tab closes, and a failing call is logged once without stopping the loop.
def every(ctx: indah.Context) -> indah.Component:
    ticks = indah.Signal(0)
    ctx.every(0.5, lambda: ticks.set(ticks.value + 1), immediately=True)  # stops with the tab
    ran = indah.Signal("not yet")

    async def background() -> None:
        await asyncio.sleep(0.5)
        ran.set("done")

    ctx.spawn(background())  # any coroutine, cancelled if the tab closes first
    return indah.Column(
        children=[
            indah.Text(lambda: f"Refreshed {ticks.value} time(s)"),
            indah.Text(lambda: f"Background task: {ran.value}"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/live/every)

The tab's title and icon: ctx.title and ctx.favicon

A parked call should show in the browser tab, even when the viewer is on another tab. Set ctx.title (the whole title) and ctx.favicon (the name of an icon you registered) from any handler or ctx.every loop:

app = indah.create_app(
    session_factory=build,
    title="semula",
    favicons={"alert": "static/red-dot.svg"},  # a PNG, SVG, ICO, JPEG or WebP, up to 64 KB each
)


def build(ctx):
    def refresh():
        n = parked.value
        ctx.title.set(f"({n}) semula" if n else None)  # None puts the app's own title back
        ctx.favicon.set("alert" if n else None)

    ctx.every(5, refresh, immediately=True)
    ...

The change reaches this session's tab only, with no reload, and a reload or a reconnect keeps it. A new session starts with the app's own title and icon. Titles are cut at 200 characters. A favicon name that is not registered is ignored with a warning. The icons are served by the app itself, so this works under csp="strict".

Try it live. Nothing downloads until you press Run it.

Tab title and favicon - ctx.title and ctx.favicon change this tab's title and icon without a reload, for an attention cue like "(2) app" with a red dot. Icons are registered with create_app(favicons=); None puts the app's own back. Other tabs are untouched.
def tab_title(ctx: indah.Context) -> indah.Component:
    pending = indah.Signal(0)

    def sync() -> None:
        n = pending.value
        ctx.title.set(f"({n}) {_TAB_TITLE}" if n else None)  # None puts the app's title back
        ctx.favicon.set("alert" if n else None)  # a name from create_app(favicons=)

    def add() -> None:
        pending.set(pending.value + 1)
        sync()

    def clear() -> None:
        pending.set(0)
        sync()

    return indah.Column(
        children=[
            indah.Text(lambda: f"{pending.value} pending: look at this browser tab"),
            indah.Row(
                children=[
                    indah.Button("Add a pending call", on_click=add),
                    indah.Button("Clear", on_click=clear, variant="ghost"),
                ]
            ),
        ]
    )

This example needs a server: favicons are served from api/brand/favicon/<name>, a route the browser runtime does not provide. Run make demo to try it. Open in the Studio (make demo, then c/live/tab-title)

Show and act on rows with Table

The rich Table takes dict rows with a stable key and typed columns.

from indah import Table, Col, RowAction, Signal

checked = Signal([])
table = Table(
    rows=rows,  # a list, a signal, or a Stream
    key="id",
    columns=[
        Col("ts", "When", kind="time"),  # "3s ago", refreshed live
        # Col("ts", "At", kind="time", time_format="clock"),  # 09:14:22.318, viewer's local time
        Col("id", kind="mono"),
        Col("result", kind="badge", tones={"hit": "ok", "miss": "warn", "error": "err"}),
        Col("ms", kind="number"),
    ],
    height="24rem",  # the body scrolls under a sticky header
    search=True,  # a filter box
    column_toggle=True,
    follow=True,  # keep the newest row in view (streamed rows)
    actions=[RowAction("Reject", reject, confirm="Reject this call?")],
    checked=checked,  # a checkbox column plus select-all
)
  • RowAction(label, on_click, confirm=, when=) calls on_click(key). A row can be stale by the time the click lands, so the handler must tolerate a key that no longer exists. label may be a function of the row and when a bool or a function of the row; see "A members table" below.
  • A members table: the button reads "Make editor" on a viewer and "Make viewer" on an editor, and the last admin has none.
RowAction(
    lambda row: "Make editor" if row["role"] == "viewer" else "Make viewer",
    change_role,  # on_click(key)
    confirm="Change this role?",
    when=lambda row: row["id"] != last_admin_id(),  # no button on this row
)

row is that row's dict. The label and visibility are worked out on the server and sent with each row, so a plain string label sends nothing extra. when hides the button; it does not stop a crafted click, so keep the real check in change_role (or your authorization layer). A function that raises hides the button for that row. - Col(kind="cell", render=spec, sort_key="field") draws a composite cell from the row's fields, with the same spec vocabulary as a List item (text and bind name row fields). It is display only, and it sorts and is searched by sort_key. Keep a cell to one line in a virtual table. Col("prompt", truncate=True, max_width="30ch") clips a long value with an ellipsis and shows the full text on hover; wrap=True lets it wrap instead (not with virtual=True). Both are off by default. The Studio page "Table: composite cells" shows them. - density="compact" shrinks one table. Pass a Signal[str] to let the viewer toggle it. - on_open=fn (or keyboard=True) makes the table drivable from the keyboard. Tab or click to focus it, then j/k or the arrows move the active row, Home/End jump, PageUp/PageDown move a screenful, Space ticks a row of a checked= table, and Enter calls fn(key) (sync or async; without on_open, Enter selects like a click). Moving never posts anything. The active row is held by key, so streamed rows, sorting and follow= do not move it (End resumes following), and at the edge of a paged or remote table the arrow turns the page. Escape or Tab leaves the table. Off by default, so an existing table is unchanged. See "Keys and focus" below.

Try these live (5 examples)
Table: typed columns - Dict rows with a stable key and typed Cols: time, mono, badge, number. Try the filter box, the column menu and the density switch.
def table_rich(ctx: indah.Context) -> indah.Component:
    calls = make_calls(40)
    picked = indah.Signal(None)
    density = indah.Signal("comfortable")
    return indah.Column(
        children=[
            indah.Radio(density, options=["comfortable", "compact"], label="Density"),
            indah.Table(
                rows=calls,
                key="id",
                selected=picked,
                height="18rem",
                search=True,
                column_toggle=True,
                density=density,
                columns=[
                    indah.Col("ts", "When", kind="time", time_format="clock"),
                    indah.Col("id", kind="mono"),
                    indah.Col("route"),
                    indah.Col("status", kind="badge", tones=STATUS_TONES),
                    indah.Col("ms", "Latency (ms)", kind="number"),
                ],
            ),
            indah.Text(lambda: f"Selected key: {picked.value}"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-rich)

Table: composite cells - A Col(kind="cell", render=...) draws a cell from the row's fields (a meter, a two-line caller); truncate= clips a long prompt with a tooltip, wrap= lets a note wrap. Sort the Match column and search.
def table_cells(ctx: indah.Context) -> indah.Component:
    rows = [
        {
            "id": f"req-{i:02d}",
            "who": ["ana", "bo", "cy", "dee"][i % 4],
            "route": ["/chat", "/summarise", "/classify"][i % 3],
            "prompt": text,
            "note": "Matched on the first try. " * (1 + i % 3),
            "tier": tier,
        }
        for i, (text, tier) in enumerate(PROMPTS)
    ]
    match = {
        "tag": "meter",
        "attrs": {"min": "0", "max": "5", "aria-label": "Match tier"},
        "bind": {"value": "tier"},
    }
    who = {
        "tag": "div",
        "children": [
            {"tag": "strong", "text": "who"},
            {"tag": "small", "text": "route", "class": "muted"},
        ],
    }
    return indah.Table(
        rows=rows,
        key="id",
        search=True,
        height="20rem",
        columns=[
            indah.Col("id", kind="mono"),
            indah.Col("who", "Caller", kind="cell", render=who),
            indah.Col("tier", "Match", kind="cell", render=match, sort_key="tier", width="9rem"),
            indah.Col("prompt", "Prompt", truncate=True, max_width="26ch"),
            indah.Col("note", "Notes", wrap=True, width="14rem"),
        ],
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-cells)

Table: row actions and checkboxes - A RowAction per row (this one asks first) and a checked signal for bulk work.
def table_actions(ctx: indah.Context) -> indah.Component:
    rows = indah.Signal(make_calls(8, seed=1))
    checked = indah.Signal([])

    def archive(key) -> None:  # the row may be gone already: tolerate that
        rows.set([r for r in rows.value if r["id"] != key])
        ctx.toast(f"Archived {key}", kind="success")

    def archive_checked() -> None:
        gone = set(checked.value)
        rows.set([r for r in rows.value if r["id"] not in gone])
        checked.set([])
        ctx.toast(f"Archived {len(gone)} rows", kind="success")

    return indah.Column(
        children=[
            indah.Table(
                rows=rows,
                key="id",
                checked=checked,
                actions=[indah.RowAction("Archive", archive, confirm="Archive this call?")],
                columns=[
                    indah.Col("id", kind="mono"),
                    indah.Col("route"),
                    indah.Col("status", kind="badge", tones=STATUS_TONES),
                ],
            ),
            indah.Row(
                children=[
                    indah.Button("Archive checked", archive_checked, variant="tonal"),
                    indah.Text(lambda: f"{len(checked.value)} checked, {len(rows.value)} rows"),
                ]
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-actions)

Table: keyboard navigation - Tab into the table, then j/k or the arrows move the active row, Home/End jump, Space ticks, Enter opens (on_open=). The j below is also a Shortcuts key: it moves the row while the table has focus and rings the bell anywhere else.
def table_keyboard(ctx: indah.Context) -> indah.Component:
    calls = make_calls(40, seed=3)
    opened = indah.Signal("nothing opened yet")
    bells = indah.Signal(0)
    checked = indah.Signal([])

    def open_call(key: str) -> None:
        opened.set(f"opened {key}")

    return indah.Column(
        children=[
            indah.Shortcuts({"j": (lambda: bells.set(bells.value + 1), "Ring the bell")}),
            indah.Text(
                lambda: f"{opened.value}. The page-wide j shortcut fired {bells.value} times."
            ),
            indah.Table(
                rows=calls,
                key="id",
                height="16rem",
                checked=checked,
                on_open=open_call,
                narrow="cards",  # a labelled card per row below 560 px (IND-258)
                columns=[
                    indah.Col("id", kind="mono"),
                    indah.Col("route"),
                    indah.Col("status", kind="badge", tones=STATUS_TONES),
                ],
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-keyboard)

Table: follow a Stream - A Stream sends only new rows and keeps the newest limit. The table follows the tail; scroll up and it pauses.
def table_follow(ctx: indah.Context) -> indah.Component:
    stream = indah.Stream(make_calls(12), limit=30)  # keeps only the newest 30
    calls = make_calls(100, seed=9)
    cursor = {"i": 0}

    def add(n: int) -> None:
        batch = calls[cursor["i"] : cursor["i"] + n]
        cursor["i"] += n
        stream.append(
            *[
                {**r, "id": f"live-{cursor['i'] - len(batch) + k + 1:03d}"}
                for k, r in enumerate(batch)
            ]
        )

    return indah.Column(
        children=[
            indah.Row(
                children=[
                    indah.Button("Add 5 rows", lambda: add(5)),
                    indah.Button("Add 40 rows", lambda: add(40), variant="tonal"),
                    indah.Text(lambda: f"{len(stream.value)} rows kept (limit {stream.limit})"),
                ]
            ),
            indah.Table(
                rows=stream,
                key="id",
                height="16rem",
                follow=True,
                columns=[
                    indah.Col("id", kind="mono"),
                    indah.Col("route"),
                    indah.Col("status", kind="badge", tones=STATUS_TONES),
                ],
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-follow)

Tens of thousands of rows: remote= and virtual=

For more rows than one prop should carry, give the table a loader. It is asked for one window at a time, with the viewer's search, sort and offset.

def loader(q: indah.TableQuery):
    rows, total = db.page(search=q.search, sort=q.sort, offset=q.offset, limit=q.limit)
    return rows, total


table = Table(
    columns=[Col("id", kind="mono"), Col("name")],
    key="id",
    remote=loader,  # sync loaders run in a worker thread
    virtual=True,  # render only the rows in view
    height="30rem",
    search=True,
    reload_on=[project],  # re-run the last query when a signal changes
)

Things to know about a remote table:

  • Sorting and search are the loader's job. A loader that ignores them is a bug in your app.
  • follow=True is not available with remote= and raises a ValueError.
  • The header checkbox ticks only the rows on screen. With checked= the table shows "N of M selected" and a Select all M button that gathers every match for the current search, up to 10,000 rows. Over that, the table asks the viewer to narrow the search.
  • query= mirrors the latest TableQuery into a signal, and page_size sets the window.

Try it live. Nothing downloads until you press Run it.

Table: 5,000 rows, remote and virtual - The table holds no rows: it asks a loader for the window in view, with the search and sort. Scroll, sort, filter, then use Select all.
def table_remote(ctx: indah.Context) -> indah.Component:
    checked = indah.Signal([])

    def loader(q: indah.TableQuery):  # the loader owns search and sort
        rows = [n for n in NODES if q.search.lower() in n["id"] + n["zone"]]
        if q.sort:
            rows.sort(key=lambda n: n[q.sort[0]], reverse=q.sort[1] == "desc")
        return rows[q.offset : q.offset + q.limit], len(rows)

    return indah.Column(
        children=[
            indah.Table(
                key="id",
                remote=loader,
                virtual=True,
                height="20rem",
                search=True,
                checked=checked,
                density="compact",
                columns=[
                    indah.Col("id", kind="mono"),
                    indah.Col("zone"),
                    indah.Col("cpu", "CPU %", kind="number"),
                    indah.Col(
                        "state", kind="badge", tones={"up": "ok", "drain": "warn", "down": "err"}
                    ),
                ],
            ),
            indah.Text(lambda: f"{len(checked.value)} node(s) checked"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/table-remote)

Slow handlers: keep the loop free

indah serves every tab from one event loop. A plain def handler runs on that loop, and a blocking call inside an async def handler does too, so while it runs no tab on the server updates. A time.sleep(5), a requests.get, a synchronous database driver or a model call all stall everyone. Awaiting is fine: await asyncio.sleep(5) yields to the other tabs.

Run blocking work in a thread and await it:

import asyncio
import sqlite3

import indah

rows = indah.Signal([])


def query(sql: str) -> list:  # blocking: never call it on the loop
    with sqlite3.connect("app.db") as db:
        db.row_factory = sqlite3.Row
        return [dict(r) for r in db.execute(sql)]


async def refresh():
    rows.set(await asyncio.to_thread(query, "select id, text from entries limit 100"))


page = indah.Column(
    children=[
        indah.Button("Refresh", on_click=refresh),
        indah.Table(rows=rows, key="id", columns=[indah.Col("id"), indah.Col("text")]),
    ]
)

Table(remote=loader) already does this for you: a plain def loader runs in a worker thread, so a blocking database call there is fine. An async def loader runs on the loop, so the same rule applies inside it.

Overlays, toasts and keys

open_ = indah.Signal(False)

indah.Button("Delete", delete, confirm="Delete this entry?")  # asks first
indah.Modal(title="Conflict", open=open_, size="lg", children=[...])
indah.Drawer(title="Review", open=open_, side="right", children=[...])

indah.Menu(
    "Actions",
    [
        indah.MenuItem("Rename", rename, shortcut="F2"),  # shortcut is display text only
        indah.MenuItem("Delete", delete, danger=True, confirm="Delete this entry?"),
    ],
)  # a menu button; items may also be a Signal, Computed or function returning the list

ctx.toast("Saved", kind="success")  # info, success, warn or error; ttl=0 sticks
ctx.toast("Approved", ttl=8, action=("Undo", undo))  # a button; runs undo once, then dismisses
indah.Badge(lambda: f"{n.value} waiting", tone="warn")
indah.Switch(pinned, label="Pinned")
indah.Text("hover me", tooltip="Shown on hover and on keyboard focus")

indah.Shortcuts(
    {
        "j": (next_row, "Next call"),  # the optional text feeds the ? help
        "a": (approve, "Approve"),
        "g l": (go_log, "Go to the log"),  # a sequence
    }
)

A Menu opens on click, Enter, Space or the arrow keys and follows the usual menu keys: Up and Down move (and wrap), Home and End jump, a letter moves to the next item that starts with it, Escape closes and returns focus to the trigger, and Tab closes and moves on, so the keyboard is never trapped. Choosing an item closes the menu and runs its handler. A MenuItem(shortcut="F2") only shows the key; bind it with Shortcuts. Items are matched by key= (default: the label) against the current list, so a click that lands as an item disappears does nothing. To leave an item out for someone who may not use it, build the list with ctx.only(perm, lambda: MenuItem(...)) and wrap the handler in guard(perm): an omitted item is never sent, and guard checks again at the click. A Menu goes in a row, a card or a rail; a table cell is display only, so keep RowAction for per-row buttons.

Try these live (6 examples)
Modal and Drawer - Each is an open signal plus children. Esc, the backdrop or the x closes it and runs on_close.
def modal_drawer(ctx: indah.Context) -> indah.Component:
    modal = indah.Signal(False)
    drawer = indah.Signal(False)
    closed = indah.Signal("Nothing closed yet.")
    return indah.Column(
        children=[
            indah.Row(
                children=[
                    indah.Button("Open modal", lambda: modal.set(True)),
                    indah.Button("Open drawer", lambda: drawer.set(True), variant="tonal"),
                ]
            ),
            indah.Text(lambda: closed.value),
            indah.Modal(
                title="A modal",
                open=modal,
                size="sm",
                on_close=lambda: closed.set("The modal closed."),
                children=[indah.Text("Esc, the backdrop or the x closes it.")],
            ),
            indah.Drawer(
                title="A drawer",
                open=drawer,
                side="right",
                on_close=lambda: closed.set("The drawer closed."),
                children=[indah.Text("Same behaviour, sliding in from the side.")],
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/modal-drawer)

Toasts - ctx.toast(message, kind=..., ttl=...) reaches this tab only. ttl=0 keeps it until clicked.
def toasts(ctx: indah.Context) -> indah.Component:
    def show(kind: str):
        return lambda: ctx.toast(f"This is a {kind} toast", kind=kind)

    return indah.Row(
        children=[
            *[
                indah.Button(k, show(k), variant="tonal")
                for k in ("info", "success", "warn", "error")
            ],
            indah.Button(
                "sticky",
                lambda: ctx.toast("Click me to dismiss", kind="info", ttl=0),
                variant="ghost",
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/toasts)

Toast with an action - ctx.toast(msg, action=("Undo", fn), ttl=8) adds a button. Clicking it runs fn once and dismisses the toast; it goes to this tab only. guard() is checked when the button is clicked.
def toast_action(ctx: indah.Context) -> indah.Component:
    pending = indah.Signal(["alpha", "beta", "gamma"])
    done = indah.Signal([])

    def approve() -> None:
        if not pending.value:
            return
        name = pending.value[0]
        pending.set(pending.value[1:])
        done.set([*done.value, name])

        def undo() -> None:  # runs once, when the button is clicked
            done.set([d for d in done.value if d != name])
            pending.set([name, *pending.value])

        ctx.toast(f"Approved {name}", kind="success", ttl=8, action=("Undo", undo))

    return indah.Column(
        children=[
            indah.Text(lambda: f"Pending: {', '.join(pending.value) or 'none'}"),
            indah.Text(lambda: f"Approved: {', '.join(done.value) or 'none'}"),
            indah.Button("Approve next", approve, variant="tonal"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/toast-action)

Confirm before acting - Button(confirm=...) asks first and posts the click only if you accept. It is a UX guard, not authorization.
def confirm(ctx: indah.Context) -> indah.Component:
    items = indah.Signal(["alpha", "beta", "gamma"])
    return indah.Column(
        children=[
            indah.Text(lambda: f"Entries: {', '.join(items.value) or 'none'}"),
            indah.Button(
                "Delete all",
                lambda: items.set([]),
                variant="ghost",
                confirm="Delete all entries?",
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/confirm)

Menu - Menu(trigger, items) is a menu button: arrow keys, Home/End, a letter to jump, Escape back to the trigger. An item can be a danger, ask to confirm, be disabled or show a shortcut (text only). The items may follow a signal.
def menu(ctx: indah.Context) -> indah.Component:
    status = indah.Signal("Nothing chosen yet.")
    locked = indah.Signal(False)

    def say(text: str):
        return lambda: status.set(text)

    # The items are a function of `locked`, so the menu follows the switch with no reload.
    items = indah.Computed(
        lambda: [
            indah.MenuItem("Rename", say("Renamed."), shortcut="F2"),
            indah.MenuItem("Duplicate", say("Duplicated.")),
            indah.MenuItem("Archive", say("Archived."), disabled=True),
            indah.MenuItem(
                "Delete",
                say("Deleted."),
                danger=True,
                confirm="Delete this project?",
                disabled=locked.value,
            ),
        ]
    )
    return indah.Column(
        children=[
            indah.Row(
                children=[
                    indah.Menu("Actions", items),
                    indah.Switch(locked, label="Locked"),
                ]
            ),
            indah.Text(lambda: status.value),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/menu)

Badge, Switch and tooltips - A Badge tone and text may be reactive, a Switch is a boolean input, and any component takes tooltip=.
def badges(ctx: indah.Context) -> indah.Component:
    pinned = indah.Signal(False)
    waiting = indah.Signal(3)
    return indah.Column(
        children=[
            indah.Row(
                children=[
                    indah.Badge("neutral"),
                    indah.Badge("ok", tone="ok"),
                    indah.Badge("warn", tone="warn"),
                    indah.Badge("err", tone="err"),
                    indah.Badge("info", tone="info"),
                ]
            ),
            indah.Row(
                children=[
                    indah.Badge(lambda: f"{waiting.value} waiting", tone="warn"),
                    indah.Button("Take one", lambda: waiting.set(max(0, waiting.value - 1))),
                ]
            ),
            indah.Switch(pinned, label="Pinned"),
            # The tone is a callable, so the chip changes colour with the switch.
            indah.Badge(
                lambda: "pass" if pinned.value else "fail",
                tone=lambda: "ok" if pinned.value else "err",
            ),
            indah.Text(lambda: "Pinned." if pinned.value else "Not pinned."),
            indah.Text("Hover or focus me", tooltip="Shown on hover and on keyboard focus"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/badges)

A command palette

CommandPalette(commands) is the dashboard driven like a terminal: press Ctrl+K (Cmd+K on a Mac), type, and press Enter. Arrows move, Escape closes and puts focus back where it was.

palette = indah.CommandPalette(
    [
        indah.Command("Open the log", to="/log", group="Go to"),
        indah.Command("Pause intake", pause, group="Actions", keywords="stop halt"),
        indah.Command("Delete all", wipe, group="Actions", confirm="Delete every entry?"),
    ],
    ctx=ctx,  # needed only for a jump (`to=`): it moves this tab, like `ctx.navigate`
)

A command either runs a function (sync or async) or jumps to an in-app page. The filter runs in the browser over the list it was sent, so typing costs no round trip. The match order is stable: a label that starts with what you typed, then one with a word that does, then one that contains it, then one that contains it as a subsequence (gl finds "Go to log"), then a match in the keywords or the group; ties keep the order you gave. Put commands of one group next to each other, since the empty palette shows a heading each time the group changes.

Commands for a page. commands can be a Signal, Computed or function, and the palette re-sends its list when it changes. To add a page's own commands, return the app's list plus the current page's from one function that reads ctx.path (or a signal): the commands appear when the page shows and leave with it.

def commands():
    out = list(app_commands)
    if ctx.path.value.startswith("/log"):
        out.append(indah.Command("Clear the log", clear_log, group="This page"))
    return out


indah.CommandPalette(commands, ctx=ctx)

The shortcut opens it from anywhere that is not already in a dialog. A bare key such as shortcut="/" is ignored while the viewer types in a field; a mod+ combo is not. Do not map the same key in Shortcuts. To leave a command out for someone who may not use it, build the list with ctx.only(perm, lambda: Command(...)) and wrap the handler in guard(perm): an omitted command is never sent, a forged run of it does nothing, and guard checks again when it runs. Like Menu, a run is matched by key= (default: the label) against the current list.

confirm= is a UX guard only: the server still runs any click it receives, so check authorization in your handler. A toast goes to the current tab only, never put a secret in one. A toast's action= button runs its function once as that tab's user, so a guard() on it is checked at the click, and a second click or a stale toast does nothing. Give an undo a longer ttl than the default 4 seconds. Shortcuts bare keys are ignored while the viewer types or a dialog is open, and a map is active only while it is in the rendered tree.

Try it live. Nothing downloads until you press Run it.

Command palette - CommandPalette(commands) opens on Ctrl/Cmd+K: type to filter (a prefix first, then a word, a substring, a subsequence, then keywords), arrows move, Enter runs, Escape closes. Commands can run a function, jump to a page (to=), ask to confirm, and a page can add its own.
def command_palette(ctx: indah.Context) -> indah.Component:
    status = indah.Signal("Press Ctrl+K (or Cmd+K), type, and press Enter.")
    on_log_page = indah.Signal(False)

    def say(text: str):
        return lambda: status.set(text)

    # The list is a function of `on_log_page`: a page's own commands join the app's while it shows,
    # and leave with it. A jump command (`Command("Log", to="/log")`) takes `ctx=` on the palette.
    commands = indah.Computed(
        lambda: [
            indah.Command("Open the log", say("Opened the log."), group="Go to", shortcut="g l"),
            indah.Command("Open pending", say("Opened pending."), group="Go to"),
            indah.Command(
                "Pause intake", say("Paused."), group="Actions", keywords="stop halt freeze"
            ),
            indah.Command(
                "Delete all entries",
                say("Deleted."),
                group="Actions",
                confirm="Delete every entry?",
            ),
            *(
                [indah.Command("Clear the log", say("Cleared."), group="This page")]
                if on_log_page.value
                else []
            ),
        ]
    )
    return indah.Column(
        children=[
            indah.CommandPalette(commands, ctx=ctx),
            indah.Switch(on_log_page, label="On the log page"),
            indah.Text(lambda: status.value),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/command-palette)

Keys and focus

A widget that owns keys while it has focus (the keyboard Table, and the command palette) goes first. It acts only on keys aimed at itself, never on a key typed into an input inside it or one with ctrl, cmd or alt held, and it marks the key as handled, which Shortcuts respects. So with a keyboard Table focused, j moves its row; anywhere else the same j runs your Shortcuts binding. mod+k is the command palette's default key; give it another shortcut= if you want mod+k for something else. Tab and Escape always leave. Use mod+ or alt+ combos for page-wide actions and bare keys for the focused widget.

Try it live. Nothing downloads until you press Run it.

Keyboard shortcuts - Shortcuts maps keys (and sequences like g c) to handlers; ? opens a help overlay built from the labels.
def shortcuts(ctx: indah.Context) -> indah.Component:
    count = indah.Signal(0)
    return indah.Column(
        children=[
            indah.Text("Click the page body, then press a, r or g c. Press ? for the help."),
            indah.Text(lambda: f"Count: {count.value}"),
            indah.Shortcuts(
                {
                    "a": (lambda: count.set(count.value + 1), "Add one"),
                    "r": (lambda: count.set(0), "Reset the count"),
                    "g c": (lambda: count.set(100), "Jump to one hundred"),
                }
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/shortcuts)

Several pages with Router

The full steps, with a complete file, are in How to add several pages. This is the short version.

def build(ctx):
    pages = indah.Router(
        ctx,
        routes={
            "/": overview,
            "/projects/{project}": project_page,
            "/projects/{project}/entries/{entry_id}": entry_page,
        },
        not_found=indah.Text("No such page"),
    )
    nav = indah.Column(
        children=[
            indah.Link(ctx, "Overview", to="/"),
            indah.Link(ctx, "Projects", to="/projects", match="prefix"),
        ]
    )
    return indah.Session(indah.Sidebar(children=[nav, pages]))

ctx.path is the current page, ctx.params holds the route's values, and ctx.navigate("/x") goes there from code. A Link is a real <a href>, so open-in-new-tab works.

A Link whose to= is a function of ctx.params is safe against a crafted address: if the function returns something that is not an in-app path (a newline, a space, a backslash), the link points at /, is never active, and the stream carries on. ctx.navigate still raises ValueError for such a path, since that is your code's mistake rather than the visitor's.

In a rail, use NavItem(ctx, "Pending", to="/pending", badge=count, icon="..."): a Link with a live count at its end that disappears when the count is zero or empty.

Hidden pages still run

Every page is built up front, so a page's reactive code runs even when its route is not showing, with no params. Read params with ctx.params.value.get("project"), never ctx.params.value["project"], and keep expensive work behind a computed. Do not put anything role-restricted in a page: hidden pages are in the page snapshot.

{id:int} converts a segment to an integer. After a server restart an open tab reopens on the page it is on now.

One Router per session

The address bar holds one path per tab, so a session can have only one Router; a second raises ValueError. To show routing inside part of a page (a docs chapter, a card), use Tabs, or a Signal with a computed, for that switcher; or run the routed app on its own and link to it. Nested routers are not supported.

Try these live (3 examples)
Link and active state - A Link is a real anchor: middle-click opens a tab, a plain click navigates without a reload.
def links(ctx: indah.Context) -> indah.Component:
    return indah.Column(
        children=[
            indah.Text(lambda: f"ctx.path is {ctx.path.value!r}"),
            indah.Text("These links drive this chapter's own Router (see the sidebar):"),
            indah.Row(
                children=[
                    indah.Link(ctx, "This page", to="/links"),
                    indah.Link(ctx, "Prefix match", to="/links", match="prefix"),
                    indah.Link(ctx, "Overview", to="/"),
                ]
            ),
            indah.Text(
                "The active link carries `aria-current=page`. `match='prefix'` also lights up for "
                "pages below the target, which matters for `/projects/{name}` style trees.",
                markdown=True,
            ),
        ]
    )

This example needs a server: it assumes the Studio's own URL paths (c/<chapter>/<page>), which a docs page does not have. Run make demo to try it. Open in the Studio (make demo, then c/routing/links)

NavItem with a count - A Link for a rail: an icon, and a live count that hides at zero.
def navitem(ctx: indah.Context) -> indah.Component:
    pending = indah.Signal(2)
    return indah.Column(
        children=[
            indah.Column(
                children=[
                    indah.NavItem(ctx, "Overview", to="/navitem", icon="\u2302"),
                    indah.NavItem(ctx, "Pending", to="/links", badge=pending, icon="\u2691"),
                    indah.NavItem(ctx, "Review", to="/navigate", badge=lambda: 0, match="prefix"),
                ]
            ),
            indah.Row(
                children=[
                    indah.Button("Add one", lambda: pending.set((pending.value or 0) + 1)),
                    indah.Button("Clear", lambda: pending.set(0), variant="tonal"),
                ]
            ),
            indah.Text(
                "The badge follows a signal and disappears at zero or empty. The active item "
                "carries `aria-current=page`, like a `Link`.",
                markdown=True,
            ),
        ]
    )

This example needs a server: it assumes the Studio's own URL paths (c/<chapter>/<page>), which a docs page does not have. Run make demo to try it. Open in the Studio (make demo, then c/routing/navitem)

ctx.navigate and not_found - Server code can move the tab. A path with no route shows the router's not_found page.
def navigate(ctx: indah.Context) -> indah.Component:
    return indah.Column(
        children=[
            indah.Text(lambda: f"ctx.path is {ctx.path.value!r}"),
            indah.Row(
                children=[
                    indah.Button("Go to Links", lambda: ctx.navigate("/links")),
                    indah.Button(
                        "Go somewhere unknown",
                        lambda: ctx.navigate("/no-such-page"),
                        variant="tonal",
                    ),
                ]
            ),
            indah.Text(
                "`ctx.navigate(path)` moves the tab from server code and adds a history entry.",
                markdown=True,
            ),
        ]
    )

This example needs a server: it assumes the Studio's own URL paths (c/<chapter>/<page>), which a docs page does not have. Run make demo to try it. Open in the Studio (make demo, then c/routing/navigate)

Split panes and master-detail

indah.SplitPane(left, right, direction="horizontal", initial=0.4, height="30rem")
indah.MasterDetail(table, detail, open=drawer_open)  # a drawer on a narrow screen

Try it live. Nothing downloads until you press Run it.

SplitPane - A draggable divider (mouse or arrow keys); the ratio is remembered per key.
def split(ctx: indah.Context) -> indah.Component:
    return indah.SplitPane(
        indah.Card(
            title="Left", children=[indah.Text("Drag the divider, or focus it and use the arrows.")]
        ),
        indah.Card(title="Right", children=[indah.Text("The ratio is remembered under its key.")]),
        key="demo-split",
        initial=0.4,
        height="12rem",
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/layout/split)

MasterDetail - Wide: list and detail side by side. Narrow (resize the window): the detail opens as a drawer, and the open signal closes it.
def master_detail(ctx: indah.Context) -> indah.Component:
    chosen = indah.Signal("")
    is_open = indah.Signal(False)

    def pick(name: str):
        def go() -> None:
            chosen.set(name)
            is_open.set(True)

        return go

    master = indah.Column(children=[indah.Button(n, pick(n), variant="ghost") for n in _ROWS])
    detail = indah.Column(
        children=[
            indah.Text(lambda: f"### {chosen.value or 'Detail'}", markdown=True),
            indah.Text(lambda: _ROWS.get(chosen.value, "Pick a person on the left.")),
        ]
    )
    return indah.MasterDetail(master, detail, open=is_open, title="Person", key="people")

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/layout/master-detail)

Viewers: JsonTree and Diff

indah.JsonTree(lambda: entry.value, expanded=2)  # search, collapse all, copy path
indah.Diff(
    old_text,
    new_text,
    mode="split",  # or "unified"; "auto" is unified on a phone
    labels=("cached", "incoming"),
)

Diff is computed in Python over pretty-printed, key-sorted JSON (text that is not JSON is compared as it is), so the browser only draws rows. A very large input is truncated and marked as such.

Try it live. Nothing downloads until you press Run it.

JSON tree - A collapsible viewer with search and copy-path. Search opens the way to a match.
def json_tree(ctx: indah.Context) -> indah.Component:
    return indah.JsonTree(ENTRY, expanded=1, label="A cache entry")

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/json-tree)

Diff - Two documents side by side; key order and formatting never show as changes.
def diff(ctx: indah.Context) -> indah.Component:
    incoming = indah.Signal(json.dumps(INCOMING))
    return indah.Column(
        children=[
            indah.TextArea(incoming, label="Incoming (edit me)", rows=3),
            indah.Diff(CACHED, lambda: incoming.value, labels=("cached", "incoming")),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/diff)

Forms that edit data

TextArea(signal, label=, rows=) is a multi-line input. Like every input, the browser owns the text while the viewer is typing in it, so a late echo from the server never overwrites it.

Try it live. Nothing downloads until you press Run it.

Keyed, editable lists - List(key=, on_item=): rows keep their place and the cursor while you type, add or remove. Each row is a small render spec.
def keyed_list(ctx: indah.Context) -> indah.Component:
    tasks = indah.Signal(
        [
            {"id": "t1", "title": "Write docs"},
            {"id": "t2", "title": "Ship it"},
        ]
    )
    nxt = {"n": 2}

    def on_item(key, event, value) -> None:  # sync or async; `key` is the row's id
        if event == "remove":
            tasks.set([t for t in tasks.value if t["id"] != key])
        elif event == "title":
            tasks.set([{**t, "title": value} if t["id"] == key else t for t in tasks.value])

    def add() -> None:
        nxt["n"] += 1
        tasks.set(
            [
                *tasks.value,
                {"id": f"t{nxt['n']}", "title": f"Task {nxt['n']}"},
            ]
        )

    return indah.Column(
        children=[
            indah.List(tasks, key="id", item=TASK_SPEC, on_item=on_item, empty="Nothing to do"),
            indah.Button("Add task", add, variant="tonal"),
            indah.Text(lambda: " | ".join(t["title"] for t in tasks.value) or "(empty)"),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/data/list)

CodeEditor for JSON and YAML

body = indah.Signal('{"model": "gpt-4o"}')

indah.CodeEditor(
    body,
    language="json",  # "json" (default), "yaml" or "text"
    label="Request",
    height="24rem",
    format_button=True,  # JSON only: re-indent, keeping key order
    on_save=save,  # Ctrl/Cmd-S, called with the signal already up to date
)
indah.CodeEditor(old_revision, read_only=True)  # a history snapshot

It highlights, indents, closes brackets and quotes, folds, searches, and for JSON marks a parse error with its position. It is loaded the first time an editor appears, so apps without one never download it (about 180 KB compressed). A very large body is limited by create_app(max_event_bytes=), 1 MiB by default. Tab indents; press Ctrl/Cmd-M to switch that off so the keyboard can leave the editor. {{name}} placeholders (a template slot such as {{now}}) are highlighted in every language, as a visual cue only: names are not completed or checked. If the editor cannot load, a plain text area with the same binding is shown.

For a variable number of editable rows, use a keyed List:

rows = indah.Signal([{"id": "m1", "role": "user", "content": "hi"}])


def on_item(key, event, value):  # sync or async
    if event == "remove":
        rows.set([r for r in rows.value if r["id"] != key])
    elif event == "content":
        rows.set([{**r, "content": value} if r["id"] == key else r for r in rows.value])


indah.List(rows, key="id", item=ROW_SPEC, on_item=on_item)

Every item is a dict with a unique id. Adding, removing or reordering keeps the other rows, and the cursor in a row being typed in. ROW_SPEC is a render spec (see Custom components); each on={...} event reaches on_item with the row's key. A keyed list takes a signal or a callable, not a Stream.

In a row spec, "text": "title" shows the item's title field. For fixed text, such as a button label, use "literal": {"tag": "button", "literal": "Remove", "on": {"click": {"event": "remove"}}} needs no field on the items.

Try it live. Nothing downloads until you press Run it.

CodeEditor - JSON and YAML editing with linting, a server-side Format button and a read-only mode.
def code_editor(ctx: indah.Context) -> indah.Component:
    doc = indah.Signal('{"name":"indah","tags":["ui","python"]}')
    notes = indah.Signal("# YAML works too\nname: indah\nkeys: [a, b]\n")
    fixed = indah.Signal('{"read_only": true}')
    parsed = indah.computed(lambda: _describe(doc.value))
    return indah.Column(
        children=[
            indah.CodeEditor(doc, language="json", format_button=True, height="8rem", label="JSON"),
            indah.Text(lambda: parsed.value),
            indah.CodeEditor(notes, language="yaml", height="6rem", label="YAML"),
            indah.CodeEditor(
                fixed, language="json", read_only=True, height="4rem", label="Read only"
            ),
        ]
    )

Loads about 9 MB, then runs in your browser. Open in the Studio (make demo, then c/overlays/code-editor)

Theme and density

indah.Theme(light={...}, dark={...}, radius=, font=, font_display=, font_body=, font_mono=, fonts=, css=) overrides the design tokens, and create_app(density="compact") tightens tables. See Design system for the token names and what each is for.

Hosted use

indah keeps one session per open tab, in memory, on the server. To put a dashboard in front of real users (login, per-user sessions, roles, limits, a CSP), read Host an app for real users. The ADRs under docs/adr/ (0025 to 0038) describe the decisions behind each feature above.