A scrolling region with thin, draggable overlay scrollbars.
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::scroll_area::{ScrollArea, ScrollAxis};
use crate::ui::separator::Separator;
const ARTISTS: [&str; 5] = ["Ornella Binni", "Tom Byrom", "Vladimir Malyavko", "Ana Lima", "Kai Ito"];
pub fn scroll_area_demo(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let (border, muted, muted_fg) = (theme.border, theme.muted, theme.muted_foreground);
let tags = ScrollArea::new("tags")
.h(px(288.0))
.w(px(192.0))
.rounded(px(6.0))
.border_1()
.border_color(border)
.child(
div()
.p_4()
.child(div().mb_4().text_sm().font_weight(FontWeight::MEDIUM).child("Tags"))
.children((1..=50).rev().map(|n| {
div()
.child(div().text_sm().child(format!("v1.2.0-beta.{n}")))
.child(div().my_2().child(Separator::horizontal()))
})),
);
let artwork = ScrollArea::new("artwork")
.axis(ScrollAxis::Horizontal)
.w(px(384.0))
.rounded(px(6.0))
.border_1()
.border_color(border)
.child(
div().flex().gap_4().p_4().children(ARTISTS.iter().map(|artist| {
div()
.flex_none()
.flex()
.flex_col()
.gap_2()
.child(div().w(px(150.0)).h(px(200.0)).rounded(px(6.0)).bg(muted))
.child(
div()
.flex()
.gap_1()
.text_xs()
.text_color(muted_fg)
.child("Photo by")
.child(div().font_weight(FontWeight::SEMIBOLD).text_color(theme.foreground).child(*artist)),
)
})),
);
div().flex().items_center().gap_8().child(tags).child(artwork)
}Installation
Copies src/ui/scroll_area.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/scroll_area.rs.src/ui/scroll_area.rs use std::{sync::Arc, time::Duration}; use gpui::{ div, prelude::*, px, Along, AnimationExt, AnyElement, App, Axis, Bounds, ElementId, EmptyView, Entity, MouseButton, Pixels, Point, Refineable, ScrollHandle, SpringAnimation, SpringConfig, StyleRefinement, Task, Window, }; use crate::theme::ActiveTheme; /// Bar thickness, like shadcn's `w-2.5`. const BAR: Pixels = px(10.0); /// Gap between the bar's edge and its thumb, like shadcn's `p-px`. const PAD: Pixels = px(1.0); /// Radix keeps the thumb grabbable however long the content gets. const MIN_THUMB: Pixels = px(18.0); /// Radix's `scrollHideDelay`: how long the bars stay after the pointer leaves or scrolling stops. const HIDE_DELAY: Duration = Duration::from_millis(600); /// Fades the bars in and out over ~150ms. Critically damped (damping = 2 * sqrt(stiffness)), /// so a quick re-entry turns the fade around without flicker. const FADE_SPRING: SpringConfig = SpringConfig::new(900.0, 60.0, 1.0); /// Which directions the area scrolls in. #[derive(Clone, Copy, Default, PartialEq)] pub enum ScrollAxis { #[default] Vertical, Horizontal, Both, } impl ScrollAxis { fn has(self, axis: Axis) -> bool { match self { ScrollAxis::Vertical => axis == Axis::Vertical, ScrollAxis::Horizontal => axis == Axis::Horizontal, ScrollAxis::Both => true, } } } /// A scrolling region with thin overlay scrollbars in place of the platform ones. Like Radix's /// default `type="hover"`, the bars fade in while the pointer is over the area or it scrolls, /// and fade out shortly after. /// Size it like any div: `ScrollArea::new("tags").h(px(288.0)).w(px(192.0))`. #[derive(IntoElement)] pub struct ScrollArea { id: ElementId, axis: ScrollAxis, handle: Option<ScrollHandle>, style: StyleRefinement, children: Vec<AnyElement>, } /// The scroll position is pointer state the app has no reason to own (Radix's ScrollArea is /// uncontrolled too), and GPUI writes it into a `ScrollHandle` during layout, so the handle /// lives here. The viewport and overflow are kept from the last frame because they are only /// known after layout, and the thumb is drawn from them. struct ScrollAreaState { handle: ScrollHandle, viewport: Bounds<Pixels>, max: Point<Pixels>, /// Where on the thumb the pointer went down, so the thumb doesn't jump under it. grab: Pixels, hovered: bool, /// The offset last rendered, to notice scrolling, which shows the bars too. last_offset: Point<Pixels>, /// True from the last scroll or pointer exit until `HIDE_DELAY` has passed. lingering: bool, /// Clears `lingering`; replacing it cancels the previous countdown. hide: Option<Task<()>>, } /// Keeps the bars up for `HIDE_DELAY`, restarting the countdown if one is running. fn linger(state: &Entity<ScrollAreaState>, cx: &mut App) { let weak = state.downgrade(); let hide = cx.spawn(async move |cx| { cx.background_executor().timer(HIDE_DELAY).await; weak.update(cx, |state, cx| { state.lingering = false; state.hide = None; cx.notify(); }) .ok(); }); state.update(cx, |state, _| { state.lingering = true; state.hide = Some(hide); }); } /// Drag payload. `on_drag_move` fires for every listener of this type, so the id and axis /// keep one bar's drag from moving another. struct ThumbDrag(ElementId, Axis); /// Thumb length and offset along the track, in pixels from the track's start. fn thumb_geometry(viewport: Pixels, max: Pixels, offset: Pixels) -> (Pixels, Pixels) { let track = viewport - PAD * 2.0; let length = (track * (viewport / (viewport + max))).max(MIN_THUMB).min(track); let fraction = if max > px(0.0) { (-offset / max).clamp(0.0, 1.0) } else { 0.0 }; (length, (track - length) * fraction) } impl ScrollArea { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), axis: ScrollAxis::default(), handle: None, style: StyleRefinement::default(), children: Vec::new(), } } pub fn axis(mut self, axis: ScrollAxis) -> Self { self.axis = axis; self } /// Scrolls with your own handle, so you can read the offset or call `scroll_to_bottom()`. /// Pass the same handle every frame: the area adopts it the first time it renders. pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self { self.handle = Some(handle.clone()); self } } impl Styled for ScrollArea { fn style(&mut self) -> &mut StyleRefinement { &mut self.style } } impl ParentElement for ScrollArea { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for ScrollArea { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let own_handle = self.handle; let state = window.use_keyed_state(self.id.clone(), cx, |_, _| ScrollAreaState { handle: own_handle.unwrap_or_else(ScrollHandle::new), viewport: Bounds::default(), max: Point::default(), grab: px(0.0), hovered: false, last_offset: Point::default(), lingering: false, hide: None, }); let (handle, viewport, max, last_offset) = { let state = state.read(cx); (state.handle.clone(), state.viewport, state.max, state.last_offset) }; let offset = handle.offset(); if offset != last_offset { state.update(cx, |state, _| state.last_offset = offset); linger(&state, cx); } // A drag that leaves the area keeps the bars up until it ends. let visible = { let state = state.read(cx); state.hovered || state.lingering || cx.has_active_drag() }; let child_id = |name: &str| ElementId::NamedChild(Arc::new(self.id.clone()), name.into()); let thumb_color = cx.theme().border; let axis = self.axis; let both = axis == ScrollAxis::Both && max.x > px(0.0) && max.y > px(0.0); let bar = |scroll_axis: Axis| { let overflow = max.along(scroll_axis); if !axis.has(scroll_axis) || overflow <= px(0.0) { return None; } let (length, start) = thumb_geometry(viewport.size.along(scroll_axis), overflow, offset.along(scroll_axis)); let id = self.id.clone(); let drag_id = self.id.clone(); let down_state = state.clone(); let move_state = state.clone(); let thumb_start = viewport.origin.along(scroll_axis) + PAD + start; let thumb = div() .id(match scroll_axis { Axis::Vertical => "scroll-thumb-y", Axis::Horizontal => "scroll-thumb-x", }) .absolute() .rounded_full() .bg(thumb_color) .map(|this| match scroll_axis { Axis::Vertical => this.left(PAD).right(PAD).top(PAD + start).h(length), Axis::Horizontal => this.top(PAD).bottom(PAD).left(PAD + start).w(length), }) .on_mouse_down(MouseButton::Left, move |event, _, cx| { let grab = event.position.along(scroll_axis) - thumb_start; down_state.update(cx, |state, _| state.grab = grab); }) .on_drag(ThumbDrag(drag_id, scroll_axis), |_, _, _, cx| cx.new(|_| EmptyView)); Some( div() .absolute() .map(|this| match scroll_axis { // When both bars show, each stops short of the shared corner. Axis::Vertical => this .top_0() .right_0() .w(BAR) .when(both, |this| this.bottom(BAR)) .when(!both, |this| this.bottom_0()), Axis::Horizontal => this .left_0() .bottom_0() .h(BAR) .when(both, |this| this.right(BAR)) .when(!both, |this| this.right_0()), }) .on_drag_move::<ThumbDrag>(move |event, _, cx| { let ThumbDrag(drag_id, drag_axis) = event.drag(cx); if *drag_id != id || *drag_axis != scroll_axis { return; } move_state.update(cx, |state, cx| { let size = state.viewport.size.along(scroll_axis); let overflow = state.max.along(scroll_axis); let (length, _) = thumb_geometry(size, overflow, px(0.0)); let travel = size - PAD * 2.0 - length; let along = event.event.position.along(scroll_axis) - event.bounds.origin.along(scroll_axis) - PAD - state.grab; let fraction = if travel > px(0.0) { (along / travel).clamp(0.0, 1.0) } else { 0.0 }; let current = state.handle.offset(); let next = current.apply_along(scroll_axis, |_| -(overflow * fraction)); if next != current { state.handle.set_offset(next); cx.notify(); } }); }) .child(thumb) // A freshly mounted spring starts at its target, so the bars start hidden. .with_spring( child_id(match scroll_axis { Axis::Vertical => "bar-y", Axis::Horizontal => "bar-x", }), SpringAnimation::new(FADE_SPRING).to(visible), |this, phase| this.opacity(phase.interpolate_clamped(0.0, 1.0)), ), ) }; let vertical = bar(Axis::Vertical); let horizontal = bar(Axis::Horizontal); let viewport_div = div() .id(self.id.clone()) .size_full() .track_scroll(&handle) .flex() .map(|this| match axis { ScrollAxis::Vertical => this.flex_col().overflow_y_scroll(), ScrollAxis::Horizontal => this.overflow_x_scroll(), ScrollAxis::Both => this.items_start().overflow_scroll(), }) // A non-shrinking wrapper takes its content's natural size along the scrolling // axes, which is what GPUI measures the overflow from (Radix wraps content too). .child(div().flex_none().children(self.children)); let hover_state = state.clone(); let mut root = div().relative().overflow_hidden(); root.style().refine(&self.style); root.on_children_prepainted(move |bounds, _, cx| { state.update(cx, |state, cx| { let viewport = bounds.first().copied().unwrap_or_default(); let max = state.handle.max_offset(); if state.viewport != viewport || state.max != max { state.viewport = viewport; state.max = max; cx.notify(); } }); }) .id(child_id("root")) .on_hover(move |hovered, _, cx| { hover_state.update(cx, |state, cx| { state.hovered = *hovered; cx.notify(); }); if !*hovered { linger(&hover_state, cx); } }) .child(viewport_div) .children(vertical) .children(horizontal) } }Register the module
// src/ui/mod.rs pub mod scroll_area;
Usage
use crate::ui::scroll_area::*;API Reference
ScrollAxis
Which directions the area scrolls in.
ScrollAxis::VerticalScrollAxis::HorizontalScrollAxis::BothScrollArea
A scrolling region with thin overlay scrollbars in place of the platform ones. Like Radix's default type="hover", the bars fade in while the pointer is over the area or it scrolls, and fade out shortly after. Size it like any div: ScrollArea::new("tags").h(px(288.0)).w(px(192.0)).
ScrollArea::new(id: impl Into<ElementId>) -> Self.axis(axis: ScrollAxis).track_scroll(handle: &ScrollHandle)Scrolls with your own handle, so you can read the offset or call scroll_to_bottom(). Pass the same handle every frame: the area adopts it the first time it renders.