pysxLearn by building

Build and operate · Lesson 27 of 28

Build the capstone workspace

Combine the course's state, keyed forms, components, routes and themes in one useful workflow.

Now bring the pieces together in a project workspace. Individual demonstrations teach one boundary at a time; a coherent application reveals where those boundaries interact. A record edit changes derived filters, but must not move its private draft to a different row.

The capstone uses the tutorial's own shared controls and theme tokens. A new task receives a stable identifier. Editing replaces the matching record while reordering changes only order. Routes and application-level state have deliberate owners.

Understand the moving parts

Create a task, edit its note, mark it complete and filter the list. Reverse the rows while a draft has focus. These are ordinary user actions, not isolated API calls; the app should keep the full story consistent.

Use Reset workspace to return to the starting dataset. A page refresh is a different operation with session semantics; do not use it as a hidden substitute for a broken reset. The next lesson extends this same application with failure and recovery rather than replacing it with a different showcase.

Walk through the code

from dataclasses import dataclass, replace
from pysx import Fragment, Signal, derived, each, project, pysx, signal


@dataclass(frozen=True)
class Task:
    id: int
    title: str
    done: bool = False
    note: str = ""


@dataclass(frozen=True)
class LabState:
    draft: str = ""
    count: int = 0
    tasks: tuple[Task, ...] = (
        Task(1, "Read the lesson"),
        Task(2, "Build the interface"),
    )


def app(state: Signal[LabState] | None = None) -> Fragment:
    root = signal(LabState()) if state is None else state
    tasks = project(
        root,
        lambda value: list(value.tasks),
        lambda value, rows: replace(value, tasks=tuple(rows)),
    )
    draft = signal("")
    only_active = signal(False)
    next_id = max((task.id for task in tasks()), default=0) + 1
    visible = derived(
        lambda: [row for row in tasks() if not only_active() or not row.done],
    )

    def add(_: object) -> None:
        nonlocal next_id
        text = draft().strip()[:120]

        if text and len(tasks()) < 20:
            tasks.update(lambda rows: [*rows, Task(next_id, text)])
            next_id += 1
            draft.set("")

    def reverse(_: object) -> None:
        tasks.update(lambda rows: list(reversed(rows)))

    def reset(_: object) -> None:
        nonlocal next_id
        root.set(LabState())
        draft.set("")
        only_active.set(False)
        next_id = 3

    def row(item: Task) -> Fragment:
        note = project(
            root,
            lambda value: next((task.note for task in value.tasks if task.id == item.id), ""),
            lambda value, text: replace(
                value,
                tasks=tuple(
                    replace(task, note=text[:512]) if task.id == item.id else task
                    for task in value.tasks
                ),
            ),
        )

        def toggle(_: object) -> None:
            tasks.update(
                lambda values: [
                    replace(task, done=not task.done) if task.id == item.id else task
                    for task in values
                ]
            )

        def remove(_: object) -> None:
            tasks.update(lambda values: [task for task in values if task.id != item.id])

        return pysx(t"""
            li(data-task={item.id} data-complete={str(item.done).lower()})
                h3: {item.title}
                label(for={f"task-note-{item.id}"}): "Private row note"
                input(id={f"task-note-{item.id}"} bindValue={note})
                div:
                    button(data-task-toggle={item.id} onClick={toggle}):
                        "Toggle complete"
                    button(data-task-remove={item.id} onClick={remove}): "Remove task"
        """)

    return pysx(t"""
        section:
            form(id="task-form" onSubmit={add})
                label(for="new-task"): "New task"
                input(id="new-task" bindValue={draft} required={True} maxLength={120})
                button(id="task-add" type="submit"): "Add task"
            div:
                button(id="task-reverse" onClick={reverse}): "Reverse tasks"
                button(id="task-reset" onClick={reset}): "Reset workspace"
                label(for="task-active" class="check-field")
                    input(id="task-active" type="checkbox" bindChecked={only_active})
                    "Show active tasks only"
            ul(id="tasks"): {each(visible, row, key=lambda item: item.id)}
            p: "Task count: " {derived(lambda: len(tasks()))}
    """)

The initial records are Read the lesson and Build the interface. Add allocates a stable id; each row projects its note into the same root. Reverse preserves the record identity and note, Toggle complete updates the record, and the active filter derives the visible list. Reset workspace restores the initial dataset.

Try it live

Add a task, edit a row note, reverse, toggle completion and test the active filter. Reset and repeat.

What to observe

The same row retains its note across movement, filters show the correct records and reset restores the dataset.

  • Read the lesson

  • Build the interface

Task count: 2

Take this with you

A good capstone verifies a complete user journey across several ownership boundaries.