Skip to content

Authoring patterns example

A single page that exercises the idioms from the Authoring patterns guide:

  • Markup written as html templates, with components used as tags.
  • Composition through children (a Card component with a children parameter that forwards an id through **attrs).
  • State with create_signal and derived values with create_memo.
  • Reactive list rendering with For over a draft-first store.
  • A mutation wrapped in action with a pending indicator.
  • Cleanup with on_settled and on_cleanup (a ticking Timer).

Full listing

import asyncio
from typing import Any

from wybthon import (
    Children,
    For,
    Show,
    action,
    component,
    create_memo,
    create_signal,
    create_store,
    html,
    on_cleanup,
    on_settled,
    render,
)


@component
def Card(title: str = "", children: Children = None, **attrs: Any):
    return html(t"""
      <section class="card" {attrs}>
        <h3>{title}</h3>
        {children}
      </section>
    """)


@component
def NamesList():
    store, set_store = create_store({"names": []})
    draft, set_draft = create_signal("")

    total = create_memo(lambda: len(store["names"]))
    starts_with_a = create_memo(lambda: sum(1 for n in store["names"] if n["text"].lower().startswith("a")))

    @action
    async def add(text: str):
        # Simulate a slow save; the button is disabled while ``add.pending()``.
        await asyncio.sleep(0.3)
        set_store(lambda s: s["names"].append({"id": len(s["names"]) + 1, "text": text}))
        set_draft("")

    def save():
        add(draft())

    def clear():
        set_store(lambda s: s["names"].clear())

    def edit(e):
        set_draft(e.target.value)

    def row(item, index):
        return html(t"<li>{index() + 1}. {item()['text']}</li>")

    return html(t"""
      <div>
        <p>Total: {total()} | Starts with A: {starts_with_a()}</p>
        <div>
          <input value={draft()} oninput={edit} placeholder="Name">
          <button onclick={save} disabled={add.pending()}>Add</button>
          <button onclick={clear}>Clear</button>
        </div>
        {Show(add.pending(), html(t"<p>Saving...</p>"))}
        <ul>
          {For(store["names"], row, fallback=html(t"<li>No names yet.</li>"), keyed=lambda n: n["id"])}
        </ul>
      </div>
    """)


@component
def Timer():
    seconds, set_seconds = create_signal(0)

    def start():
        from js import clearInterval, setInterval
        from pyodide.ffi import create_proxy

        proxy = create_proxy(lambda: set_seconds(lambda s: s + 1))
        handle = setInterval(proxy, 1000)

        def stop():
            clearInterval(handle)
            proxy.destroy()

        return stop  # cleanup runs on unmount

    on_settled(start)
    on_cleanup(lambda: print("Timer unmounted"))

    return html(t'<div class="timer"><span>Seconds: {seconds()}</span></div>')


@component
def Page():
    show_timer, set_show_timer = create_signal(True)

    def toggle_timer():
        set_show_timer(lambda v: not v)

    return html(t"""
      <div>
        <{Card} title="State and derived values" id="names">
          <{NamesList} />
        </{Card}>
        <{Card} title="Cleanup">
          <button onclick={toggle_timer}>Toggle timer</button>
          {Show(show_timer(), Timer())}
        </{Card}>
      </div>
    """)


render(Page(), "#app")

What to notice

  • Card declares its props as parameters with defaults, and its children parameter accepts the nested markup. {title} is a parameter, so it's a tracked read the compiler turns into a getter. **attrs collects every prop Card doesn't declare, and spreading it onto the <section> (<section {attrs}> is a spread) puts the parent's id="names" there; each forwarded key stays reactive. A None value removes the attribute.
  • Page uses the component tag form: <{Card} title="...">...</{Card}> passes the attributes as props and the nested markup as children, and <{NamesList} /> takes none. The call form, {Card(title="Cleanup", children=[...])} or Card(title=...)[...], does the same and is fully type-checked; wyb check checks the tag form's props, and dev mode checks them at run time.
  • NamesList keeps its list in a store. set_store(lambda s: s["names"].append(...)) mutates a draft; only the fields that changed notify, and For matches rows by id so existing <li> elements are kept.
  • The store list goes to For as is: For(store["names"], ...) tracks it without a wrapping lambda. A dict store is read with subscripts; use a dataclass when you'd rather write store.names.
  • With a key function, For hands the row callback accessors for both the item and the index, so row reads item() and index() right in its template; the expression is one hole.
  • The summary line reads two memos, total() and starts_with_a(); each is its own text binding.
  • add is an action. While it's in flight, add.pending() is True, which disables the button (disabled={add.pending()}) and shows the "Saving..." line.
  • save reads draft() in an event handler, which isn't a tracking scope, so the read doesn't subscribe anything.
  • Handlers that don't need the event take no arguments (onclick={clear}); edit takes the event to read e.target.value. The compiler never wraps a handler. Every handler is a named function, since Python doesn't allow a bare lambda inside a t-string interpolation (an inline one needs parentheses: onclick={(lambda: set_draft(""))}).
  • Show and For mount as native regions, not wrapper components: each is one computation that selects what to render, with no component scope or props of its own. A Show branch written as markup or a component call, such as Timer(), is lazy: the compiler wraps it in a function, so it's built only when the branch shows.
  • Timer starts its interval in on_settled and returns a cleanup from it, so the interval stops when Show unmounts the timer. on_cleanup in the body runs at the same time. Showing it again calls the lazy branch again, which mounts a fresh Timer with its own state.

Next steps