use_controls
An input handler acts on the app by returning controls,
but an effect, or a callback that a program or a timer calls, has no event to return them for.
use_controls gives a component a sender that hands the app a control from anywhere.
Here an effect scrolls a test run's first failure into view once the log has rendered,
as a React effect calls scrollIntoView on an element through a ref:
@component
def results_log(lines: tuple[str, ...] = LOG) -> Div:
first_failure, _ = use_state(ElementHandle)
send_control = use_controls()
failure_index = next((i for i, line in enumerate(lines) if line.startswith("FAIL")), None)
async def show_first_failure() -> None:
if failure_index is not None:
send_control(ScrollIntoView(first_failure, block="center"))
use_effect(show_first_failure, deps=(failure_index,))
return Div(
style=col | border | border_lightrounded | pad_x(1) | size(42, 7) | overflow_y_scroll,
on_input=scroll_on_wheel(),
children=tuple(
Text(
content=line,
style=text_color("red" if line.startswith("FAIL") else "slate", 400),
handle=first_failure if i == failure_index else None,
)
for i, line in enumerate(lines)
),
)
The log opens with its failure in the middle of the view, rather than at its start, where the failure would be out of sight.
The effect depends on failure_index, so it scrolls again only when a different line is the first failure,
and leaves the log where the reader scrolled it otherwise.
The multiplexer example
sends Quit when its last pane's shell exits,
and moves focus with FocusNext when the focused pane's shell exits.
The app handles a sent control as it handles one a handler returns, after the events already waiting,
so state set just before sending it changes the same frame the control does.
Every render returns an equal sender, so it can be left out of an effect's deps.
API
counterweight.hooks.use_controls
use_controls() -> ControlSender
Sends the app controls from outside an input handler, such as from an effect, or a callback a program or a timer calls. An input handler returns its controls instead.
| RETURNS | DESCRIPTION |
|---|---|
ControlSender
|
A sender that hands the app each control it's called with, |
ControlSender
|
which the app handles as it handles a control an input handler returns, |
ControlSender
|
after the events already waiting. |
ControlSender
|
Every render returns an equal sender, so it can be left out of an effect's |
ControlSender
|
and including it never reruns the effect. |
ControlSender
|
It keeps working after the component unmounts, so a control sent as it goes, such as |
counterweight.hooks.ControlSender
dataclass
What use_controls returns:
call it with a control to send it to the app, as send_control(Quit()).