Scrolling
A box whose overflow is Scroll is a scroll container:
its content can be larger than it, and it shows the part its offset scrolls into view.
This page covers making one, scrolling it with the wheel, the keyboard and from handlers,
scrolling an element into view, and reading how far it's scrolled.
Clipping covers how a scroll container cuts off what's outside its padding box,
which it does as a box with hidden overflow does.
Scroll areas
Most scrolling boxes want the same things:
the wheel and the keys scroll them, Tab and a click focus them, as browsers make a scroll container focusable,
and a style that scrolls even beside a constraint utility that hides overflow.
use_scroll_area gives a component all of those, and leaves drawing it to the component,
and scroll_area is a bordered box built on it:
SOURCE = (
"def deploy(image: str, steps: tuple[int, ...] = (10, 50, 100)) -> None:",
" for percent in steps:",
" shift_traffic(image, percent)",
)
@component
def panes() -> Div:
return Div(
style=row | gap(1),
on_input=tab_focus,
children=(
scroll_area(
tuple(Text(content=event) for event in EVENTS),
style=size(24, 6),
auto_focus=True,
),
scroll_area(
tuple(Text(content=line) for line in SOURCE),
axis="x",
style=size(24, 6),
),
),
)
The rest of this page covers the pieces they're built from, for a box that needs something they don't do.
Scroll containers
overflow_scroll makes a box a scroll container on both axes,
and overflow_x_scroll and overflow_y_scroll on one,
as CSS's overflow: scroll does.
On an axis it scrolls, the box clips its children to its padding box,
and moves them up and left by its offset.
Counterweight holds each scroll container's offset, as a browser holds an element's scrollTop,
so a box scrolls without any state in the component that renders it.
It starts at 0, the start of the content.
After every layout, it moves to keep the content in view where it was
(see Keeping the content in view),
and is clamped to how far the content reaches,
so when the content shrinks, the box scrolls back as far as it has to.
A scroll container that unmounts or is hidden loses its offset, and starts at 0 again when it comes back.
How far a box can scroll is how far its content reaches past its padding box, as on the web. That includes its absolutely positioned descendants, so a dropdown that opens past the bottom of a scrolling form lets the form scroll down to show it (see the autocomplete recipe).
A scroll container's automatic minimum size is 0, as one with hidden overflow's is
(see Content sets a minimum size),
so a flex item that scrolls shrinks to fit beside its siblings instead of growing to fit its content.
That's usually what a scrolling pane wants;
give it a size, or shrink(0), when it should be as large as its content up to some limit.
A Text doesn't scroll its own text, nor a Canvas what it draws,
so either one whose overflow is Scroll raises ValueError:
put a long Text or a large Canvas in a Div that scrolls.
Scrolling with the wheel
Nothing scrolls unless a handler scrolls it, as with every other input,
so a scroll container that the wheel should scroll composes
scroll_on_wheel into its on_input.
A titled pane puts its border and title on a box around the part that scrolls,
so they stay put while the content moves:
@component
def pane() -> Div:
return Div(
style=col | border | border_lightrounded | size(30, 6),
children=(
Text(content=" Deploy log ", style=position_absolute | inset_top(-1) | inset_left(1) | clip_to_border),
Div(
style=fill(1) | col | overflow_y_scroll,
on_input=scroll_on_wheel(),
children=tuple(Text(content=f"{i:>2} {event}") for i, event in enumerate(EVENTS, start=1)),
),
),
)
A wheel event goes to the element under the pointer and bubbles from there,
so of nested scroll containers, the innermost under the pointer scrolls.
scroll_on_wheel lets an event that would move its container past either end of its range bubble on,
so once the inner one reaches its end, the wheel scrolls the one around it,
as the web chains scrolling from one container to the next.
With Shift held, scroll_on_wheel scrolls sideways for the vertical wheel, as browsers on Windows and Linux do,
so a mouse without a sideways wheel can scroll a container that only scrolls sideways, such as a wide code block.
The wheel event still says which way the wheel turned and that Shift was held,
as Firefox's does, rather than reporting a sideways turn, as Chrome's does,
so a handler before scroll_on_wheel can give Shift with the wheel a meaning of its own.
Some terminals keep Shift with the wheel for their own scrollback and never report it,
so a sideways wheel or a trackpad's sideways swipe is the only way to scroll sideways there.
Scrolling with the keyboard
scroll_on_keys scrolls for the keys that scroll a page in a browser:
the arrow keys by a row or a column, PageUp and PageDown by a page, and Home and End to the start and the end.
A key press goes to the focused element and bubbles from there,
so a container the keys scroll is usually a focusable component's top-level element,
and the keys scroll it while it, or anything inside it, is focused.
Like scroll_on_wheel, it lets a key that would move its container past either end of its range bubble on,
to the next container out.
A page is 87.5% of the height of the view, rounded down, as in Chrome,
so the last lines of one page stay in view at the top of the next, to read on from.
page_down and page_up return the ScrollBy for a page of any size,
for apps that bind paging to other keys, such as less's Space for a whole page and d and u for half of one:
def less_keys(event: InputEvent, receiver: Receiver) -> InputResponse:
# Receiver.scroll is None only off a scroll container, and this handler is only on one.
if receiver.scroll is None:
return None
match event:
case KeyPressed(key=" "):
return page_down(receiver.subtree, receiver.scroll, fraction=1.0)
case KeyPressed(key="d"):
return page_down(receiver.subtree, receiver.scroll, fraction=0.5)
case KeyPressed(key="u"):
return page_up(receiver.subtree, receiver.scroll, fraction=0.5)
case _:
return None
@component
def pager() -> Div:
focus = use_focus(auto_focus=True)
return Div(
style=col
| border
| border_lightrounded
| size(30, 8)
| overflow_y_scroll
| (border_color("sky", 400) if focus.is_focused else border_color("slate", 600)),
on_input=first(less_keys, scroll_on_keys(), scroll_on_wheel()),
children=tuple(Text(content=f"{i:>2} {EVENTS[i % len(EVENTS)]}") for i in range(30)),
)
less_keys comes first, so its keys win over any scroll_on_keys binds,
and anything it doesn't handle falls through to the others.
Scrolling from a handler
The ScrollTo and ScrollBy controls scroll a container
to an offset, or by an amount, clamped to its range.
A handler on the scroll container itself names it by its receiver's subtree, as scroll_on_wheel does.
A handler anywhere else names it by an element handle, an ElementHandle,
as a React component reaches a DOM node through a ref:
create one with use_state(ElementHandle), and pass it to the element's handle.
@component
def controlled() -> Div:
log, _ = use_state(ElementHandle)
return Div(
style=col | gap(1),
children=(
Div(
style=row | gap(2),
children=(
Text(content="[ Top ]", on_input=on_click(lambda: ScrollTo(log, y=0))),
Text(content="[ Bottom ]", on_input=on_click(lambda: ScrollTo(log, y=len(EVENTS)))),
),
),
Div(
style=col | border | border_lightrounded | size(30, 5) | overflow_y_scroll,
handle=log,
children=tuple(Text(content=f"{i:>2} {event}") for i, event in enumerate(EVENTS, start=1)),
),
),
)
Two mounted elements given the same element handle raise DuplicateElementHandle,
and a control whose handle names no mounted scroll container does nothing.
Scroll controls apply to the layout of the render after the handler that returns them, before that render paints,
in the order they were returned,
and after anchoring and sticking to the end have placed the content,
so each moves the view from where those left it.
So a handler that adds a line to a log and returns ScrollBy(log, y=1) beside the state change
scrolls by a row of the log that has the new line, in the same frame.
That's where Counterweight differs from the web:
a browser's scrollBy scrolls the page as it stands while the handler runs,
before React renders the state change, and a React app that wants to scroll the content that change lays out
calls it from useLayoutEffect instead, which is what scroll controls do.
A handler that runs later in the same batch of input sees the controls returned before it:
its receiver's scroll is moved by each ScrollTo and ScrollBy since the last render,
clamped to the range as of that render,
so scroll_on_keys passes a key on once an earlier key has scrolled its container to the end.
Scrolling an element into view
ScrollIntoView scrolls to an element rather than to an offset,
as the web's scrollIntoView does:
it scrolls each scroll container above the element, from the innermost out, until the element is in view.
Its block says where the element goes vertically: "start", the default, puts its top at the top of the view,
"center" in the middle, "end" at the bottom,
and "nearest" scrolls as little as it takes, and not at all if the element is already in view.
inline says the same horizontally, and is "nearest" by default.
It stops at an element with clip_to_screen,
since no container above that element clips it, so none has to scroll to show it.
A table of contents scrolls each section's heading to the top of the pane it's in:
SECTIONS = (
("Install", "Add counterweight to your project with uv."),
("Components", "A component is a function that returns an element."),
("Hooks", "Hooks keep state and run effects for a component."),
("Styles", "Styles are merged from small utilities with |."),
)
@component
def contents() -> Div:
headings, _ = use_state(lambda: tuple(ElementHandle() for _ in SECTIONS))
return Div(
style=row | size(40, 6),
children=(
Div(
style=col | width(14) | border_right | border_lightrounded | pad_x(1),
children=tuple(
Text(
content=title,
style=text_color("sky", 300),
on_input=on_click(partial(ScrollIntoView, heading)),
)
for (title, _), heading in zip(SECTIONS, headings, strict=True)
),
),
Div(
style=fill(1) | col | gap(1) | pad_x(1) | overflow_y_scroll,
on_input=scroll_on_wheel(1),
children=tuple(
Div(
style=col,
children=(
Text(content=title, style=text_color("amber", 400), handle=heading),
Text(content=body, style=text_wrap_pretty),
),
)
for (title, body), heading in zip(SECTIONS, headings, strict=True)
),
),
),
)
Like the other scroll controls, it applies to the layout of the render after the handler that returns it,
as React's useLayoutEffect would call scrollIntoView after the DOM updates and before the browser paints.
So a handler that changes state and returns ScrollIntoView beside it shows both in the same frame,
and the handle names the element that has it in that render, not the one before.
A list that moves a highlight with Down puts one element handle on whichever item is highlighted,
and returns ScrollIntoView(handle, block="nearest") beside the state change that moves it:
the handle has moved to the new item by the time the control applies
(see A long list in Pickers).
use_text_area does the same for its cursor:
it returns a cursor_row element handle for the element the cursor's row is drawn in,
and its handler returns ScrollIntoView for it with block="nearest" beside each edit,
so a text area in a scroll container keeps the cursor in view as it moves between rows.
Moving focus scrolls the newly focused element into view with block="nearest",
as browsers do, so Tab never leaves focus on something out of sight.
That includes a component that takes focus with auto_focus as it mounts.
ScrollIntoView scrolls in one step.
The web's behavior: "smooth" animates the scroll across frames,
which Counterweight has no design for yet: a fixed number of frames and a fixed duration are both plausible.
Reading the scroll
use_scroll returns a Scroll: how far the calling component's top-level element is scrolled,
how far it can be, and the size of its padding box, the part of the content in view.
Given an ElementHandle, it reports on the element with that handle instead,
as a React component reads another element's scrollTop through a ref
(see Jumping to the end).
A handler's Receiver carries the same for a receiving element that's
a scroll container, which is how scroll_on_wheel knows whether its container can move any further.
Like use_rects, use_scroll reports the scroll as of the last layout,
and a component that calls it renders again as soon as it changes, before the frame is painted.
A list too long to render whole can render only the rows in view, with empty boxes above and below them
so the content is as tall as every row would make it, as React's windowing libraries do:
ROWS = 100_000
@component
def windowed_row(i: int) -> Text:
return Text(content=f"row {i:,} of {ROWS:,}")
@component
def windowed() -> Div:
scroll = use_scroll()
# Render the rows in view, with a screen's worth of rows on each side
# so a scroll shows rows, not blank space, before this re-renders,
# and an empty box above and below for the rest, so the content is as tall as every row.
overscan = scroll.view_height
first = max(0, scroll.offset.y - overscan)
last = min(ROWS, scroll.offset.y + scroll.view_height + overscan)
return Div(
style=col | border | border_lightrounded | size(30, 6) | overflow_y_scroll,
on_input=scroll_on_wheel(),
children=(
Div(style=height(first) | shrink(0)),
# Keyed, so a row keeps its node as the window moves, and scroll anchoring follows the row.
*(windowed_row(i).with_key(str(i)) for i in range(first, last)),
Div(style=height(ROWS - last) | shrink(0)),
),
)
The rows on each side of the view cover the frame between a scroll and the render that follows it, which would otherwise show the empty boxes. The rows are keyed components, so each keeps its place as the window moves (see Keeping the content in view).
Keeping the content in view
When content changes above what's in view, an offset that stayed put would show different content: a message dropped from the top of a transcript would pull everything up by its height. So a scroll container keeps what's in view where it is, as browsers do with scroll anchoring. Before each layout, it picks an anchor: the first node in view, or, for a node only partly in view, the first of its descendants in view. After the layout, it moves its offset so the anchor's top edge is as far from the top of the view as it was. Content that changes below the anchor, or inside it, doesn't move the view; content that changes above it moves the view with it.
These two feeds show the same alerts, newest first, and a new one arrives at the top every two seconds.
The wheel scrolls both together, a row a notch.
The left one anchors, as every scroll container does unless told otherwise;
the right one has overflow_anchor_none, so its offset stays where it was:
ALERTS = (
"disk 91% on db-2",
"p99 latency 840ms",
"pod web-7 restarted",
"cert expiring",
"queue depth 12k",
)
@component
def alert(number: int) -> Text:
return Text(content=f"{number:>2} {ALERTS[number % len(ALERTS)]}")
@component
def alert_feed(title: str, viewport: ElementHandle, anchor: Style, newest: int) -> Div:
return Div(
style=col | border | border_lightrounded | size(26, 6),
children=(
Text(content=f" {title} ", style=position_absolute | inset_top(-1) | inset_left(1) | clip_to_border),
Div(
style=fill(1) | col | overflow_y_scroll | anchor,
handle=viewport,
# Newest first, keyed, so each alert keeps its node, which anchoring follows, as new ones arrive above.
children=tuple(alert(n).with_key(str(n)) for n in range(newest, 0, -1)),
),
),
)
@component
def anchoring() -> Div:
feeds, _ = use_state(lambda: (ElementHandle(), ElementHandle()))
tick = use_clock(timedelta(seconds=2))
# A new alert every two seconds, at the top.
newest = 8 + int(tick.since_mount / timedelta(seconds=2))
def scroll_both(event: InputEvent, receiver: Receiver) -> InputResponse:
match event:
case MouseScrolledDown() | MouseScrolledUp():
return tuple(ScrollBy(feed, y=event.direction) for feed in feeds)
case _:
return None
anchored, unanchored = feeds
return Div(
style=row | gap(1),
on_input=scroll_both,
children=(
alert_feed("Anchored", anchored, overflow_anchor_auto, newest),
alert_feed("overflow_anchor_none", unanchored, overflow_anchor_none, newest),
),
)
While they're scrolled to the top, new alerts push the rest down in both, since a container at the top doesn't anchor. Once they're scrolled down, the anchored feed keeps showing the alerts it was showing, with the new ones arriving out of view above, while the other's offset stays put, so each new alert pushes what it shows down a row. Scrolling the anchored feed back up reaches the new ones:
The anchor is a node, so it follows what each node shows from one render to the next. Siblings without keys continue the sibling at the same index, so when items drop off the front of an unkeyed list, every node shows the item after the one it did, and the view lurches forward by however far that moved the anchor. Give each item of a list whose front changes its own key, as React asks of a list (see When position isn't identity).
As on the web:
- A container scrolled to the top doesn't anchor, so content added above the top pushes the rest down into view.
- Anchoring moves only the vertical offset.
overflow_anchor_noneturns it off: on a scroll container, its offset only gets clamped, and on an element inside one, neither it nor anything inside it is picked as the anchor. An element withclip_to_screenis never picked either.- A container whose anchor unmounted or was hidden only clamps its offset.
Following the end
A log or a transcript should stay scrolled to its end as lines arrive, so the newest is always in view,
until the reader scrolls back to read something earlier.
stick_to_end_y does that: a container that's scrolled to its end before a layout is scrolled to its end after it,
and one that isn't is anchored as usual.
stick_to_end_x does the same horizontally, stick_to_end on both axes, and unstick turns it off.
A container whose content fits is at its end, so a log that starts short follows its end from its first line,
and one that mounts already overflowing starts at its end.
This log keeps its newest eight lines, adds one a second, and sticks to its end:
KEPT_LINES = 8
@component
def request_line(number: int) -> Text:
return Text(content=f"{number:>3} GET /items/{number} 200")
@component
def tail() -> Div:
tick = use_clock(timedelta(seconds=1))
# A line a second, keeping the newest few.
newest = 4 + int(tick.since_mount.total_seconds())
return Div(
style=col | border | border_lightrounded | size(30, 6) | overflow_y_scroll | stick_to_end_y,
on_input=scroll_on_wheel(1),
# Keyed, so a line keeps its node, which anchoring follows, as older lines drop off the top.
children=tuple(request_line(n).with_key(str(n)) for n in range(max(0, newest - KEPT_LINES), newest)),
)
Scrolled back two lines, it stays where the reader left it as new lines arrive below and old ones drop off above:
Scrolling back down to the end makes it follow the end again. The web has no property for this: a page puts an anchor element after the content, or reverses a column so it starts at its end. The chat composer keeps its messages scrolled to the newest this way.
Here it is following, scrolled back, and following again:
Jumping to the end
Counterweight doesn't draw scrollbars (#417), as most terminal apps don't, so a reader scrolled back through a log has no sign of how far the end is. A button over the last line that appears once the log is scrolled back, and jumps to the end, gives them one:
@component
def jump_to_end() -> Div:
log, _ = use_state(ElementHandle)
scroll = use_scroll(log)
return Div(
style=col | border | border_lightrounded | size(30, 6),
children=(
Div(
style=fill(1) | col | overflow_y_scroll | stick_to_end_y,
handle=log,
on_input=scroll_on_wheel(1),
children=tuple(Text(content=f"{i:>2} {event}") for i, event in enumerate(EVENTS, start=1)),
),
# A sibling of the log, not a child, so it stays over the last line as the log scrolls.
*(
()
if scroll.offset.y == scroll.max_offset.y
else (
Text(
content=" ↓ Jump to end ",
style=position_absolute
| inset_bottom(0)
| inset_x(0)
| margin_x_auto
| fit_content_width
| text_bg("sky", 800),
on_input=on_click(lambda: ScrollTo(log, y=scroll.max_offset.y)),
),
)
),
),
)
Scrolling back, then clicking the button:
The button is a sibling of the log in a box around it, not a child of the log,
because a scroll container moves everything inside it by its offset, absolutely positioned elements included,
so a button inside the log would scroll away with the lines.
Being outside the log, it reads the log's scroll with use_scroll(log).
It renders again as soon as the log scrolls, before the frame is painted,
so the button appears in the frame that scrolls the log back.
A wheel event over the button goes to the box around the log, not the log, so the wheel doesn't scroll it there.
use_scroll_area puts its handler on the box around the part that scrolls,
so its is_at_end and to_end make the same button from inside the component,
and the wheel scrolls the log from over the button too.
Where scrolled boxes are
Scrolling moves boxes, so everything that reports where a box is reports where it's painted:
use_rects, a receiver's rects, the element the mouse is over,
and use_hovered.
A box scrolled partly out of view is still whole there, with its visible region the part in view,
as for any box that's clipped.
API
counterweight.focus.ElementHandle
dataclass
An opaque token that names one element, as a React ref names a DOM node:
a scroll container for ScrollTo, ScrollBy
and use_scroll, or an element to bring into view with
ScrollIntoView,
such as the cursor's row a text area draws with its cursor_row.
It's an identity token, equal only to itself, so it can exist before the element it names has mounted:
a component creates one with use_state(ElementHandle) and passes it to an element's handle.
Two mounted elements given the same handle raise DuplicateElementHandle.
__repr__
__repr__() -> str
Names the handle by its identity, since that's all that tells two handles apart.
counterweight.focus.DuplicateElementHandle
Raised when two mounted elements are given the same ElementHandle, which leaves it naming neither.