zgui

Scrolling

Make an element scroll, scroll to an element from code, react to scrolling, build long virtualised lists, and how wheel, trackpad and touch input scroll.

Content taller or wider than its box can scroll. zgui handles wheel, trackpad, touch and scrollbar input for you; your code decides which elements scroll, moves them from code when needed, and keeps long lists cheap.

Make an element scroll

use zgui::prelude::*;
use zgui::{component, css, view};

#[component]
fn Notes() -> impl IntoView {
    view! {
        scroll(class = "notes") {
            column(class = "notes__body") {
                text {"…a great deal of text…"}
            }
        }
    }
}

const SHEET: &str = css!(
    ".notes       { height: 240px; }
     .notes__body { padding: 12px; }"
);

A scroll container needs a bounded size, such as height: 240px here or a size given by its flex parent. Otherwise it grows to fit its content and has nothing to scroll.

The scroll element is a convenience. The framework style sheet gives it one rule:

scroll { display: block; overflow: auto; }

Any element is a scroll container when its overflow-x or overflow-y is auto or scroll. A column with overflow-y: auto scrolls. A scroll element with overflow: visible does not.

overflowClips contentScroll containerUser can scroll this axisScrollbar gutter
visiblenonononone
clipyesnononone
hiddenyesonly if the other axis is auto/scrollnonone
autoyesyesyesreserved once the content overflows
scrollyesyesyesalways reserved

Each axis is handled on its own. With overflow-x: hidden; overflow-y: auto, the wheel, trackpad and touch move only the vertical axis. Code can still move the hidden axis with scroll_to.

With overflow: auto, layout reserves a 15 CSS pixel scrollbar gutter once the content overflows, which narrows the content. The decision is kept between frames, so the gutter does not flicker while content inside changes. To avoid the sideways shift entirely, use overflow: scroll, or reserve the space with padding.

Scroll position terms

TermMeaning
scrollportthe content box the content is seen through
content extenthow far the content reaches
offsethow far the content has been moved from its start

An offset ranges from zero to content extent − scrollport on each axis. A positive offset reveals content further down and to the right. The offset belongs to the element, so it survives when the element's boxes are rebuilt, for example after a display change.

Scroll an element into view

Call scroll_to on a NodeRef to the element you want to show. Its nearest scrolling ancestor moves:

use zgui::prelude::*;
use zgui::{component, css, view};

/// `NodeRef` is `Copy` and not `Send`, so a list of these needs `LocalStorage`.
#[derive(Clone)]
struct Section {
    id: u64,
    title: String,
    node: NodeRef,
}

#[component]
fn Manual(sections: Signal<Vec<Section>, LocalStorage>) -> impl IntoView {
    view! {
        row(class = "manual") {
            column(class = "manual__index") {
                for section in move || sections.get(), key = |s: &Section| s.id {
                    control(
                        class = "manual__link",
                        on:click = move |_| section.node.scroll_to(
                            ScrollTarget::IntoViewStart,
                            ScrollBehavior::Smooth,
                        )
                    ) {
                        {section.title.clone()}
                    }
                }
            }
            scroll(class = "manual__body") {
                column {
                    for section in move || sections.get(), key = |s: &Section| s.id {
                        box(class = "manual__section", node_ref = section.node) {
                            label(class = "manual__heading") {{section.title.clone()}}
                            text {"…"}
                        }
                    }
                }
            }
        }
    }
}

const SHEET: &str = css!(
    ".manual          { height: 100%; gap: 16px; }
     .manual__index   { width: 200px; overflow-y: auto; }
     .manual__body    { flex: 1 1 auto; }
     .manual__section { padding: 24px; }"
);

section.node refers to the section, so scroll_to moves .manual__body, its nearest scrolling ancestor.

ScrollTarget, ScrollBehavior and ScrollPosition are in the prelude.

ScrollTargetEffectContainer that moves
IntoViewbrings the node into view, moving as little as possiblethe nearest scrolling ancestor
IntoViewStartaligns the node to the start of the scrollportthe nearest scrolling ancestor
IntoViewEndaligns the node to the endthe nearest scrolling ancestor
IntoViewCentercentres the nodethe nearest scrolling ancestor
Offset(Point<DevicePx, Device>)scrolls to an absolute offsetthis node, which must scroll
By(Point<DevicePx, Device>)scrolls by a relative amountthis node, which must scroll

ScrollBehavior::Instant (the default) moves in one frame. ScrollBehavior::Smooth animates over 240 ms. A node taller than the scrollport is aligned to its start by every IntoView variant.

scroll_to queues a scroll. It runs later in the same frame, against the geometry of the last completed frame. So scroll_position() read right after the call still shows the old offset, and scrolling to a node created in the same turn does nothing because it has no geometry yet. Reveal a panel in one turn and scroll to it in the next.

Scroll to an offset

ScrollTarget::Offset and ScrollTarget::By move the container itself, so call them on a NodeRef to the scroll container. Their values are in device pixels. Multiply a CSS-pixel distance by NodeRef::scale(), which returns device pixels per CSS pixel:

use zgui::geom::{DevicePx, Point};

// `port` is a NodeRef on the scroll container. Scroll down by 40 CSS pixels.
let step = 40.0 * port.scale();
port.scroll_to(ScrollTarget::By(Point::new(DevicePx(0.0), DevicePx(step))), ScrollBehavior::Smooth);

An offset past the end is clamped to the end when the scroll runs, so ScrollTarget::Offset(Point::new(DevicePx(0.0), DevicePx(f32::MAX))) scrolls to the bottom. CssPx, DevicePx, Point and Size live in zgui::geom and are not in the prelude. The units table lists which API uses which unit.

React to scrolling

on:scroll reports the new position. It does not bubble and cannot be cancelled.

scroll(
    class = "log",
    on:scroll = move |ev| pinned.set(ev.is_at_end_vertically())
) { /* … */ }
pub struct ScrollEvent {
    pub offset: Point<CssPx, Css>,
    pub content_size: Size<CssPx, Css>,
    pub scrollport: Size<CssPx, Css>,
}

A container that moved several times in one frame is reported once. The event fires after layout and before painting, so anything a handler changes is drawn in the same frame.

To read the position as a signal, use a NodeRef:

MethodReturns
scroll_offset()the offset from the last completed frame
scroll_position()offset, content extent and scrollport from the last completed frame
observe_scroll()a Signal<ScrollPosition, LocalStorage> updated every frame the container moves
observe_scroll_while(active)the same, observing only while active returns true
scroll_to(target, behavior)nothing; queues a scroll

Several observers of one container share one observation.

pub struct ScrollPosition {
    pub offset: Point<DevicePx, Device>,
    pub content_size: Size<DevicePx, Device>,
    pub scrollport: Size<DevicePx, Device>,
}

impl ScrollPosition {
    pub fn remaining(self) -> Size<DevicePx, Device>;   // never below zero
    pub fn is_at_end_vertically(self) -> bool;
    pub fn is_at_end_horizontally(self) -> bool;
}

Virtualise a long list

A list of 100 000 rows means 100 000 elements to style, lay out, paint and hit-test, but a scrollport 30 rows tall shows only 30. Virtualising builds only the visible rows and uses padding to stand in for the rest, so the scrollbar keeps the right length. Without it, the cost of every scroll frame grows with the number of boxes; on the reference machine a plain scroller exceeds a 16.6 ms frame at about 23 000 rows (see Measurements).

The component library ships one: VirtualList from zgui-ui takes a row count, a fixed row height and a row closure, and also sets the list's accessible row positions:

use zgui_ui::prelude::*;

view! {
    VirtualList(
        count = lines,
        row_size = 22.0,
        label = "Log",
        row = move |index: usize| view! { text {{move || format!("line {index}")}} }
    )
}

Build a virtual list yourself

Without zgui-ui, build the same thing from a node_ref, one observation, one derived value and a keyed for:

use zgui::prelude::*;
use zgui::{component, css, view};

/// Row height in CSS pixels. Declared, not measured.
const ROW: f32 = 24.0;

/// Extra rows built past each edge of the scrollport.
const OVERSCAN: usize = 4;

#[derive(Copy, Clone, PartialEq, Debug, Default)]
struct Visible {
    first: usize,
    count: usize,
    /// Height of the rows before the first built row, in CSS pixels.
    lead: f32,
    /// Height of the rows after the last built row, in CSS pixels.
    trail: f32,
}

impl Visible {
    fn indices(self) -> Vec<usize> {
        (self.first..self.first + self.count).collect()
    }
}

/// `port` and `offset` are in CSS pixels.
fn visible(rows: usize, port: f32, offset: f32) -> Visible {
    if rows == 0 {
        return Visible::default();
    }
    // Rounded up, plus one: a scrolled port can show part of an extra row.
    let fits = ((port.max(0.0) / ROW).ceil() as usize).max(1) + 1;
    let anchor = ((offset.max(0.0) / ROW).floor() as usize).min(rows - 1);
    let first = anchor.saturating_sub(OVERSCAN);
    let end = (anchor + fits + OVERSCAN).min(rows);
    Visible {
        first,
        count: end - first,
        lead: first as f32 * ROW,
        trail: (rows - end) as f32 * ROW,
    }
}

#[component]
fn Ledger(rows: Signal<usize>) -> impl IntoView {
    let port = NodeRef::new();
    // The observation starts when the handle binds, so asking before the element exists is fine.
    let position = port.observe_scroll();

    let seen = Signal::derive_local(move || {
        let position = position.get();
        // The observation is in device pixels; ROW is in CSS pixels.
        let scale = port.scale();
        let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
        visible(
            rows.get(),
            position.scrollport.height.0 / scale,
            position.offset.y.0 / scale,
        )
    });

    view! {
        scroll(class = "ledger", node_ref = port) {
            column(
                style:padding-top = move || Some(format!("{}px", seen.get().lead)),
                style:padding-bottom = move || Some(format!("{}px", seen.get().trail))
            ) {
                for index in move || seen.get().indices(), key = |index: &usize| *index {
                    row(class = "ledger__row") {
                        text {{move || format!("row {index}")}}
                    }
                }
            }
        }
    }
}

const SHEET: &str = css!(
    ".ledger      { height: 480px; }
     .ledger__row { height: 24px; align-items: center; padding: 0 12px; }"
);

How it works:

  1. observe_scroll() turns the container's position into a signal, updated in the frame the scroll happens.
  2. seen computes which rows to build. It reruns on every scroll, but its value changes only when the visible run changes, so scrolling within one row rebuilds nothing.
  3. padding-top and padding-bottom stand in for the rows that are not built, so the content extent equals the full list.
  4. The for is keyed by row index. Moving the run by one row removes one row and builds one; see Control flow.

On the first frame the scrollport is zero, because nothing has been laid out yet. fits is at least one row, so the list has something to measure and the next frame corrects itself.

The row height must be declared, not measured: measuring row 4 200 means building it, which is what virtualising avoids. If the style sheet disagrees with ROW, the scrollbar has the wrong length.

Keep the position when content changes

zgui does not anchor the scroll position to the content; overflow-anchor is not supported. The offset stays the same number while the content underneath it changes:

ChangeOffset
the offset is now past the end (container shrank or content shrank)clamped to the new end
the offset is still legalunchanged
the device pixel ratio changedscaled by the change

So content inserted above the visible area pushes what the user sees down by the inserted height. Two patterns handle this.

Stay at the bottom of a log

A log or chat that should stay at the bottom while the user is there:

use zgui::geom::{DevicePx, Point};
use zgui::reactive::RenderEffect;

#[derive(Clone)]
struct Line {
    id: u64,
    text: String,
}

#[component]
fn Log(lines: Signal<Vec<Line>>) -> impl IntoView {
    let port = NodeRef::new();
    // Whether the user is at the bottom. Scrolling up clears it; scrolling back sets it.
    let pinned = RwSignal::new_local(true);
    let position = port.observe_scroll();

    let following = RenderEffect::new(move |_| {
        let position = position.get();
        if pinned.get_untracked() && !position.is_at_end_vertically() {
            // Clamped to the real end when it runs.
            port.scroll_to(
                ScrollTarget::Offset(Point::new(DevicePx(0.0), DevicePx(f32::MAX))),
                ScrollBehavior::Instant,
            );
        }
    });
    on_cleanup_local(move || drop(following));

    view! {
        scroll(
            class = "log",
            node_ref = port,
            on:scroll = move |ev| pinned.set(ev.is_at_end_vertically())
        ) {
            column {
                for line in move || lines.get(), key = |line: &Line| line.id {
                    text {{line.text.clone()}}
                }
            }
        }
    }
}

The observation arrives after the layout that grew the content, and the scroll runs on the next frame. Once the log is at the end, the effect does nothing.

Insert rows above the visible area

When older rows are inserted above, scroll down by their height. With fixed row heights, use ScrollTarget::By. With unknown heights, keep a node_ref on the row that was at the top and call scroll_to(ScrollTarget::IntoViewStart, ScrollBehavior::Instant) in the turn after the insert.

Scroll with the keyboard

zgui has no built-in keyboard scrolling. Arrow keys, Page Up/Down, Home and End do nothing to a scroll container unless you handle them:

use zgui::geom::{DevicePx, Point};

let port = NodeRef::new();

view! {
    scroll(
        class = "list",
        node_ref = port,
        tabindex = Focus::Sequential,
        on:key_down = move |ev| {
            let page = port.scroll_position().scrollport.height.0;
            let line = 40.0 * port.scale();
            let step = match &ev.key {
                Key::Named(NamedKey::ArrowDown) => line,
                Key::Named(NamedKey::ArrowUp) => -line,
                Key::Named(NamedKey::PageDown) => page,
                Key::Named(NamedKey::PageUp) => -page,
                _ => return,
            };
            port.scroll_to(
                ScrollTarget::By(Point::new(DevicePx(0.0), DevicePx(step))),
                ScrollBehavior::Smooth,
            );
        }
    ) { /* rows */ }
}

scrollport.height is already in device pixels. The 40 px line is in CSS pixels, so it is multiplied by port.scale().

Use the wheel for something else

Scrolling is the default action of a wheel event. It runs after all listeners and is skipped if any listener called prevent_default. The :prevent modifier does this for you:

use zgui::geom::CssPx;

let zoom = RwSignal::new_local(1.0_f32);

view! {
    box(
        class = "map",
        on:wheel:prevent = move |ev| {
            // Nothing scrolls. The wheel zooms instead.
            let by = ev.delta.to_pixels(CssPx(16.0)).height.0;
            zoom.update(|level| *level = (*level - by * 0.001).clamp(0.25, 8.0));
        }
    ) {
        canvas(class = "map__surface")
    }
}

The end of a gesture always releases stretched edges, even if a listener prevented the default.

Stop the page scrolling behind a modal

zgui::view::current_host() returns the window's HostHandle. freeze_scrolling(true) on it stops the window's own scroll container from moving, without changing its layout, offset or gutter. Modal overlays use this. Setting overflow: hidden on the root instead would reset the offset to the top. Containers inside the page still scroll. Calls do not nest. See Overlays and portals.

Scrollbars

zgui draws scrollbars itself. They are not elements and are not in the document.

PartWhen it existsSize
trackwhenever a gutter is reservedfills the gutter
thumbonly when the content can moveproportional to the visible fraction of the content

The gutter is 15 CSS pixels wide (zgui_style::sheets::ua::SCROLLBAR_SIZE). As in CSS, it sits between the border and the padding: the bar touches the border, and the padding stays on the content's side of the bar. Bars are drawn outside the scrollport and are not clipped by it.

There is no selector for scrollbars, and scrollbar-color, scrollbar-width and scrollbar-gutter are not supported. Their look follows the scroll container's color-scheme. When it names exactly one scheme (light or dark), that scheme is used. Otherwise (normal, or light dark) the window's colour scheme is used:

PartLight schemeDark scheme
tracktransparenttransparent
thumbblack at 35 % alphawhite at 50 % alpha

Two custom properties replace these colours on a scroll container: --zgui-scrollbar-thumb and --zgui-scrollbar-track. Both inherit, so one declaration on :root themes every scrollbar.

The thumb is painted as a slim capsule, 6 device pixels thick, centred in the gutter. Its hit area still covers the full gutter width, and the invisible track still responds to presses.

A press on a scrollbar is handled before anything else. It does not move focus and does not click the container.

Press onEffect
the thumbdragging moves the thumb with the pointer, keeping the grab point under it
the trackthe container pages one screenful towards the press

Performance

A frame that only scrolls restyles nothing, relays out nothing and does not rebuild the hit index. When a scrollport has an opaque background and nothing outside the container draws over it, zgui can also reuse the pixels already drawn and paint only the strip the movement uncovered. See the Cost model for the exact conditions.

Units

WhereUnit
ScrollPosition, NodeRef::scroll_offset, ScrollTarget::Offset, ScrollTarget::Bydevice pixels
ScrollEvent (the on:scroll payload)CSS pixels
ScrollDelta::Pixels (part of the on:wheel payload)CSS pixels

On a surface with two device pixels per CSS pixel, the same position is two different numbers. NodeRef::scale() returns device pixels per CSS pixel. Divide a device-pixel value by it to get CSS pixels.

The unit is part of the type, so the compiler catches most mistakes.

How input scrolls

on:wheel delivers wheel and trackpad input. It bubbles and can be cancelled.

pub struct WheelEvent {
    pub delta: ScrollDelta,   // Lines { x, y } or Pixels(Size<CssPx, Css>)
    pub phase: ScrollPhase,   // Discrete | Started | Moved | Momentum | Ended
    pub position: Point<CssPx, Css>,
    pub id: PointerId,
    pub kind: PointerKind,
}

WheelEvent and ScrollPhase are in zgui::vocab; ScrollDelta is in the prelude.

DeviceDeltaPhase
notched mouse wheelLinesDiscrete
trackpad or other precision surfacePixelsStarted, Moved, Ended
platform momentum after the fingers lift (macOS)PixelsMomentum

Distance per wheel notch

QuestionAnswered by
lines per notchthe desktop, through ScrollSettings::lines_per_notch (3 on Linux, Windows and macOS)
has the user's direction preference been appliedthe desktop, through ScrollSettings::direction
how tall one line isthe scrolled container's computed text style

A page is scrollport − one line, and never less than one line. Use ScrollDelta::to_pixels to convert a delta yourself:

use zgui::geom::CssPx;

let delta = ScrollDelta::Lines { x: 0.0, y: -3.0 };
assert_eq!(delta.to_pixels(CssPx(16.0)).height, CssPx(-48.0));

A whole wheel notch on X11, Wayland or Windows glides to its destination over 240 ms with a cubic ease-out. A new notch extends the destination of the running glide, so three fast notches travel three times as far as one. Trackpad and touch input, and wheels on platforms that animate the wheel themselves (macOS), are applied in the frame they arrive.

Nested containers

A wheel notch acts on the chain of scroll containers from the element under the pointer up to the root. Each container takes as much as it has room for and passes the rest outwards. If an inner list has 40 px left and the notch asks for 100 px, the list moves 40 px and the page moves 60 px.

The axes are handled separately. A sideways flick over a vertical list scrolls the page sideways. The chain follows the element tree, so a display: contents wrapper does not break it.

Trackpad gestures

A trackpad gesture behaves as it does in AppKit and in browsers:

  • It latches to one container. The first movement picks the innermost container that can move in that direction. The gesture moves only that container until the fingers lift, even if the pointer leaves it. If a list reaches its end mid-gesture, the list stretches and the page around it stays still.
  • It rails to one axis. A gesture that starts clearly along one axis (at least twice as much movement on it as on the other) ignores the other axis until it ends.
  • The finger holds the stretch. While the fingers are down, a stretched edge stays where the finger put it. Moving back first undoes the stretch, then scrolls. When the fingers lift, the edge springs back.
  • Momentum bounces. When platform momentum carries the container to an end, the edge travels past it at the gesture's speed, returns, and the rest of the momentum is dropped. If an edge was still stretched when the fingers lifted, the momentum that follows is dropped.

Touch

A finger dragging a container scrolls it.

GestureEffect
pan startsthe scroll chain is chosen where the finger went down and kept for the whole drag
pan movesthe content follows the finger
pan endsthe container keeps the finger's speed and decelerates

Only one drag runs at a time. A second contact that starts panning takes over.

Elastic edges

Scroll input that no container can absorb can stretch an edge past its end. The edge springs back when the input stops. Which input may stretch is a desktop setting, ScrollSettings::elastic:

ElasticStretches on
Kinetic (default on every backend)trackpad gestures and touch; a mouse wheel stops at the end
Alwaysevery input, including a wheel
Nevernothing
  • Only an axis that a container actually scrolls can stretch. Content that fits its scrollport does not move.
  • For wheel input, the outermost container in the chain that scrolls on that axis stretches. A trackpad gesture stretches the container it latched to.
  • The stretch follows an AppKit-style rubber band, measured against the scrollport's size. The first pixels move at about half the finger's speed, later ones less. No pull moves the content a full scrollport.
  • The return is an exponential decay. An edge released 100 device pixels out is back within 2 pixels after about 0.3 seconds, at any frame rate.

The stretch is not part of the offset. scroll_offset, the thumb, observations and on:scroll all report the clamped position, snapped to the device pixel grid, while an edge is stretched. Only painting adds the stretch, unsnapped, so an edge returning from overscroll moves smoothly.

Next

On this page