Authoring patterns example¶
A single page that exercises the idioms from the Authoring patterns guide:
- Markup written as
htmltemplates, with components used as tags. - Composition through
children(aCardcomponent with achildrenparameter that forwards anidthrough**attrs). - State with
create_signaland derived values withcreate_memo. - Reactive list rendering with
Forover a draft-first store. - A mutation wrapped in
actionwith a pending indicator. - Cleanup with
on_settledandon_cleanup(a tickingTimer).
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¶
Carddeclares its props as parameters with defaults, and itschildrenparameter accepts the nested markup.{title}is a parameter, so it's a tracked read the compiler turns into a getter.**attrscollects every propCarddoesn't declare, and spreading it onto the<section>(<section {attrs}>is a spread) puts the parent'sid="names"there; each forwarded key stays reactive. ANonevalue removes the attribute.Pageuses the component tag form:<{Card} title="...">...</{Card}>passes the attributes as props and the nested markup aschildren, and<{NamesList} />takes none. The call form,{Card(title="Cleanup", children=[...])}orCard(title=...)[...], does the same and is fully type-checked;wyb checkchecks the tag form's props, and dev mode checks them at run time.NamesListkeeps its list in a store.set_store(lambda s: s["names"].append(...))mutates a draft; only the fields that changed notify, andFormatches rows byidso existing<li>elements are kept.- The store list goes to
Foras is:For(store["names"], ...)tracks it without a wrapping lambda. A dict store is read with subscripts; use a dataclass when you'd rather writestore.names. - With a key function,
Forhands the row callback accessors for both the item and the index, sorowreadsitem()andindex()right in its template; the expression is one hole. - The summary line reads two memos,
total()andstarts_with_a(); each is its own text binding. addis anaction. While it's in flight,add.pending()isTrue, which disables the button (disabled={add.pending()}) and shows the "Saving..." line.savereadsdraft()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});edittakes the event to reade.target.value. The compiler never wraps a handler. Every handler is a named function, since Python doesn't allow a barelambdainside a t-string interpolation (an inline one needs parentheses:onclick={(lambda: set_draft(""))}). ShowandFormount as native regions, not wrapper components: each is one computation that selects what to render, with no component scope or props of its own. AShowbranch written as markup or a component call, such asTimer(), is lazy: the compiler wraps it in a function, so it's built only when the branch shows.Timerstarts its interval inon_settledand returns a cleanup from it, so the interval stops whenShowunmounts the timer.on_cleanupin the body runs at the same time. Showing it again calls the lazy branch again, which mounts a freshTimerwith its own state.
Next steps¶
- Read Components and Lifecycle and Ownership.
- Browse the Counter example for a smaller starting point.
- See Stores for
reconcile,snapshot, and derived stores.