Skip to content

API

Application

counterweight.app.app async

app(
    root: Callable[[], Component],
    output_stream: TextIO = sys.stdout,
    input_stream: TextIO = sys.stdin,
    headless: bool = False,
    dimensions: tuple[int, int] | None = None,
    autopilot: Iterable[AnyEvent | AnyControl] = (),
) -> None
PARAMETER DESCRIPTION
root

The root component of the application.

TYPE: Callable[[], Component]

output_stream

The stream to which the application will write its output.

TYPE: TextIO DEFAULT: stdout

input_stream

The stream from which the application will read its input.

TYPE: TextIO DEFAULT: stdin

headless

If True, the application will not attempt to read from the input stream or write to the output stream. This is primarily useful when combined with the autopilot parameter.

TYPE: bool DEFAULT: False

dimensions

The dimensions of the terminal window, in characters. If None, the dimensions of the terminal window will be used.

TYPE: tuple[int, int] | None DEFAULT: None

autopilot

An iterable of events and controls to be processed by the application. This is primarily useful for testing or generating screenshots programmatically. Note that the autopilot will not be processed until after the initial render cycle, and that using the autopilot does not automatically cause the application to quit!

TYPE: Iterable[AnyEvent | AnyControl] DEFAULT: ()

Components

counterweight.components.component

component(
    func: Callable[P, AnyElement]
) -> Callable[P, Component]

A decorator that marks a function as a component.

counterweight.components.Component dataclass

Component(
    func: Callable[..., AnyElement],
    args: tuple[object, ...],
    kwargs: dict[str, object],
    key: str | int | None = None,
)

The result of calling a component function. These should not be instantiated directly; instead, use the @component decorator on a function and call it normally.

func instance-attribute

func: Callable[..., AnyElement]

args instance-attribute

args: tuple[object, ...]

kwargs instance-attribute

kwargs: dict[str, object]

key class-attribute instance-attribute

key: str | int | None = None

with_key

with_key(key: str | int | None) -> Component

Elements

counterweight.elements.AnyElement module-attribute

AnyElement = Union[Div, Text]

counterweight.elements.Div

type class-attribute instance-attribute

type: Literal['div'] = 'div'

style class-attribute instance-attribute

style: Style = Field(default=Style())

children class-attribute instance-attribute

children: Sequence[Component | AnyElement] = Field(
    default=()
)

on_key class-attribute instance-attribute

on_key: Callable[[KeyPressed], AnyControl | None] | None = (
    None
)

on_mouse class-attribute instance-attribute

on_mouse: (
    Callable[[MouseEvent], AnyControl | None] | None
) = None

counterweight.elements.Text

type class-attribute instance-attribute

type: Literal['text'] = 'text'

content instance-attribute

content: str | Sequence[Chunk]

style class-attribute instance-attribute

style: Style = Field(default=Style())

on_key class-attribute instance-attribute

on_key: Callable[[KeyPressed], AnyControl | None] | None = (
    None
)

on_mouse class-attribute instance-attribute

on_mouse: (
    Callable[[MouseEvent], AnyControl | None] | None
) = None

children property

cells cached property

cells: tuple[CellPaint, ...]

Hooks

counterweight.hooks.use_state

use_state(
    initial_value: Getter[T] | T,
) -> tuple[T, Setter[T]]
PARAMETER DESCRIPTION
initial_value

The initial value of the state. It can either be the initial value itself, or a zero-argument function that returns the initial value.

TYPE: Getter[T] | T

RETURNS DESCRIPTION
T

The current value of the state (i.e., for the current render cycle).

Setter[T]

A function that can be called to update the value of the state (e.g., in an event handler). It can either be called with the new value of the state, or a function that takes the current value of the state and returns the new value of the state. If the value is not equal to the current of the state, Counterweight will trigger a render cycle.

counterweight.hooks.Getter module-attribute

Getter = Callable[[], T]

counterweight.hooks.Setter module-attribute

Setter = Callable[[Callable[[T], T] | T], None]

counterweight.hooks.use_effect

use_effect(setup: Setup, deps: Deps = None) -> None
PARAMETER DESCRIPTION
setup

The setup function that will be called when the component first mounts or if its dependencies have changed (see below).

TYPE: Setup

deps

The dependencies of the effect. If any of the dependencies change, the previous invocation of the setup function will be cancelled and the setup function will be run again. If None, the setup function will be run on every render.

TYPE: Deps DEFAULT: None

counterweight.hooks.Setup module-attribute

Setup = Callable[[], Coroutine[None, None, None]]

counterweight.hooks.Deps module-attribute

Deps = tuple[object, ...] | None

counterweight.hooks.use_ref

use_ref(initial_value: Getter[T] | T) -> Ref[T]
PARAMETER DESCRIPTION
initial_value

the initial value of the ref. It can either be the initial value itself, or a zero-argument function that returns the initial value.

TYPE: Getter[T] | T

RETURNS DESCRIPTION
Ref[T]

A Ref that holds a reference to the given value.

counterweight.hooks.Ref

current instance-attribute

current: T

counterweight.hooks.use_mouse

use_mouse() -> Mouse
RETURNS DESCRIPTION
Mouse

A record describing the current state of the mouse.

counterweight.hooks.Mouse dataclass

Mouse(
    absolute: Position, motion: Position, button: int | None
)

absolute instance-attribute

absolute: Position

The absolute position of the mouse on the screen (i.e., the top-left corner of the screen is Position(x=0, y=0)).

motion instance-attribute

motion: Position

The difference in the absolute position of the mouse since the last render cycle.

button instance-attribute

button: int | None

The button that is currently pressed, or None if no button is pressed.

counterweight.hooks.use_rects

use_rects() -> Rects
RETURNS DESCRIPTION
Rects

A recording describing the rectangular areas of the content, padding, border, and margin of the calling component's top-level element on the previous render cycle. In the initial render, the returned rectangles will all be positioned at the top-left corner of the screen with 0 width and height.

counterweight.hooks.Rects dataclass

Rects(
    content: Rect, padding: Rect, border: Rect, margin: Rect
)

content instance-attribute

content: Rect

padding instance-attribute

padding: Rect

border instance-attribute

border: Rect

margin instance-attribute

margin: Rect

counterweight.hooks.use_hovered

use_hovered() -> Hovered
RETURNS DESCRIPTION
Hovered

A record describing which of the calling component's top-level element's content, padding, border, and margin rectangles the mouse is currently inside.

counterweight.hooks.Hovered dataclass

Hovered(
    content: bool, padding: bool, border: bool, margin: bool
)

content instance-attribute

content: bool

padding instance-attribute

padding: bool

border instance-attribute

border: bool

margin instance-attribute

margin: bool

Events

counterweight.events.KeyPressed dataclass

KeyPressed(key: str)

key instance-attribute

key: str

counterweight.events.MouseEvent module-attribute

counterweight.events.MouseMoved dataclass

MouseMoved(absolute: Position, button: int | None)

absolute instance-attribute

absolute: Position

The absolute position on the screen that the mouse moved to.

button instance-attribute

button: int | None

The button that was held during the motion, or None if no button was pressed.

counterweight.events.MouseDown dataclass

MouseDown(absolute: Position, button: int)

absolute instance-attribute

absolute: Position

The absolute position on the screen that the mouse moved to.

button instance-attribute

button: int

The mouse button that was pressed during the motion.

counterweight.events.MouseUp dataclass

MouseUp(absolute: Position, button: int)

absolute instance-attribute

absolute: Position

The absolute position on the screen that the mouse moved to.

button instance-attribute

button: int

The mouse button that was released during the motion.

counterweight.events.MouseScrolledDown dataclass

MouseScrolledDown(absolute: Position, direction: int = 1)

absolute instance-attribute

absolute: Position

The absolute position on the screen that the mouse moved to.

direction class-attribute instance-attribute

direction: int = 1

The direction that the mouse was scrolled as an integer offset; -1 for up, +1 for down.

counterweight.events.MouseScrolledUp dataclass

MouseScrolledUp(absolute: Position, direction: int = -1)

absolute instance-attribute

absolute: Position

The absolute position on the screen that the mouse moved to.

direction class-attribute instance-attribute

direction: int = -1

The direction that the mouse was scrolled as an integer offset; -1 for up, +1 for down.

Controls

counterweight.controls.AnyControl module-attribute

counterweight.controls.Quit dataclass

Quit()

Cause the application to quit.

The quit occurs at the beginning of the next render cycle, so all other events that are due to be processed in the current cycle will be processed before the application exits.

counterweight.controls.Bell dataclass

Bell()

Cause the terminal to emit a bell sound.

The bell occurs at the beginning of the next render cycle, so all other events that are due to be processed in the current cycle will be processed before the sound is played.

counterweight.controls.Screenshot dataclass

Screenshot(
    handler: Callable[[ElementTree], Awaitable[None] | None]
)

Take a "screenshot" of the rendered UI, using the given handler callback function. The screenshot is passed to the handler as an ElementTree containing an SVG representation of the UI.

The screenshot is taken at the beginning of the next render cycle, so all other events that are due to be processed in the current cycle will be processed before the screenshot is taken (but the screenshot will still be of the UI from before the next render occurs!).

handler instance-attribute

handler: Callable[[ElementTree], Awaitable[None] | None]

to_file classmethod

to_file(
    path: Path, indent: int | None = None
) -> Screenshot

A convenience method for producing a Screenshot that writes the resulting SVG to the given path.

PARAMETER DESCRIPTION
path

The path to write the SVG to. Parent directories will be created if they do not exist.

TYPE: Path

indent

The number of spaces to indent the SVG by (for readability). If None, the SVG will not be indented.

TYPE: int | None DEFAULT: None

counterweight.controls.ToggleBorderHealing dataclass

ToggleBorderHealing()

Toggle whether border healing occurs.

Styles

counterweight.styles.Style

layout class-attribute instance-attribute

layout: Flex = Field(default=Flex())

span class-attribute instance-attribute

span: Span = Field(default=Span())

margin class-attribute instance-attribute

margin: Margin = Field(default=Margin())

border class-attribute instance-attribute

border: Border | None = Field(default=None)

padding class-attribute instance-attribute

padding: Padding = Field(default=Padding())

content class-attribute instance-attribute

content: Content = Field(default=Content())

typography class-attribute instance-attribute

typography: Typography = Field(default=Typography())

counterweight.styles.Span

width class-attribute instance-attribute

width: int | Literal['auto'] = Field(default='auto')

height class-attribute instance-attribute

height: int | Literal['auto'] = Field(default='auto')

counterweight.styles.Margin

top class-attribute instance-attribute

top: int = Field(default=0)

bottom class-attribute instance-attribute

bottom: int = Field(default=0)

left class-attribute instance-attribute

left: int = Field(default=0)

right class-attribute instance-attribute

right: int = Field(default=0)

color class-attribute instance-attribute

color: Color = Field(default=from_name('black'))

counterweight.styles.Border

kind class-attribute instance-attribute

kind: BorderKind = Field(default=Light)

style class-attribute instance-attribute

style: CellStyle = Field(default=CellStyle())

edges class-attribute instance-attribute

edges: frozenset[BorderEdge] = frozenset(
    {Top, Bottom, Left, Right}
)

contract class-attribute instance-attribute

contract: int = Field(default=0)

counterweight.styles.Padding

top class-attribute instance-attribute

top: int = Field(default=0)

bottom class-attribute instance-attribute

bottom: int = Field(default=0)

left class-attribute instance-attribute

left: int = Field(default=0)

right class-attribute instance-attribute

right: int = Field(default=0)

color class-attribute instance-attribute

color: Color = Field(default=from_name('black'))

counterweight.styles.Content

color class-attribute instance-attribute

color: Color = Field(default=from_name('black'))

counterweight.styles.Typography

style class-attribute instance-attribute

style: CellStyle = Field(default=CellStyle())

justify class-attribute instance-attribute

justify: Literal['left', 'center', 'right'] = 'left'

wrap class-attribute instance-attribute

wrap: Literal['none', 'paragraphs'] = 'none'

counterweight.styles.Color

red instance-attribute

red: int

green instance-attribute

green: int

blue instance-attribute

blue: int

hex property

hex: str

from_name classmethod

from_name(name: str) -> Color

from_hex cached classmethod

from_hex(hex: str) -> Color

blend

blend(other: Color, alpha: float) -> Color

counterweight.styles.CellStyle

foreground class-attribute instance-attribute

foreground: Color = Field(default=from_name('white'))

background class-attribute instance-attribute

background: Color = Field(default=from_name('black'))

bold class-attribute instance-attribute

bold: bool = False

dim class-attribute instance-attribute

dim: bool = False

italic class-attribute instance-attribute

italic: bool = False

underline class-attribute instance-attribute

underline: bool = False

strikethrough class-attribute instance-attribute

strikethrough: bool = False

Layout

counterweight.styles.Flex

type class-attribute instance-attribute

type: Literal['flex'] = 'flex'

direction class-attribute instance-attribute

direction: Literal['row', 'column'] = 'row'

position class-attribute instance-attribute

position: Relative | Absolute | Fixed = Field(
    default=Relative(), discriminator="type"
)

weight class-attribute instance-attribute

weight: PositiveInt | None = 1

z class-attribute instance-attribute

z: int = 0

align_self class-attribute instance-attribute

align_self: Literal[
    "none", "start", "center", "end", "stretch"
] = "none"

justify_children class-attribute instance-attribute

justify_children: Literal[
    "start",
    "center",
    "end",
    "space-between",
    "space-around",
    "space-evenly",
] = "start"

align_children class-attribute instance-attribute

align_children: Literal[
    "start", "center", "end", "stretch"
] = "start"

gap_children class-attribute instance-attribute

gap_children: NonNegativeInt = 0

counterweight.styles.Relative

Relative positioning is relative to the parent element's content box. Elements occupy space and are laid out next to their siblings according to the parent's layout direction.

type class-attribute instance-attribute

type: Literal['relative'] = 'relative'

x class-attribute instance-attribute

x: int = 0

y class-attribute instance-attribute

y: int = 0

counterweight.styles.Absolute

Absolute positioning is relative to the parent element's content box, but the element does not occupy space in the layout.

The inset property determines which corner of the parent element's content box this element is positioned relative to.

type class-attribute instance-attribute

type: Literal['absolute'] = 'absolute'

x class-attribute instance-attribute

x: int = 0

y class-attribute instance-attribute

y: int = 0

inset class-attribute instance-attribute

inset: Inset = Field(default=Inset())

counterweight.styles.Inset

vertical class-attribute instance-attribute

vertical: Literal['top', 'center', 'bottom'] = 'top'

horizontal class-attribute instance-attribute

horizontal: Literal['left', 'center', 'right'] = 'left'

counterweight.styles.Fixed

Fixed positioning is relative to the screen's top-left corner (0, 0).

type class-attribute instance-attribute

type: Literal['fixed'] = 'fixed'

x class-attribute instance-attribute

x: int = 0

y class-attribute instance-attribute

y: int = 0