Skip to content

Elements

Elements are what a component returns: the boxes layout sizes and the screen draws, as HTML elements are for a React component. Each is an immutable value, a frozen dataclass, and there are three:

  • Div is a box that holds other elements and components, as its children, and lays them out.
  • Text is a leaf that holds text, as a string or as styled chunks, which layout measures and wraps.
  • Canvas is a leaf whose cells a painter draws, for pictures, plots and anything else that isn't text.

All three take a style (see Styles), an on_input handler that receives the input events delivered to them, and a handle that names them for the scroll controls.

Below, a rounded Div lays out a Canvas, which draws a heart in half blocks, beside a column Div of two Texts: the first built from two chunks in different colors, and the second wrapping to the column's width.

HEART_ART = (
    ".XX.XX.",
    "XXXXXXX",
    "XXXXXXX",
    ".XXXXX.",
    "..XXX..",
    "...X...",
)
HEART = Pixels.from_points(
    width=7,
    height=6,
    points={Position(x, y): rose_500 for y, line in enumerate(HEART_ART) for x, c in enumerate(line) if c == "X"},
    default=slate_900,
)


@component
def root() -> Div:
    return Div(
        style=row
        | align_children_center
        | gap(2)
        | border
        | border_lightrounded
        | pad_x(1)
        | content_color("slate", 900),
        children=(
            Canvas(painter=HalfBlocks(HEART)),
            Div(
                style=col | width(30),
                children=(
                    Text(
                        style=text_bg("slate", 900),
                        content=(
                            Chunk(content="Favorites", style=text_color("rose", 400).text_style),
                            Chunk(content=" · 3 new", style=text_color("slate", 500).text_style),
                        ),
                    ),
                    Text(
                        style=text_wrap_pretty | text_bg("slate", 900),
                        content="Everything you've starred, newest first.",
                    ),
                ),
            ),
        ),
    )

A Div holding a Canvas and two Texts

╭──────────────────────────────────────────╮
│ ▀▀▀▀▀▀▀  Favorites · 3 new               │
│ ▀▀▀▀▀▀▀  Everything you've starred,      │
│ ▀▀▀▀▀▀▀  newest first.                   │
╰──────────────────────────────────────────╯

API

counterweight.elements.AnyElement module-attribute

AnyElement = Div | Text | Canvas

Any element: what a component returns, and what a Div holds beside components.