# WebComPy > WebComPy is a Python frontend framework running entirely in the browser via PyScript/Emscripten with SSR and static site generation (SSG) in standard CPython from a single codebase. **Core concepts** - **Dual-environment execution**: The same Python `webcompy` core code renders live DOM nodes in the browser (PyScript/Pyodide) and HTML strings on the server (CPython or server-side Emscripten/Pyodide ASGI), separating browser PyScript detection (`ENVIRONMENT == "pyscript"`) from Emscripten runtime mechanics (`IS_EMSCRIPTEN`, i.e., `platform.system() == "Emscripten"`) and switching ports via dependency injection (`RenderContext`). - **Reactivity by default**: `Signal`, `Computed`, `ReactiveList`, and `ReactiveDict` track dependencies automatically and update bound DOM text, attributes, lists (`repeat`), and conditional branches (`switch`) without manual DOM orchestration. - **Light DOM custom elements**: Components are Python functions decorated with `@define_component()` returning virtual element trees with props, slots, lifecycle hooks (`on_before_rendering`, `on_mounted`, `on_before_destroy`), and component-scoped CSS. - **SSR hydration transfer**: State created inside component setup with `use_state`, `use_computed`, `use_reactive_list`, `use_reactive_dict`, and `use_async_result` (and `HttpClient` / `load_text` results) transfers cleanly from SSR/SSG HTML into the browser without flash or double-fetching. - **ASGI coexistence**: WebComPy dev/prod servers are standard Starlette ASGI applications that can mount sub-apps (`WebComPyServerConfig.mounts`) or be embedded inside host FastAPI/Starlette applications, alongside typed JSON-RPC (`webcompy.rpc`). - **Current installation note**: Until the latest releases are published on PyPI, `webcompy`, `webcompy-server`, `webcompy-cli`, and `webcompy-testing` are installed via GitHub `#subdirectory=packages/` URLs (see Installation), while PyScript resolves `webcompy` from PyPI/wheels. **Important notes** - Always call `@define_component()` with parentheses; omitting arguments derives the custom-element tag from the function name (`HomePage` -> ``), and passing `"custom-tag"` overrides it explicitly. - Create reactive state via `use_state` / `use_reactive_list` / `use_reactive_dict` inside component setup functions when SSR-to-browser value transfer is needed. - No JavaScript build step or Node.js bundler is required for WebComPy applications. - Keep server/build configuration (`WebComPyBuildConfig`, `WebComPyServerConfig`, `StaticRoute`) in `webcompy_config.py`; keep browser-visible runtime config (`WebComPyAppConfig`) in your app module so server-only code never enters the browser wheel. - Prefer typed RPC contracts (`Procedure`, `StreamingProcedure`, `Subscription`) bound to `app.rpc` (`ProcedureRegistry`) and called via `RpcHttpClient` / `RpcWsClient` over ad-hoc untyped RPC endpoints. **Minimal working example** ```python from webcompy.app import WebComPyApp from webcompy.components import ComponentContext, define_component from webcompy.elements import DOMEvent, html from webcompy.signal import use_computed, use_state @define_component() def CounterApp(context: ComponentContext[None]): count = use_state(lambda: 0) doubled = use_computed(lambda: count.value * 2) def increment(_ev: DOMEvent) -> None: count.value += 1 return html.DIV( {}, html.H1({}, "Counter"), html.P({}, "Count: ", count, " (doubled: ", doubled, ")"), html.BUTTON({"@click": increment}, "+1"), ) app = WebComPyApp(root_component=CounterApp) ``` Serve locally with `uv run python -m webcompy start --dev`, materialize deployable artifacts once with `uv run python -m webcompy prebuild` (and run `start --prebuilt`), or export static HTML/wheels with `uv run python -m webcompy generate` (browser-only standalone usage calls `app.run()`). **Essential API cheat sheet** | Area | Module | Core Public Symbols | Purpose | |---|---|---|---| | App & Components | `webcompy.app`, `webcompy.components` | `WebComPyApp`, `WebComPyAppConfig`, `PluginScript`, `PrePaintStyle`, `pre_paint_vars`, `use_pre_paint_style`, `define_component`, `ComponentContext`, `on_before_rendering`, `on_mounted`, `on_before_destroy` | App bootstrap, config, pre-paint scripts/styles, Light DOM components, lifecycle hooks | | Reactive State | `webcompy.signal` | `Signal`, `Computed`, `ReactiveList`, `ReactiveDict`, `use_state`, `use_computed`, `use_reactive_list`, `use_reactive_dict`, `use_readonly_signal`, `effect` | Reactive state primitives, setup-scoped transfer state, tracked side effects | | Elements & Flow | `webcompy.elements` | `html`, `DOMEvent`, `DomNodeRef`, `repeat`, `switch`, `Suspense`, `ErrorBoundary`, `ClientOnly`, `Teleport`, `Transition` | Typed HTML builders, keyed list reconciliation, async/error/portal/animation boundaries | | Templates & Assets | `webcompy.template`, `webcompy.resources` | `render_template`, `load_markdown_document`, `css_text`, `load_text`, `load_bytes` | HTML template interpolation, Markdown loading, package resource access | | Routing & DI | `webcompy.router`, `webcompy.di` | `Router`, `RouterLink`, `RouterView`, `RouterContext`, `use_router`, `lazy`, `InjectKey`, `provide`, `inject` | History/hash SPA routing, lazy routes, scoped dependency injection | | Async, HTTP & Forms | `webcompy.components`, `webcompy.ajax`, `webcompy.forms` | `use_async_result`, `use_async`, `HttpClient`, `Response`, `from_json`, `Field`, `Form`, `use_field`, `use_form`, `required`, `email` | Async setup data, typed HTTP client, reactive fields and validation | | Realtime & RPC | `webcompy.realtime`, `webcompy.rpc` | `use_event_source`, `use_websocket`, `Procedure`, `StreamingProcedure`, `Subscription`, `RpcHttpClient`, `RpcWsClient`, `ProcedureRegistry`, `batch`, `notify` | Shared SSE/WebSocket composables and contract-first typed JSON-RPC | | UI & i18n | `webcompy.ui`, `webcompy.ui.code_block`, `webcompy.i18n` | `CodeBlock`, `Input`, `Select`, `Modal`, `Drawer`, `Dropdown`, `Tabs`, `Alert`, `Card`, `Spinner`, `use_i18n`, `I18nManager` | First-party accessible UI primitives and SSR-consistent internationalization | | Server, CLI & Testing | `webcompy_server`, `webcompy_cli`, `webcompy_cli.config`, `webcompy_testing` | `configure_server_context`, `generate_html`, `create_asgi_app`, `create_prebuilt_asgi_app`, `prebuild_app`, `generate_static_site`, `run_server`, `PrebuildManifest`, `WebComPyBuildConfig`, `WebComPyServerConfig`, `StaticRoute`, `PWAConfig`, `TestRenderer`, `create_test_asgi_app`, `render_app_html` | ASGI embedding, dev/prod/prebuilt server, SSG export, headless component & ASGI testing | **Context bundles and Markdown endpoints** - Index only (overview, essential API cheat sheet, and `.md` page links — smallest file, tens of KB): https://webcompy.net/llms.txt - Compact single-file bundle (smaller alternative to `llms-full.txt` with Getting Started, Basic Usage, and Server & Tooling inlined; larger than the index, hundreds of KB): https://webcompy.net/llms-small.txt - Complete single-file bundle (all documentation pages with runnable demo sources inlined; ~1 MB+): https://webcompy.net/llms-full.txt - Per-page raw Markdown: append `.md` to any documentation page URL (for example, https://webcompy.net/documents/basic/components.md). --- Source: https://webcompy.net/documents/getting-started/what-is-webcompy.md (Category: Getting Started) # What is WebComPy WebComPy is a Python frontend framework. You write your UI in Python — components, routing, and state — and the same codebase runs in two places: in the browser via PyScript, and on the server via standard Python for pre-rendering. ## The dual-environment model Every WebComPy app lives in two runtimes: - **Browser (PyScript/Emscripten)**: reactive components render into the DOM, handle events, and update the page. This is where your app is interactive. - **Server (standard Python)**: the same components render to HTML for server-side rendering (SSR) and static site generation (SSG), so first loads are fast and crawlable. ```text Python components |-- browser --> interactive DOM (PyScript) |-- server --> pre-rendered HTML (SSR / SSG) ``` The framework detects the runtime with `platform.system() == "Emscripten"` and wires up the matching port implementations (DOM, fetch, scheduler) through dependency injection. Application code stays the same on both sides. ## Core promises - **Components**: plain functions decorated with `@define_component()` render as Light DOM custom elements. Props, slots, and scoped CSS included. - **Reactivity**: `Signal`, `Computed`, and reactive collections refresh the DOM automatically when state changes. - **Routing**: client-side routing with history and hash modes, path parameters, and navigation hooks. - **CLI and pre-rendering**: scaffold projects, run a dev server with live reload, and ship SSR or fully static output. - **Typed data flow**: schema-driven API clients, JSON-RPC with streaming and WebSocket transports, and server-to-browser hydration transfer. ## Relationship to FastAPI and Starlette WebComPy is not a replacement for your backend framework — it complements it: - The **dev server and SSR endpoints are ASGI apps**. You can embed a WebComPy serving app inside a host ASGI application (for example, next to FastAPI routes) and share the same process. - **Data fetching during SSR** goes through the same ASGI transport, so server-rendered pages can call your own API routes without leaving the process. - For typed client-server communication, WebComPy offers its own **JSON-RPC layer** (HTTP, streaming, and WebSocket), which sits alongside — not instead of — plain REST endpoints you already serve. - Already running a server-rendered Jinja2 + FastAPI app? Follow the step-by-step strangler strategy in [Migrating from Jinja2 + FastAPI](/documents/migration/from-jinja2-fastapi). ## Next steps If WebComPy sounds like a fit, read [Why WebComPy](/documents/getting-started/why-webcompy) for an honest discussion of trade-offs, then follow the [Installation](/documents/getting-started/installation) guide to set up a project. --- Source: https://webcompy.net/documents/getting-started/why-webcompy.md (Category: Getting Started) # Why WebComPy Choosing a framework is a trade-off. This page states both sides plainly so you can decide with open eyes. ## Why WebComPy - **One language for the whole frontend**: components, routing, state, and data fetching are all Python. No context-switching between a Python backend and a JavaScript frontend. - **Reactivity without ceremony**: `Signal` and `Computed` values refresh the DOM automatically. You describe what the UI should show, not how to update it. - **Pre-rendering built in**: server-side rendering and static site generation come from the same component code — fast first loads without a separate pipeline. - **Typed client-server flow**: schema-driven API clients and JSON-RPC (HTTP, streaming, WebSocket) keep the contract between browser and server explicit. - **Familiar ecosystem**: the browser runtime is Python via PyScript, so libraries you already know — including numpy and friends — work where the runtime supports them. ## Why not WebComPy At the time of writing, the following drawbacks are real. Weigh them before committing: - **PyScript payload and cold start**: the browser must load the Python runtime before your app starts. Initial loads are heavier and slower than a hand-tuned JavaScript bundle, especially on slow networks. - **Young ecosystem**: fewer third-party components, integrations, and answered questions than mainstream JavaScript frameworks. You will occasionally build what elsewhere you would install. - **Performance ceiling**: Python in the browser cannot match compiled JavaScript for hot loops and large-scale DOM churn. Apps with heavy per-frame computation may need to push work to the server or to JavaScript. - **Browser-API coverage gaps**: newer or niche web APIs may not yet have a framework wrapper, leaving you to write interop code yourself. - **Smaller hiring and community pool**: finding developers and reviewers with WebComPy experience is harder than with established frameworks. None of these are permanent — runtime size, coverage, and community all move over time — but they describe the framework as it exists today. ## The short version Choose WebComPy when a Python-only stack, declarative reactivity, and built-in pre-rendering outweigh raw bundle size and ecosystem maturity for your project. If minimal cold-start latency or a vast plugin ecosystem is the top priority, a mainstream JavaScript framework is currently the safer pick. ## Next steps Continue to the [Installation](/documents/getting-started/installation) guide to set up a project, or skim [What is WebComPy](/documents/getting-started/what-is-webcompy) for the architectural picture. --- Source: https://webcompy.net/documents/getting-started/installation.md (Category: Getting Started) # Installation > **Note**: Until the latest release is published to PyPI, the packages are resolved from the GitHub repository via the `git+` URLs below. Once the packages are on PyPI, the install commands can be simplified (e.g. `uv add webcompy-cli` / `poetry add webcompy-cli` / `pip install webcompy[cli]`). PyScript loads `webcompy` from PyPI and does not yet support installing from a GitHub repository, so the version loaded in PyScript is the last published one. ## Prerequisites - Python 3.12 or later. - `uv` (recommended) or `Poetry` as the project package manager. ## Install with uv (Recommended) Create a new project and set up dependencies using `uv`. ```bash mkdir webcompy-project && cd webcompy-project uv init uv add "webcompy @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy" uv add "webcompy-server @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-server" uv add "webcompy-cli @ git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-cli" uv run python -m webcompy init ``` ## Browser dependencies Browser dependencies are third-party packages loaded by PyScript in the browser (for example `numpy` or `matplotlib` for demos). Declare them as an optional dependency group named `browser` in `pyproject.toml` so the CLI can resolve and lock them for the PyScript runtime: ```toml [project.optional-dependencies] browser = ["numpy", "matplotlib"] ``` This step is optional — skip it if your app needs no third-party packages in the browser. ## Project configuration `webcompy init` generates `webcompy_config.py`. The base shape mirrors the scaffold template: ```python # webcompy_config.py import app.app as app_module from webcompy_cli.config import WebComPyBuildConfig, WebComPyServerConfig config = WebComPyBuildConfig( app_module, dependencies=None, # explicit browser package list (None = resolve from pyproject) dependencies_from=None, # pyproject group to read browser deps from (e.g. "browser") server=WebComPyServerConfig(port=8080), # dev server and SSR serving options ) ``` - `app_module`: your application package — the `WebComPyApp` instance the CLI builds and serves. - `dependencies`: an explicit list of browser packages. Leave `None` to resolve from `pyproject.toml` instead. - `dependencies_from`: the `pyproject.toml` group those packages are read from. Set `"browser"` to use the `[project.optional-dependencies] browser` group above. - `server`: serving-only options such as the dev server port. It never affects the browser bundle. When you use the `browser` group, pair it with lockfile sync so `webcompy-lock.json` tracks that group: ```python from webcompy_cli.config import LockfileSyncConfig config = WebComPyBuildConfig( app_module, dependencies=None, dependencies_from="browser", lockfile_sync_config=LockfileSyncConfig(sync_group="browser"), server=WebComPyServerConfig(port=8080), ) ``` ## Lock file & dev server Generate the lock file and start the dev server: ```bash uv run python -m webcompy lock uv run python -m webcompy start --dev ``` Note: `webcompy lock --install` uses `uv pip` or `pip`, not `poetry install`. Use `webcompy lock --sync` to compare versions with `pyproject.toml`. ## Install with Poetry If you prefer Poetry, use the following setup: ```bash poetry new webcompy-project && cd webcompy-project poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy" poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-server" poetry add "git+https://github.com/kniwase/WebComPy.git#subdirectory=packages/webcompy-cli" poetry run python -m webcompy init ``` Add browser dependencies to `[project.optional-dependencies]` in `pyproject.toml` (same as the uv setup above), then configure `webcompy_config.py` as shown above, and run: ```bash poetry run python -m webcompy lock poetry run python -m webcompy start --dev ``` Note: `webcompy lock --install` uses `uv pip` or `pip`, not `poetry install`. Use `webcompy lock --sync` to compare versions with `pyproject.toml`. --- Source: https://webcompy.net/documents/getting-started/quickstart.md (Category: Getting Started) # Quickstart ## Create a project After installing WebComPy, scaffold a new project inside an existing Python project: ```bash uv run python -m webcompy init ``` The command generates the application entry point, a router, and a set of example components under your project. It also creates `webcompy_config.py` so the CLI knows how to build and serve your app. ## Start the dev server Start the development server with live reload: ```bash uv run python -m webcompy start --dev ``` The server prints the URL of your app (default: `http://localhost:8080`). Open it in a browser to see the template page running in PyScript. ## Your first component Components are plain functions decorated with the `@define_component()` factory. Open `app/components/home.py` and replace its body with your own view: ```python from webcompy.components import ComponentContext, define_component from webcompy.elements import html from webcompy.router import RouterContext @define_component() def HomePage(context: ComponentContext[RouterContext]): context.set_title("My First App") return html.H1( {}, "Hello WebComPy!", ) ``` The custom element name is derived from the function name (`HomePage` → ``); pass it explicitly with `@define_component(custom_element_name="home-page")` when you want a different tag. Every component renders as a custom element. Components return an element tree built with the `html` helpers. Reactive state comes from `Signal`, `use_state`, and `use_computed`; the framework refreshes the DOM automatically when the state changes. ## Next steps Head to the [Installation](/documents/getting-started/installation) guide for the full setup reference, or explore the demos in the navigation bar to see components, routing, and reactive state in action. --- Source: https://webcompy.net/documents/getting-started/project-structure.md (Category: Getting Started) # Project Structure Running `webcompy init` inside an existing Python project scaffolds an application package with this layout: ```text webcompy-project/ ├── app/ │ ├── __init__.py │ ├── app.py # the WebComPyApp instance │ ├── router.py # route table │ └── components/ # your components (home.py, ...) ├── webcompy_config.py # build + server configuration ├── pyproject.toml # project metadata and browser dependencies ├── webcompy-lock.json # locked browser dependency versions ├── static/ # static files served as-is └── dist/ # generated output (SSG) ``` ## The app package `app/app.py` holds the `WebComPyApp` instance — the central object that owns routes, head metadata, styles, and scripts. `app/router.py` maps URL paths to lazily-loaded components, and `app/components/` holds the components themselves. Each component file defines one or more `@define_component()` functions that render as custom elements. ## Configuration: build vs server `webcompy_config.py` separates two concerns in one file: ```python config = WebComPyBuildConfig( app_module, # your app package (imported as a module) dependencies=None, # explicit browser deps (or resolve from pyproject) dependencies_from=None, # e.g. "browser": read browser deps from pyproject server=WebComPyServerConfig(port=8080), # dev server / SSR serving options ) ``` - The **`WebComPyBuildConfig`** fields (`dependencies`, `dependencies_from`, lockfile sync) control how browser dependencies are resolved and locked for the PyScript runtime. - The **`server`** field (`WebComPyServerConfig`) controls serving only — port, and related runtime options. It never affects the browser bundle. Each field is explained in place where it appears; the [Installation](/documents/getting-started/installation) guide walks through a complete example including the browser-dependency variant. ## Static files and resources The `static/` directory holds files served verbatim — stylesheets, images, and other assets your pages reference. App-package resource files (text resources transferred to the browser) go through the resource port with an allow-list, so only declared resources are exposed. ## The lockfile `webcompy-lock.json` pins the exact browser dependency versions resolved from `pyproject.toml`. It is generated by `webcompy lock` and keeps every machine — and the PyScript runtime — on identical versions. The lock workflow (`lock`, `lock --sync`, `lock --export`, `lock --install`) is covered in the [Installation](/documents/getting-started/installation) guide. `dist/` is generated output from `webcompy generate` (static site generation). It is a build artifact, not source — regenerate rather than edit it. ## Next steps With the layout in mind, head to the [Quickstart](/documents/getting-started/quickstart) to render your first component, inspect the full field reference in [Project Configuration](/documents/server/project-configuration) and [CLI Reference](/documents/server/cli-reference), or browse the demos in the navigation bar. --- Source: https://webcompy.net/documents/guides/overview.md (Category: Guides) # Guides Overview This tutorial builds one **ToDo application** from scratch across six sequential steps. By the end, you will have a working single-page app with reactive filtering, reusable components, hash-routed views, validated forms, async HTTP loading, error recovery, and a static production bundle. Each step runs a live interactive PyScript demo and shows its full standalone `app.py` source at the bottom of the page, so you can read and test every milestone independently. ## Prerequisites - Completed [Quickstart](/documents/getting-started/quickstart) and [Project Structure](/documents/getting-started/project-structure) - A local project created with `webcompy init` and dependencies installed via `uv sync` ## Tutorial roadmap | Step | Topic | What the app gains | Time | |---|---|---|---| | 1 | [Step 1: App Shell](/documents/guides/todo-app-shell) | Seeded tasks in a `ReactiveList`, filter state, `use_computed`, `repeat(..., key=...)` | ~10 min | | 2 | [Step 2: Components](/documents/guides/todo-components) | Extracted `TodoItem` and `TodoToolbar` components using props and slots | ~10 min | | 3 | [Step 3: Navigation](/documents/guides/todo-navigation) | Flat `Router` (`/`, `/active`, `/done`), `RouterLink` active styling, and `RouterView` | ~10 min | | 4 | [Step 4: Forms](/documents/guides/todo-forms) | Add-task form with `use_field`, validators, `use_form`, `FormField`, `Input`, and `Checkbox` | ~15 min | | 5 | [Step 5: Remote Data](/documents/guides/todo-remote-data) | Typed `HttpClient` requests, `use_async_result` loading/error UI, and an in-app `FetchMiddleware` mock | ~15 min | | 6 | [Step 6: Deploy](/documents/guides/todo-deploy) | `ErrorBoundary` recovery and static build output with `webcompy generate` | ~10 min | ## How each step builds on the last 1. **Shell first, interactivity second**: Start by proving that reactive collections and derived counts render cleanly before adding child components or routes. 2. **Basic-tier APIs throughout**: Every step stays within core WebComPy primitives (`webcompy.signal`, `webcompy.components`, `webcompy.elements`, `webcompy.router`, `webcompy.forms`, `webcompy.ui`, and `webcompy.ajax`), except Step 5's compact client-side `FetchMiddleware` mock so remote requests work identically on static hosting. 3. **Self-contained demos**: Every step embeds a runnable iframe backed by its own `app.py` file and finishes with links to deeper reference pages. ## Next steps - Start building the app shell in [Step 1: App Shell](/documents/guides/todo-app-shell). --- Source: https://webcompy.net/documents/guides/todo-app-shell.md (Category: Guides) # Step 1 — App Shell and Reactive State In this first step (~10 minutes), you build the root `TodoApp` shell with three seeded tasks, reactive filter buttons (`All`, `Active`, `Done`), and a live counter showing how many tasks remain. There are no input forms or subcomponents yet — the goal is to wire reactive state and keyed list rendering cleanly. The live interactive demo and complete source for this step appear at the bottom of the page. ## Defining task state with `use_reactive_list()` and `Signal` Each task stores an integer `id`, a `title`, and a reactive `done` cell (`Signal[bool]`) so individual completion flags can update later without replacing the whole list: ```python from typing import TypedDict from webcompy.signal import Signal, use_reactive_list, use_state class TaskItem(TypedDict): id: int title: str done: Signal[bool] ``` Inside `TodoApp`, initialize both `tasks` and `filter_mode` with factory callables (`lambda: ...`) so setup stays friendly to pre-rendering and hydration: ```python tasks = use_reactive_list( lambda: [ TaskItem(id=1, title="Read Getting Started", done=Signal(True)), TaskItem(id=2, title="Build TodoApp state", done=Signal(False)), TaskItem(id=3, title="Split into components", done=Signal(False)), ] ) filter_mode = use_state(lambda: "all") ``` ## Deriving counts and filtered views with `use_computed()` Derived values compute automatically whenever `tasks.value`, any task's `done.value`, or `filter_mode.value` changes: ```python from webcompy.signal import use_computed remaining = use_computed(lambda: sum(1 for t in tasks.value if not t["done"].value)) visible_tasks = use_computed( lambda: [ t for t in tasks.value if filter_mode.value == "all" or (filter_mode.value == "active" and not t["done"].value) or (filter_mode.value == "done" and t["done"].value) ] ) ``` Because `use_computed` tracks every signal read during execution, you never have to subscribe or recalculate counts manually when switching filters or toggling tasks. ## Rendering keyed lists with `repeat()` and filter buttons Pass `visible_tasks` to `repeat(..., key=lambda task: task["id"])` inside `html.UL(...)`. Supplying a stable `key=` lets WebComPy reuse existing `
  • ` nodes across filter switches: ```python from webcompy.elements import html, repeat html.UL( {"class": "task-list"}, repeat( visible_tasks, lambda task, _key: html.LI( {"class": use_computed(lambda: "todo-item done" if task["done"].value else "todo-item")}, task["title"], ), key=lambda task: task["id"], ), ) ``` Each filter button updates `filter_mode.value` on `@click` and highlights the selected button using a computed `"class"` attribute. Attach CSS rules to `TodoApp.scoped_style` using WebComPy's semantic design tokens (`var(--color-accent)`, `var(--space-2)`). ## Next steps - Extract `TodoItem` and `TodoToolbar` into reusable components in [Step 2: Components](/documents/guides/todo-components). - Review reactive primitives in [Reactive State](/documents/basic/reactive-state) and list reconciliation in [Elements & Events](/documents/basic/elements-and-events). ## Complete demo source ```python from typing import TypedDict from webcompy.app import WebComPyApp from webcompy.components import ComponentContext, define_component from webcompy.elements import html, repeat from webcompy.signal import Signal, use_computed, use_reactive_list, use_state class TaskItem(TypedDict): id: int title: str done: Signal[bool] @define_component() def TodoApp(_: ComponentContext[None]): tasks = use_reactive_list( lambda: [ TaskItem(id=1, title="Read Getting Started", done=Signal(True)), TaskItem(id=2, title="Build TodoApp state", done=Signal(False)), TaskItem(id=3, title="Split into components", done=Signal(False)), ] ) filter_mode = use_state(lambda: "all") remaining = use_computed(lambda: sum(1 for t in tasks.value if not t["done"].value)) visible_tasks = use_computed( lambda: [ t for t in tasks.value if filter_mode.value == "all" or (filter_mode.value == "active" and not t["done"].value) or (filter_mode.value == "done" and t["done"].value) ] ) def filter_button(label: str, mode: str): return html.BUTTON( { "type": "button", "class": use_computed(lambda: "active" if filter_mode.value == mode else ""), "@click": lambda _ev: setattr(filter_mode, "value", mode), }, label, ) return html.DIV( {"class": "todo-shell"}, html.H1({}, "ToDo Tutorial"), html.DIV( {"class": "toolbar"}, html.SPAN({"class": "remaining"}, use_computed(lambda: f"{remaining.value} remaining")), html.DIV( {"class": "filters"}, filter_button("All", "all"), filter_button("Active", "active"), filter_button("Done", "done"), ), ), html.UL( {"class": "task-list"}, repeat( visible_tasks, lambda task, _key: html.LI( {"class": use_computed(lambda: "todo-item done" if task["done"].value else "todo-item")}, task["title"], ), key=lambda task: task["id"], ), ), ) TodoApp.scoped_style = { ".todo-shell": { "max-width": "32rem", "padding": "var(--space-3)", "font-family": "var(--font-sans)", "color": "var(--color-fg)", }, ".toolbar": { "display": "flex", "justify-content": "space-between", "align-items": "center", "gap": "var(--space-2)", "margin": "var(--space-3) 0", }, ".filters": {"display": "flex", "gap": "var(--space-2)"}, ".filters button": { "padding": "var(--space-1) var(--space-3)", "border": "1px solid var(--color-border)", "border-radius": "var(--radius-sm)", "background": "var(--color-bg-card)", "color": "var(--color-fg)", "cursor": "pointer", }, ".filters button.active": { "background": "var(--color-accent)", "border-color": "var(--color-accent)", "color": "var(--color-on-accent)", "font-weight": "600", }, ".task-list": {"list-style": "none", "padding": "0", "margin": "0"}, ".todo-item": { "padding": "var(--space-2) var(--space-3)", "border": "1px solid var(--color-border)", "border-radius": "var(--radius-sm)", "background": "var(--color-bg-card)", "color": "var(--color-fg)", "margin-bottom": "var(--space-2)", }, ".todo-item.done": {"text-decoration": "line-through", "color": "var(--color-fg-muted)"}, } app = WebComPyApp(root_component=TodoApp) app.run() ``` --- Source: https://webcompy.net/documents/guides/todo-components.md (Category: Guides) # Step 2 — Components In Step 2 (~10 minutes), you split the monolithic `TodoApp` from Step 1 into focused UI building blocks: `TodoItem` for a single task row and `TodoToolbar` for the remaining count plus customizable filter controls. The live interactive demo and complete source for this step appear at the bottom of the page. ## Defining multi-word components with `@define_component()` Call `@define_component()` with parentheses so WebComPy derives the Light DOM custom element tag from the PascalCase function name (`TodoItem` becomes ``, `TodoToolbar` becomes ``, and `TodoApp` becomes ``): ```python from webcompy.components import ComponentContext, define_component from webcompy.elements import html from webcompy.signal import use_computed @define_component() def TodoItem(context: ComponentContext[TaskItem]): task = context.props return html.LI( {"class": use_computed(lambda: "todo-item done" if task["done"].value else "todo-item")}, html.SPAN({}, task["title"]), ) ``` Moving `.todo-item` rules onto `TodoItem.scoped_style` keeps item styling encapsulated alongside its markup. ## Passing props and default slots into `TodoToolbar` `TodoToolbar` receives a `remaining` signal in `context.props` and renders custom filter controls passed through its `"default"` slot via `context.slots("default", fallback=lambda: None)`: ```python from typing import TypedDict from webcompy.signal import SignalBase class ToolbarProps(TypedDict): remaining: SignalBase[int] @define_component() def TodoToolbar(context: ComponentContext[ToolbarProps]): remaining = context.props["remaining"] return html.DIV( {"class": "toolbar"}, html.SPAN({"class": "remaining"}, use_computed(lambda: f"{remaining.value} remaining")), context.slots("default", fallback=lambda: None), ) ``` In `TodoApp`, pass the filter button strip inside `slots={"default": lambda: ...}`: ```python TodoToolbar( {"remaining": remaining}, slots={ "default": lambda: html.DIV( {"class": "filters"}, filter_button("All", "all"), filter_button("Active", "active"), filter_button("Done", "done"), ) }, ) ``` Keeping the navigation region as a slot prepares `TodoToolbar` for Step 3, where those buttons become router links without rewriting `TodoToolbar` itself. ## Next steps - Replace local filter buttons with client-side routes in [Step 3: Navigation](/documents/guides/todo-navigation). - Learn more about component tag derivation, props, slots, and `:host` styling in [Components](/documents/basic/components). ## Complete demo source ```python from typing import TypedDict from webcompy.app import WebComPyApp from webcompy.components import ComponentContext, define_component from webcompy.elements import html, repeat from webcompy.signal import Signal, SignalBase, use_computed, use_reactive_list, use_state class TaskItem(TypedDict): id: int title: str done: Signal[bool] class ToolbarProps(TypedDict): remaining: SignalBase[int] @define_component() def TodoItem(context: ComponentContext[TaskItem]): task = context.props return html.LI( {"class": use_computed(lambda: "todo-item done" if task["done"].value else "todo-item")}, html.SPAN({}, task["title"]), ) TodoItem.scoped_style = { ".todo-item": { "padding": "var(--space-2) var(--space-3)", "border": "1px solid var(--color-border)", "border-radius": "var(--radius-sm)", "background": "var(--color-bg-card)", "color": "var(--color-fg)", "margin-bottom": "var(--space-2)", }, ".todo-item.done": {"text-decoration": "line-through", "color": "var(--color-fg-muted)"}, } @define_component() def TodoToolbar(context: ComponentContext[ToolbarProps]): remaining = context.props["remaining"] return html.DIV( {"class": "toolbar"}, html.SPAN({"class": "remaining"}, use_computed(lambda: f"{remaining.value} remaining")), context.slots("default", fallback=lambda: None), ) TodoToolbar.scoped_style = { ".toolbar": { "display": "flex", "justify-content": "space-between", "align-items": "center", "gap": "var(--space-2)", "margin": "var(--space-3) 0", }, ".filters": {"display": "flex", "gap": "var(--space-2)"}, ".filters button": { "padding": "var(--space-1) var(--space-3)", "border": "1px solid var(--color-border)", "border-radius": "var(--radius-sm)", "background": "var(--color-bg-card)", "color": "var(--color-fg)", "cursor": "pointer", }, ".filters button.active": { "background": "var(--color-accent)", "border-color": "var(--color-accent)", "color": "var(--color-on-accent)", "font-weight": "600", }, } @define_component() def TodoApp(_: ComponentContext[None]): tasks = use_reactive_list( lambda: [ TaskItem(id=1, title="Read Getting Started", done=Signal(True)), TaskItem(id=2, title="Build TodoApp state", done=Signal(False)), TaskItem(id=3, title="Split into components", done=Signal(False)), ] ) filter_mode = use_state(lambda: "all") remaining = use_computed(lambda: sum(1 for t in tasks.value if not t["done"].value)) visible_tasks = use_computed( lambda: [ t for t in tasks.value if filter_mode.value == "all" or (filter_mode.value == "active" and not t["done"].value) or (filter_mode.value == "done" and t["done"].value) ] ) def filter_button(label: str, mode: str): return html.BUTTON( { "type": "button", "class": use_computed(lambda: "active" if filter_mode.value == mode else ""), "@click": lambda _ev: setattr(filter_mode, "value", mode), }, label, ) return html.DIV( {"class": "todo-shell"}, html.H1({}, "ToDo Tutorial"), TodoToolbar( {"remaining": remaining}, slots={ "default": lambda: html.DIV( {"class": "filters"}, filter_button("All", "all"), filter_button("Active", "active"), filter_button("Done", "done"), ) }, ), html.UL( {"class": "task-list"}, repeat(visible_tasks, lambda task, _key: TodoItem(task), key=lambda task: task["id"]), ), ) TodoApp.scoped_style = { ".todo-shell": { "max-width": "32rem", "padding": "var(--space-3)", "font-family": "var(--font-sans)", "color": "var(--color-fg)", }, ".task-list": {"list-style": "none", "padding": "0", "margin": "0"}, } app = WebComPyApp(root_component=TodoApp) app.run() ``` --- Source: https://webcompy.net/documents/guides/todo-navigation.md (Category: Guides) # Step 3 — Navigation In Step 3 (~10 minutes), you replace the ephemeral `filter_mode` signal with real URL routes (`/`, `/active`, `/done`) rendered through `RouterView`, and upgrade `TodoToolbar`'s slot to render `RouterLink` navigation with active styling. The live interactive demo and complete source for this step appear at the bottom of the page. ## Sharing tasks across routed views Each routed page component mounts when its path matches, so the task list needs to outlive an individual route transition. This tutorial keeps `tasks` in a module-level `ReactiveList` (`tasks: ReactiveList[TaskItem] = ReactiveList(_seed_tasks())`) for client-side simplicity; in server-rendered (SSR) applications, share cross-page state through Dependency Injection (covered in Advanced Usage) rather than module globals. A small helper builds the filtered list view for all three pages: ```python from webcompy.components import ComponentContext, define_component from webcompy.elements import html, repeat from webcompy.router import RouterContext, RouterLink from webcompy.signal import use_computed def _render_task_list(mode: str): filtered = use_computed( lambda: [ t for t in tasks.value if mode == "all" or (mode == "active" and not t["done"].value) or (mode == "done" and t["done"].value) ] ) return html.UL( {"class": "task-list"}, repeat(filtered, lambda task, _key: TodoItem(task), key=lambda task: task["id"]), ) @define_component() def TodoAllPage(_: ComponentContext[RouterContext]): return _render_task_list("all") @define_component() def TodoActivePage(_: ComponentContext[RouterContext]): return _render_task_list("active") @define_component() def TodoDonePage(_: ComponentContext[RouterContext]): return _render_task_list("done") ``` ## Wiring `Router`, `RouterLink`, and `RouterView` Pass flat route mappings and a fallback `default=TodoNotFoundPage` component to `Router(...)`, then attach the router to `WebComPyApp(root_component=TodoApp, router=router)`: ```python from webcompy.app import WebComPyApp from webcompy.router import Router, RouterLink, RouterView router = Router( {"path": "/", "component": TodoAllPage}, {"path": "/active", "component": TodoActivePage}, {"path": "/done", "component": TodoDonePage}, default=TodoNotFoundPage, mode="hash", ) app = WebComPyApp(root_component=TodoApp, router=router) ``` Inside `TodoApp`, replace the filter ` """, {"count": count, "increment": increment}, ) ``` ## Interpolation and reactivity Use `{{ expr }}` in text content or HTML attribute values: - **Direct Signal reference**: `{{ count }}` passes the `Signal` directly into a reactive text node or attribute — updates are surgical with zero intermediate wrapper. - **Expression or dotted path through a Signal**: expressions like `{{ count * 2 }}`, `{{ "even" if count % 2 == 0 else "odd" }}`, or `{{ user.profile.name }}` when `profile` is a `Signal` automatically wrap in an implicit `Computed` so the DOM updates whenever any referenced Signal changes. - **Static context values**: plain strings, numbers, `Element`, and `Component` objects are inserted directly without extra reactive overhead. A `None` variable renders nothing in text positions and `""` in attribute interpolation. - **Boolean attributes**: valueless attributes such as `

    Hello {{ name | default("stranger") }}

    """, {"name": name, "input_ref": input_ref, "focus_input": focus_input}, ) ``` Only `:ref` and `:bind` are valid `:`-prefixed attributes on standard HTML elements. To compute regular HTML attributes dynamically, use `{{ ... }}` (e.g., `class="{{ item_class }}"`). ## Component tags in templates Any hyphenated tag not in standard HTML (such as ``) resolves via the application's component registry by converting kebab-case to PascalCase (`` → `UserCard`). Plain attributes become string props, `:`-prefixed props pass context variables (preserving Signals), and element children become the component's `"default"` slot: ```html

    Shown inside the default slot.

    ``` Note that `:`-prefixed prop names convert kebab-case to snake_case in `context.props` (`:item-count` → `context.props["item_count"]`). ## Notes & caveats - **Single root element**: `render_template()` requires exactly one top-level root element (`
    ...
    `). Return multiple roots at the component boundary with a Python `list` if needed. - **Rejected HTML tags**: `