Example: Todos
Components, list mutation, filters and keyed lists, with rows that animate in and out.
- 84 lines of Python
- 1 page
- 0 server functions
- 2400 B page JS (gzip)
#Source
examples/todo/app.pyweb
"""Todo list: client-side state, a component, computed values, filters, the UI kit and motion."""
from pyweb import App, component
from pyweb.ui import Button, Card, CardContent, CardDescription, CardHeader, Checkbox, ToggleGroup, ToggleGroupItem
app = App(title="Todos", stylesheets=["/static/app.css"])
FILTERS = ["all", "active", "done"]
@component
def TodoItem(todo, on_toggle, on_remove):
<li class={{"done": todo["done"]}} initial={{"opacity": 0, "y": -8}} animate={{"opacity": 1, "y": 0}}
exit={{"opacity": 0, "x": 24}} layout>
<Checkbox checked={todo["done"]} onchange={on_toggle} aria-label={"Done: " + todo["title"]} />
<span>{todo["title"]}</span>
<Button variant="ghost" size="icon" class_="remove" onclick={on_remove} aria-label="Remove">×</Button>
</li>
@app.page("/")
def Home():
todos = []
draft = ""
show = "all"
next_id = 1
visible = [t for t in todos if show == "all" or (show == "done") == t["done"]]
remaining = len([t for t in todos if not t["done"]])
def add():
title = draft.strip()
if not title:
return
todos.append({"id": next_id, "title": title, "done": False})
next_id += 1
draft = ""
def toggle(todo_id):
for i, t in enumerate(todos):
if t["id"] == todo_id:
todos[i]["done"] = not t["done"]
def remove(todo_id):
todos = [t for t in todos if t["id"] != todo_id]
def set_filter(e):
show = e.detail["value"] or show
def clear_done():
todos = [t for t in todos if not t["done"]]
<main>
<Card>
<CardHeader>
<h1 data-part="title">Todos</h1>
<CardDescription>Everything here runs in your browser.</CardDescription>
</CardHeader>
<CardContent>
<form class="add" onsubmit={add}>
<input id="new" class="pw-control" bind={draft} placeholder="What needs doing?"
aria-label="New todo" autofocus />
<Button id="add" type="submit" disabled={not draft.strip()}>Add</Button>
</form>
<ul id="list">
for todo in visible:
<TodoItem
todo={todo}
on_toggle={lambda: toggle(todo["id"])}
on_remove={lambda: remove(todo["id"])} />
</ul>
if todos:
<footer>
<span id="left">{remaining} {"item" if remaining == 1 else "items"} left</span>
<ToggleGroup value={show} onvaluechange={set_filter} size="sm" label="Show">
for name in FILTERS:
<ToggleGroupItem value={name}>{name}</ToggleGroupItem>
</ToggleGroup>
<Button id="clear" variant="ghost" size="sm" onclick={clear_done}>Clear done</Button>
</footer>
else:
<p class="empty" animate="fade">Nothing to do yet. Add something above.</p>
</CardContent>
</Card>
</main>
#What runs where
Output of pyweb inspect: every page variable, handler and server function, where it runs and why.
Output
page Home route=/
browser todos reactive state: .append() in add(); literal initial value
browser draft reactive state: bound to an input (line 60); literal initial value
browser show reactive state: assigned in set_filter(); literal initial value
browser next_id reactive state: assigned in add(); literal initial value
browser visible derived from show, todos; recomputed when they change
browser remaining derived from todos; recomputed when they change
browser add event handler (compiled to JavaScript)
browser toggle event handler (compiled to JavaScript)
browser remove event handler (compiled to JavaScript)
browser set_filter event handler (compiled to JavaScript)
browser clear_done event handler (compiled to JavaScript)#Generated JavaScript
The browser modules the compiler wrote (before minification). They import the shared runtime.
JavaScript
// Home.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// card.pyweb
const { Card, CardHeader, CardDescription, CardContent } = (() => {
function Card($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("div", {"class": "pw-card", "data-pw-ui": "card", "data-part": "card", "$spread3": () => attrs()}, () => [$dyn(() => children())])];
}
function CardHeader($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("div", {"data-part": "header", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
}
function CardDescription($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("p", {"data-part": "description", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
}
function CardContent($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("div", {"data-part": "content", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
}
return { Card, CardHeader, CardDescription, CardContent };
})();
// button.pyweb
const { Button } = (() => {
function Button($p) {
const variant = $p["variant"] || (() => "default");
const size = $p["size"] || (() => "md");
const type = $p["type"] || (() => "button");
const href = $p["href"] || (() => null);
const loading = $p["loading"] || (() => false);
const disabled = $p["disabled"] || (() => false);
const onclick = $p["onclick"] || (() => null);
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
$when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
$dyn(() => children())
])])];
}
return { Button };
})();
// controls.pyweb
const { Checkbox, ToggleGroup, ToggleGroupItem } = (() => {
function _csv(value) {
if ((value == null)) {
return null;
}
if ($py.isinstance(value, ["list", "tuple"])) {
return $py.m(",", "join", $py.iter(value).map((v) => ($py.str(v))));
}
return $py.str(value);
}
function Checkbox($p) {
const label = $p["label"] || (() => null);
const checked = $p["checked"] || (() => false);
const indeterminate = $p["indeterminate"] || (() => false);
const name = $p["name"] || (() => null);
const value = $p["value"] || (() => null);
const disabled = $p["disabled"] || (() => false);
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("label", {"class": "pw-check", "data-part": "root", "data-disabled": () => ($py.truth(disabled()) ? "" : null)}, () => [
$h("input", {"type": "checkbox", "class": "pw-checkbox", "data-pw-ui": "checkbox", "data-part": "checkbox", "name": () => name(), "value": () => value(), "checked": () => checked(), "disabled": () => disabled(), "data-indeterminate": () => ($py.truth(indeterminate()) ? "true" : null), "$spread9": () => attrs()}),
$when(() => $py.truth(label()), () => [$h("span", {"data-part": "label"}, () => [$dyn(() => label())])]),
$dyn(() => children())
])];
}
function ToggleGroup($p) {
const type = $p["type"] || (() => "single");
const value = $p["value"] || (() => null);
const default_ = $p["default"] || (() => null);
const name = $p["name"] || (() => null);
const variant = $p["variant"] || (() => "default");
const size = $p["size"] || (() => "md");
const orientation = $p["orientation"] || (() => "horizontal");
const label = $p["label"] || (() => null);
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("div", {"class": "pw-toggle-group", "data-pw-ui": "toggle-group", "data-part": "root", "data-type": () => type(), "data-value": () => _csv(((value() == null) ? default_() : value())), "data-controlled": () => ((value() == null) ? null : ""), "data-variant": () => variant(), "data-size": () => size(), "data-orientation": () => orientation(), "aria-label": () => label(), "$spread10": () => attrs()}, () => [
$when(() => $py.truth(name()), () => [$h("input", {"type": "hidden", "name": () => name(), "value": () => $py.or(_csv(((value() == null) ? default_() : value())), () => "")})]),
$dyn(() => children())
])];
}
function ToggleGroupItem($p) {
const value = $p["value"] || (() => null);
const label = $p["label"] || (() => null);
const disabled = $p["disabled"] || (() => false);
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("button", {"type": "button", "class": "pw-toggle", "data-part": "item", "data-value": () => value(), "aria-label": () => label(), "disabled": () => disabled(), "$spread6": () => attrs()}, () => [$dyn(() => children())])];
}
return { Checkbox, ToggleGroup, ToggleGroupItem };
})();
const FILTERS = ["all", "active", "done"];
function TodoItem($p) {
const todo = $p["todo"] || (() => null);
const on_toggle = $p["on_toggle"] || (() => null);
const on_remove = $p["on_remove"] || (() => null);
return [$h("li", {"class": () => ({"done": $py.at(todo(), "done")}), "data-pw-motion": JSON.stringify({"initial": {"opacity": 0, "y": (-8)}, "animate": {"opacity": 1, "y": 0}, "exit": {"opacity": 0, "x": 24}, "layout": true}), "style": ((i, s) => s)({"opacity": 0, "y": (-8)}, null, null, {"opacity": 1, "y": 0})}, () => [
Checkbox({"checked": () => $py.at(todo(), "done"), "$rest": () => ({"onchange": (e) => { const f = on_toggle(); return f ? f(e) : undefined; }, "aria-label": $py.add("Done: ", $py.at(todo(), "title"))})}),
$h("span", null, () => [$dyn(() => $py.at(todo(), "title"))]),
Button({"variant": () => "ghost", "size": () => "icon", "onclick": () => (e) => { const f = on_remove(); return f ? f(e) : undefined; }, "children": () => [$t("\u00d7")], "$rest": () => ({"class_": "remove", "aria-label": "Remove"})})
])];
}
function Home($s) {
const todos = $signal("todos" in $s ? $s["todos"] : [{"id": 1, "title": "Write one Python file", "done": true}, {"id": 2, "title": "Run pyweb dev", "done": false}, {"id": 3, "title": "Ship it", "done": false}], "todos");
const draft = $signal("draft" in $s ? $s["draft"] : "", "draft");
const show = $signal("show" in $s ? $s["show"] : "all", "show");
const next_id = $signal("next_id" in $s ? $s["next_id"] : 4, "next_id");
const visible = $computed(() => $py.iter(todos()).filter((t) => ((show() === "all") || $py.eq((show() === "done"), $py.at(t, "done")))));
const remaining = $computed(() => $py.len($py.iter(todos()).filter((t) => !$py.truth($py.at(t, "done")))));
function add() {
let title;
title = $py.m(draft(), "strip");
if (!$py.truth(title)) {
return;
}
$py.mut(todos, [], ($v) => $py.m($v, "append", {"id": next_id(), "title": title, "done": false}));
next_id($py.add(next_id(), 1));
draft("");
}
function toggle(todo_id) {
let i, t;
for ([i, t] of $py.iter($py.enumerate(todos()))) {
if ($py.eq($py.at(t, "id"), todo_id)) {
$py.setp(todos, [i, "done"], !$py.truth($py.at(t, "done")));
}
}
}
function remove(todo_id) {
todos($py.iter(todos()).filter((t) => !$py.eq($py.at(t, "id"), todo_id)));
}
function set_filter(e) {
show($py.or($py.at(e.detail, "value"), () => show()));
}
function clear_done() {
todos($py.iter(todos()).filter((t) => !$py.truth($py.at(t, "done"))));
}
return [$h("main", null, () => [Card({"children": () => [
CardHeader({"children": () => [
$h("h1", {"data-part": "title"}, () => [$t("Todos")]),
CardDescription({"children": () => [$t("Everything here runs in your browser.")]})
]}),
CardContent({"children": () => [
$h("form", {"class": "add", "onsubmit": add}, () => [
$h("input", {"id": "new", "class": "pw-control", "$bind": draft, "placeholder": "What needs doing?", "aria-label": "New todo"}),
Button({"type": () => "submit", "disabled": () => !$py.truth($py.m(draft(), "strip")), "children": () => [$t("Add")], "$rest": () => ({"id": "add"})})
]),
$h("ul", {"id": "list"}, () => [$list(() => visible(), (todo) => [TodoItem({"todo": () => todo, "on_toggle": () => (() => (toggle($py.at(todo, "id")))), "on_remove": () => (() => (remove($py.at(todo, "id"))))})])]),
$when(() => $py.truth(todos()), () => [$h("footer", null, () => [
$h("span", {"id": "left"}, () => [
$dyn(() => remaining()),
$t(" "),
$dyn(() => ((remaining() === 1) ? "item" : "items")),
$t(" left")
]),
ToggleGroup({"value": () => show(), "size": () => "sm", "label": () => "Show", "children": () => [$list(() => FILTERS, (name) => [ToggleGroupItem({"value": () => name, "children": () => [$t($py.text(name))]})])], "$rest": () => ({"onvaluechange": set_filter})}),
Button({"variant": () => "ghost", "size": () => "sm", "onclick": () => clear_done, "children": () => [$t("Clear done")], "$rest": () => ({"id": "clear"})})
])], () => [$h("p", {"class": "empty", "data-pw-motion": JSON.stringify({"animate": "fade"}), "style": ((i, s) => s)(null, null, null, "fade")}, () => [$t("Nothing to do yet. Add something above.")])])
]})
]})])];
}
$mount("Home", Home);