Skip to content

Adding a component#

A page is a tree of components, and a component is a class: its annotated fields are its props, and html(self, render) is its rendering. Subclass cgui.Component, annotate the props, implement html:

import capturegraph as cg
import capturegraph_ui as cgui


class Badge(cgui.Component):
    text: str

    def html(self, render: cgui.Render) -> str:
        return cgui.element("span", {"class": "badge"}, cgui.text(self.text))


class Session(cg.Struct):
    photo: cg.Image


@cgui.PageBuilder()
def session(session: Session) -> None:
    cgui.Title("Session")
    Badge("pending" if cg.is_missing(session.photo) else "photographed")
    cgui.ImageViewer(session.photo)

session is a page function (Pages): under @cgui.PageBuilder() its body constructs components top to bottom, and the wrapper returns a cgui.Page — a cg.DirScalar that is the website folder, declared now and written when built. Title, ImageViewer and Badge are components alike; the standard vocabulary — VStack, HStack, Divider, Padding, Markdown, Stat, Title, ImageViewer, Gallery, Timelapse, Scatter, Chart, MapViewer, PageLink — is tabled under Components. cg.Missing is the value a load hands back for data that is not there, and cg.is_missing(value) is true for it and for None (Missing data); page code normally lets absence fall through rather than guarding, and the guard here is the one case that warrants it — absence changes what the badge says.

Props#

Declaring the subclass freezes it as a dataclass over its annotations, so props are given positionally or by keyword in declaration order, and a prop with a default is an ordinary dataclass default (unit: str | None = None). A field annotated ClassVar is a class constant, not a prop. A prop is:

  • a Python primitive (bool, int, float, str), matched by exact type (bool is not an int), or a Literal of them (marker: Literal["pin", "dot"] = "pin");
  • a list, tuple or dict of props (dict[str, float]), each item checked in turn; a Missing item in a list is left out;
  • cg.JSONValue, for a specification passed through whole (spec: dict[str, cg.JSONValue]);
  • a cg value — the loaded data itself, not its JSON. A prop annotated with a scalar type is coerced by that type's own coerce: a file prop is one annotated with a file or directory scalar (image: cg.Image, model: cgr.Splat), and a bare path given for it becomes that scalar, its extension checked. A struct or container is accepted by instance, and a plain dict or list given for an annotated cg.Map or cg.Array becomes one;
  • another component (children: list[cgui.Component]);
  • a union of any of these, taking the first member that fits (value: float | str).

Every prop is checked against its annotation when the component is constructed (check_prop); a value that fits nothing raises TypeError there and then, naming the prop as Class.prop.

The base class gives a custom component the two behaviors every standard one has, with no code of its own:

  • Absence. A component given Missing for any prop renders as nothing, and an absent component's other props go unchecked, so absence never surfaces as a type error — a recipe returning Missing simply leaves the component out of the page.
  • Attachment. A @cgui.PageBuilder() call keeps a list of open stacks — the root VStack it opens first, then each with cgui.HStack(): or with cgui.VStack(): block while it lasts — and a freshly constructed component is appended to the children of the innermost. That is why the body of a page function reads as the page.

Writing HTML#

Three functions write the markup, all on the cgui root:

  • cgui.element(tag, attributes=None, *children) writes one element, its attribute values escaped and its children already HTML. An attribute value of None or False omits the attribute and True writes it bare; a void tag (img, input, link, meta, br, hr, source) renders with no closing tag and drops any children.
  • cgui.text(value) escapes text content — the only way a string becomes content.
  • cgui.inline_json(value) is a value as a JSON literal safe inside a <script> — the only way data enters one.

The render context#

Page.build() constructs one Render and hands it to the root's html, which hands it down to every component in the tree: one mutable context per build, shared by all of them. That is what makes its bookkeeping work — a file two components stage is copied once, ids count up across the page, and a once block fires once.

Files are what a viewer of your own calls:

Method Returns
render.stage(file) The relative href of file — a file or a directory — copied under files/, numbered from 0 in staging order (files/0.ply; a directory has no suffix, files/1); the same source staged twice is copied once.
render.lib(library, file) The relative href of file from a Library, copied whole under lib/ on first use; raises FileNotFoundError when the package ships no library of that name.

Deduplication supports a script or a stylesheet several components share:

Method Returns
render.once(key, html) html the first time key is seen in this render, "" after — for a script tag several components would otherwise repeat.
render.identifier(prefix) A fresh element id cg-<prefix>-<n>, counting from 1 per prefix, unique within the render.

Links resolve a value to the relative URL of its page:

Method Returns
render.href(value) The relative link to value's page, or None when it or this page has no position.
render.entry_href(container, key) The relative link to the page of a container's entry at key (a Map key or an Array index), or None when the container or this page has no position; raises TypeError for an Array and a non-int key.

href and entry_href are the only way a component links, and the standard vocabulary reserves linking for PageLink and the of constructors (Gallery.of, Timelapse.of, MapViewer.of); a viewer of your own that shows a loaded value should keep to that rule (Links).

A browser library of your own#

A component that needs JavaScript ships it as package data. A cgui.Library names the package and the folder:

import capturegraph_ui as cgui

GSPLAT = cgui.Library("capturegraph_recipes.splats", "gsplat")

The files live under <package>/_vendor/<name>/ beside the library's own LICENSE, its version goes in the VERSIONS manifest in _vendor/ beside the library folders (gsplat 1.2.9), and the package's pyproject.toml lists _vendor as package data so a wheel carries it (Packaging an extension). Library.copy_to(page, relative) writes the folder into a page under relative through the page's put, leaving unchanged files alone, and render.lib(GSPLAT, "index.es.js") calls it once per render — the first time any component asks for one of the library's files — into the page's lib/gsplat/, returning lib/gsplat/index.es.js, so the page stays self-contained. The ui package ships Leaflet and the Vega trio the same way, and a page uses a library from either package without knowing which shipped it.

The worked example: cgr.SplatViewer#

SplatViewer lives in capturegraph-recipes, in the splats folder whose output it draws, and neither the core nor the ui package knows of it or of Splat. This is the module as shipped: the ui package's names come through cgui, its public surface, and the package's own type from its leaf module, the way package-internal code does:

import capturegraph_ui as cgui

from capturegraph_recipes.types.geometry.splat import Splat

GSPLAT = cgui.Library("capturegraph_recipes.splats", "gsplat")

_ORBIT = """
import * as SPLAT from %(module)s;
const canvas = document.getElementById(%(id)s);
const scene = new SPLAT.Scene();
const camera = new SPLAT.Camera();
const renderer = new SPLAT.WebGLRenderer(canvas);
const controls = new SPLAT.OrbitControls(camera, canvas);
const splat = await SPLAT.PLYLoader.LoadAsync(%(model)s, scene, () => {});
splat.rotation = new SPLAT.Quaternion(1, 0, 0, 0);
const frame = () => {
  controls.update();
  renderer.render(scene, camera);
  requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
""".strip()


class SplatViewer(cgui.Component):
    """A ``model`` (a ``cgr.Splat`` PLY, staged into the page) in an orbit viewer."""

    model: Splat

    def html(self, render: cgui.Render) -> str:
        identifier = render.identifier("splat")
        return cgui.element("canvas", {"class": "cg-splat", "id": identifier}) + cgui.element(
            "script",
            {"type": "module"},
            _ORBIT
            % {
                "module": cgui.inline_json("./" + render.lib(GSPLAT, "index.es.js")),
                "id": cgui.inline_json(identifier),
                "model": cgui.inline_json(render.stage(self.model)),
            },
        )

_ORBIT is the module script, %-formatted with the three JSON literals the viewer computes: the library's href as the import path, the canvas id, and the staged PLY's href. It orbits a camera around the loaded splat; the half-turn about X crosses from ARKit's Y-up frame, which the splat is stored in, to gsplat's Y-down. The prop is typed Splat, so a page constructing the viewer with an image raises there and then — SplatViewer.model: Splat does not accept '.jpeg' files; its extensions are 'ply'. — and a recipe returning Missing for a session with no splat leaves the viewer out of that page.

Testing#

A page builds outside the server under the cg_scratch fixture — shipped by the core package as a pytest plugin, so any package's tests can name it — so a test builds one and reads the folder. Files are numbered in staging order and the viewer stages one, so the model is files/0.ply:

import capturegraph_recipes as cgr
import capturegraph_ui as cgui


def test_splat_viewer_stages_the_model_and_its_library(cg_scratch, tmp_path):
    ply = tmp_path / "model.ply"
    ply.write_bytes(b"ply-bytes")

    @cgui.PageBuilder()
    def scene() -> None:
        cgr.SplatViewer(cgr.Splat(ply))

    page = scene().build()

    assert (page / "files" / "0.ply").read_bytes() == b"ply-bytes"
    assert (page / "lib" / "gsplat" / "index.es.js").is_file()
    index = (page / "index.html").read_text()
    assert '"files/0.ply"' in index and "./lib/gsplat/index.es.js" in index

Assert on the folder — index.html, files/, lib/ — which is what the server hosts, never on the component's fields. The substring checks are the illustration, not the pattern: the recipes suite parses index.html into its tags and asserts the canvas's class and the script's type="module" by attribute.