Skip to content

Handlers

counterweight.handlers holds handlers for common behaviors, and combinators that compose several handlers into the one an element's on_input takes. Nothing happens to an input event unless a handler on its path does it, so a behavior an element should have is a handler composed onto it.

Each library handler is a pure function of the event and the receiver, so it can be tested by calling it, without running an app.

An example

This basket has a button for each fruit, which adds one to the basket when it's clicked, or when Enter is pressed while it's focused, and a button that empties the basket:

FRUITS = ("Apples", "Pears", "Plums")


def button_style(is_focused: bool) -> Style:
    ring = border_color("amber", 400) | text_color("amber", 200) if is_focused else border_color("slate", 600)
    return border | border_lightrounded | pad_x(1) | ring


@component
def fruit_button(fruit: str, add: Callable[[], None]) -> Text:
    focus = use_focus()

    def add_on_enter(event: InputEvent, _: Receiver) -> InputResponse:
        match event:
            case KeyPressed(key=Key.Enter):
                add()
                return ()
            case _:
                return None

    return Text(
        content=fruit,
        style=button_style(focus.is_focused),
        on_input=first(add_on_enter, each(on_click(add), focus_receiver_on_press)),
    )


@component
def basket() -> Div:
    counts, set_counts = use_state(lambda: dict.fromkeys(FRUITS, 0))

    def add(fruit: str) -> None:
        set_counts(lambda counts: {**counts, fruit: counts[fruit] + 1})

    def empty() -> None:
        set_counts(dict.fromkeys(FRUITS, 0))

    def shortcuts(event: InputEvent, _: Receiver) -> InputResponse:
        match event:
            case KeyPressed(key=Key.Backspace):
                empty()
                return ()
            case _:
                return None

    return Div(
        style=col | full | pad_x(1),
        on_input=first(shortcuts, tab_focus, clear_focus),
        children=(
            Div(
                style=row | gap(1),
                children=(
                    *(fruit_button(fruit, partial(add, fruit)) for fruit in FRUITS),
                    Text(content="Empty", style=button_style(False), on_input=each(on_click(empty), clear_focus)),
                ),
            ),
            Text(content=" · ".join(f"{fruit}: {counts[fruit]}" for fruit in FRUITS)),
            Text(
                content="Tab moves focus, Enter adds the focused fruit, Backspace empties the basket",
                style=text_color("slate", 400),
            ),
        ),
    )

Each fruit button composes three handlers: its own add_on_enter for Enter, then, for presses, on_click and focus_receiver_on_press. The Empty button isn't focusable, and composes clear_focus with its on_click instead. The root's element composes the app's shortcuts, Tab navigation with tab_focus, and clear_focus for a press that lands on no button.

Pears focused, with two pears in the basket

 ╭────────╮ ╭───────╮ ╭───────╮ ╭───────╮                   
 │ Apples │ │ Pears │ │ Plums │ │ Empty │                   
 ╰────────╯ ╰───────╯ ╰───────╯ ╰───────╯                   
 Apples: 0 · Pears: 2 · Plums: 0                            
 Tab moves focus, Enter adds the focused fruit, Backspace em

Plums focused, with a plum added to the basket

 ╭────────╮ ╭───────╮ ╭───────╮ ╭───────╮                   
 │ Apples │ │ Pears │ │ Plums │ │ Empty │                   
 ╰────────╯ ╰───────╯ ╰───────╯ ╰───────╯                   
 Apples: 0 · Pears: 2 · Plums: 1                            
 Tab moves focus, Enter adds the focused fruit, Backspace em

Apples focused, and no apple added

 ╭────────╮ ╭───────╮ ╭───────╮ ╭───────╮                   
 │ Apples │ │ Pears │ │ Plums │ │ Empty │                   
 ╰────────╯ ╰───────╯ ╰───────╯ ╰───────╯                   
 Apples: 0 · Pears: 2 · Plums: 1                            
 Tab moves focus, Enter adds the focused fruit, Backspace em

No button focused, and the basket unchanged

 ╭────────╮ ╭───────╮ ╭───────╮ ╭───────╮                   
 │ Apples │ │ Pears │ │ Plums │ │ Empty │                   
 ╰────────╯ ╰───────╯ ╰───────╯ ╰───────╯                   
 Apples: 0 · Pears: 2 · Plums: 1                            
 Tab moves focus, Enter adds the focused fruit, Backspace em

No button focused, and the basket empty

 ╭────────╮ ╭───────╮ ╭───────╮ ╭───────╮                   
 │ Apples │ │ Pears │ │ Plums │ │ Empty │                   
 ╰────────╯ ╰───────╯ ╰───────╯ ╰───────╯                   
 Apples: 0 · Pears: 0 · Plums: 0                            
 Tab moves focus, Enter adds the focused fruit, Backspace em

Tab from nothing focused focuses Apples, and the second Tab focuses Pears, which handles Enter itself, so the two Enters add two pears. A press on Plums both focuses it and adds a plum, since each runs both press handlers. A press on Apples that's released below it focuses Apples, which happens on the MouseDown, but adds no apple, since on_click acts only on a release over its element. A press beside the buttons reaches only the root's element, whose clear_focus clears focus, and a press on Empty empties the basket and clears focus too.

Composing Handlers

first tries handlers in order and stops at the first that handles the event, so the order states their precedence. In first(on_click(open_menu), drag_panel), drag_panel never sees a button 1 press, which on_click handles. each runs every handler and combines their controls, which is how two handlers that both act on a MouseDown share one element: only the element that stops a press's first MouseDown receives the rest of it, so they can't sit on an element and its parent. In the basket, on_click and focus_receiver_on_press both claim a press's MouseDown, so each runs them both, where first would run only on_click, and the press would never move focus.

counterweight.handlers.first

first(*handlers: InputHandler) -> InputHandler

A handler that calls each of handlers in turn with the same event and receiver, and returns the first response that isn't None, () included, without calling the rest. It returns None if none of them responds.

counterweight.handlers.each

each(*handlers: InputHandler) -> InputHandler

A handler that calls every one of handlers with the same event and receiver. If any responds with something other than None, it returns a tuple of every control they returned, in the order of handlers, which is () if every response was (). It returns None if none of them responds.

Headless Components

A headless component returns its behavior as a handler, on_input, for the component to put on the element it returns, composed with any others:

field = use_text_input(value, set_value)
Text(content=..., on_input=first(field.on_input, submit_on_enter, focus_receiver_on_press))

The hook's handler returns None for the keys it doesn't edit with, such as Enter and Tab, so a handler after it in first, or on an ancestor, gets them.

Clicks

on_click makes a button: it claims a press's MouseDown, so the rest of the press comes to its element, and calls its action on the press's MouseUp, if the pointer is still over the element. As on the web, a press that's dragged off a button before it's released doesn't click it, which is how a user backs out of a click they've started.

counterweight.handlers.on_click

on_click(
    action: Callable[[], InputResponse],
) -> InputHandler

A handler that claims a button 1 MouseDown, and so every later event of the press, and on the press's MouseUp, calls action if the release is over the element: inside its border box, and inside its clip, where it's painted. It returns the controls action returns, or () if action returns None. It returns None for anything else, such as a key or a pointer move with no button held.

Focus

Nothing moves focus unless a handler returns a control that does, so Tab navigation and click-to-focus are handlers an app composes in, as the basket does. focus_on_press focuses some other component, by its focus handle, as the labels of the order form focus their fields.

tab_focus moves within the element it's attached to, so on the root component's element it moves through the whole tree, and on a dialog's element it keeps Tab inside the dialog. A focused component that wants Tab for itself, such as a code editor that indents with it, handles it and returns (), so it never bubbles to tab_focus. The headless text components don't: they pass Tab on, so it moves focus out of them.

Every handler here that acts on a press claims its MouseDown, so of nested elements with press handlers, the innermost takes the press: with focus_receiver_on_press on nested focusable components, a press focuses the innermost one under the pointer. A press on a non-focusable element that claims presses, such as a button made with on_click, leaves focus where it was, unless the element composes clear_focus in too, as the basket's Empty button does.

counterweight.handlers.tab_focus

tab_focus(
    event: InputEvent, receiver: Receiver
) -> InputResponse

A handler that moves focus to the next focusable component inside its element for Tab, and to the previous one for Shift+Tab, wrapping at the ends. On the root component's element it moves through the whole tree; on a modal's, it keeps Tab inside the modal. It returns None for anything else.

counterweight.handlers.focus_receiver_on_press

focus_receiver_on_press(
    event: InputEvent, receiver: Receiver
) -> InputResponse

A handler that claims a MouseDown and focuses the component whose element received it. It goes on the element a focusable component returns, the one whose receiver carries its focus_handle. It returns None for anything else.

RAISES DESCRIPTION
ValueError

For a MouseDown whose receiver has no focus_handle, because the component never called use_focus, or the handler is on an inner element.

counterweight.handlers.focus_on_press

focus_on_press(handle: FocusHandle) -> InputHandler

A handler that claims a MouseDown and focuses the component with handle, such as a label focusing the input beside it, whatever element received the press. It returns None for anything else.

counterweight.handlers.clear_focus

clear_focus(
    event: InputEvent, receiver: Receiver
) -> InputResponse

A handler that claims a MouseDown and clears focus. On the root component's element it blurs on a press nothing below it claimed; composed into a non-focusable element's own press handler, it blurs on the presses that element claims. It returns None for anything else.

Scrolling

Nothing scrolls a scroll container unless a handler returns a control that does, so a container the wheel scrolls composes scroll_on_wheel in, and one the keyboard scrolls composes scroll_on_keys in, on a focusable component's element:

from counterweight.handlers import first, scroll_on_keys, scroll_on_wheel

use_focus()
Div(style=fill(1) | col | overflow_y_scroll, on_input=first(scroll_on_keys(), scroll_on_wheel()), children=...)

Scrolling shows them at work, and binds paging to other keys with page_down and page_up.

counterweight.handlers.scroll_on_wheel

scroll_on_wheel(lines: int = 3) -> InputHandler

A handler that scrolls the scroll container it's on by lines toward the wheel's direction for each MouseScrolledUp, MouseScrolledDown, MouseScrolledLeft and MouseScrolledRight, which is three lines by default, as desktop platforms scroll for each notch of the wheel. With Shift held, the vertical wheel scrolls sideways, as browsers on Windows and Linux do: up scrolls left and down scrolls right. It returns None for a wheel event that would move the container past the end of its range, so the event bubbles to the next scroll container out, as the web chains scrolling, and for anything else.

RAISES DESCRIPTION
ValueError

For a wheel event whose receiver isn't a scroll container.

counterweight.handlers.scroll_on_keys

scroll_on_keys(page: float = PAGE_FRACTION) -> InputHandler

A handler that scrolls the scroll container it's on for the keys that scroll a page in a browser: Up and Down by a row, Left and Right by a column, PageUp and PageDown by page times the height of the view (see page_down), and Home and End to the start and the end of the content. A key press reaches it while the container, or an element inside it, is focused, so the container is usually the top-level element of a component that calls use_focus, and a focused element inside that handles a key itself stops it first. It returns None for a key that would move the container past the end of its range, so the key bubbles to the next scroll container out, as scroll_on_wheel does with the wheel, and for anything else.

RAISES DESCRIPTION
ValueError

If page isn't positive, and for one of those keys when its receiver isn't a scroll container.

counterweight.handlers.page_down

page_down(
    target: ElementHandle | Subtree,
    scroll: Scroll,
    fraction: float = PAGE_FRACTION,
) -> ScrollBy

The ScrollBy that scrolls the scroll container target names, scrolled as scroll says, down by fraction of the height of its view, rounded down, and at least one row.

The default is Chrome's, so on a 24-row view a page is 21 rows, and 3 stay in view. fraction=0.5 is less's half page for d, and fraction=1.0 its whole page for Space, with nothing kept.

RAISES DESCRIPTION
ValueError

If fraction isn't positive.

counterweight.handlers.page_up

page_up(
    target: ElementHandle | Subtree,
    scroll: Scroll,
    fraction: float = PAGE_FRACTION,
) -> ScrollBy

The ScrollBy that scrolls the scroll container target names up by a page, as page_down scrolls it down.

RAISES DESCRIPTION
ValueError

If fraction isn't positive.