Skip to content

component

component #

Component — one node of a page; a subclass's annotated fields are its props.

  1. Declaring a subclass freezes it as a dataclass over its annotations; constructing an instance checks every prop against its annotation (props).
  2. A page renders by asking each component for its HTML (html), handing it the page's render context to stage files and resolve links through.
  3. A component given a Missing for any prop — or None for a prop without a default — is absent: its props go unchecked and it renders as nothing (absent). A Missing item inside a list prop is left out instead (check_prop).
  4. Under a PageBuilder, a freshly built component attaches itself to the innermost open stack (Build.attach), so the body of a page function reads as the page, top to bottom.

Component #

Base of every page component; subclass it, annotate the props, implement html.

A prop is a Python primitive or a Literal of them, a list, tuple or dict of props, JSONValue, a cg value, or another component, optionally in a union that takes the first member that fits; each is checked against its annotation when the component is constructed (check_prop), and a path given for a file prop becomes that file scalar. A field with a default is optional; a ClassVar is a class constant, not a prop. A component given Missing for any prop, or None for a prop without a default, is absent and renders as nothing, so cgui.Stat("Wind", session.weather.wind_speed_mps) simply leaves the page when no weather was recorded, and cgui.Stat("ISO", exif.iso) when the photograph records none; a Missing item in a list prop is left out.

class Badge(cgui.Component):
    text: str

    def html(self, render: cgui.Render) -> str:
        return cgui.element("span", {"class": "badge"}, cgui.text(self.text))
Source code in capturegraph-ui/capturegraph_ui/core/component.py
@dataclass_transform(frozen_default=True)
class Component:
    """Base of every page component; subclass it, annotate the props, implement ``html``.

    A prop is a Python primitive or a ``Literal`` of them, a list, tuple or dict
    of props, ``JSONValue``, a ``cg`` value, or another component, optionally in
    a union that takes the first member that fits; each is checked against its
    annotation when the component is constructed (``check_prop``), and a path
    given for a file prop becomes that file scalar. A field with a default is
    optional; a ``ClassVar`` is a class constant, not a prop. A
    component given ``Missing`` for any prop, or ``None`` for a prop without a
    default, is absent and renders as nothing, so
    ``cgui.Stat("Wind", session.weather.wind_speed_mps)`` simply leaves the
    page when no weather was recorded, and ``cgui.Stat("ISO", exif.iso)`` when
    the photograph records none; a ``Missing`` item in a list prop is left out.

    ```python
    class Badge(cgui.Component):
        text: str

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

    _props: ClassVar[dict[str, object]] = {}
    _needed: ClassVar[frozenset[str]] = frozenset()

    def __init_subclass__(cls, **kwargs: object) -> None:
        """Freeze ``cls`` over its props and make its ``html`` render nothing when absent."""
        super().__init_subclass__(**kwargs)
        frozen = cast("type[DataclassInstance]", dataclass(frozen=True)(cls))
        cls._props = {
            name: hint
            for name, hint in get_type_hints(cls).items()
            if get_origin(hint) is not ClassVar
        }
        cls._needed = frozenset(
            field.name
            for field in fields(frozen)
            if field.default is MISSING and field.default_factory is MISSING
        )
        if "html" in cls.__dict__:
            cls.html = _nothing_when_absent(cls.__dict__["html"])

    def __post_init__(self) -> None:
        """Check every prop against its annotation, coercing where a scalar admits it.

        Raises:
            TypeError: If a prop does not fit its annotation; the message names the prop.
        """
        if not self.absent:
            for name, annotation in type(self)._props.items():
                checked = check_prop(
                    getattr(self, name), annotation, f"{type(self).__name__}.{name}"
                )
                object.__setattr__(self, name, checked)
        Build.attach(self)

    @property
    def absent(self) -> bool:
        """Whether a prop is ``Missing``, or ``None`` without a default: then it renders nothing."""
        return any(
            isinstance(value := getattr(self, name), cg.MissingType)
            or (value is None and name in type(self)._needed)
            for name in type(self)._props
        )

    def html(self, render: Render) -> str:
        """This component as HTML, its files staged and its links resolved through ``render``.

        Raises:
            NotImplementedError: Always, on the base class.
        """
        raise NotImplementedError(f"{type(self).__name__} does not implement html()")

absent property #

Whether a prop is Missing, or None without a default: then it renders nothing.

__init_subclass__(**kwargs) #

Freeze cls over its props and make its html render nothing when absent.

Source code in capturegraph-ui/capturegraph_ui/core/component.py
def __init_subclass__(cls, **kwargs: object) -> None:
    """Freeze ``cls`` over its props and make its ``html`` render nothing when absent."""
    super().__init_subclass__(**kwargs)
    frozen = cast("type[DataclassInstance]", dataclass(frozen=True)(cls))
    cls._props = {
        name: hint
        for name, hint in get_type_hints(cls).items()
        if get_origin(hint) is not ClassVar
    }
    cls._needed = frozenset(
        field.name
        for field in fields(frozen)
        if field.default is MISSING and field.default_factory is MISSING
    )
    if "html" in cls.__dict__:
        cls.html = _nothing_when_absent(cls.__dict__["html"])

__post_init__() #

Check every prop against its annotation, coercing where a scalar admits it.

Raises:

Type Description
TypeError

If a prop does not fit its annotation; the message names the prop.

Source code in capturegraph-ui/capturegraph_ui/core/component.py
def __post_init__(self) -> None:
    """Check every prop against its annotation, coercing where a scalar admits it.

    Raises:
        TypeError: If a prop does not fit its annotation; the message names the prop.
    """
    if not self.absent:
        for name, annotation in type(self)._props.items():
            checked = check_prop(
                getattr(self, name), annotation, f"{type(self).__name__}.{name}"
            )
            object.__setattr__(self, name, checked)
    Build.attach(self)

html(render) #

This component as HTML, its files staged and its links resolved through render.

Raises:

Type Description
NotImplementedError

Always, on the base class.

Source code in capturegraph-ui/capturegraph_ui/core/component.py
def html(self, render: Render) -> str:
    """This component as HTML, its files staged and its links resolved through ``render``.

    Raises:
        NotImplementedError: Always, on the base class.
    """
    raise NotImplementedError(f"{type(self).__name__} does not implement html()")