add scrollarea

This commit is contained in:
2026-10-29 19:23:06 +07:00
parent 4ae6a23cd9
commit cc22baca6e
12 changed files with 388 additions and 10 deletions
+2 -1
View File
@@ -27,7 +27,7 @@ full = [
"avatar",
"input",
"popover",
"tooltip",
"scroll_area",
"menu",
"dialog",
"sheet",
@@ -44,6 +44,7 @@ progress = []
avatar = []
input = []
popover = []
scroll_area = []
tooltip = []
menu = []
dialog = []
+3
View File
@@ -39,6 +39,9 @@ pub mod input;
#[cfg(feature = "popover")]
pub mod popover;
#[cfg(feature = "scroll_area")]
pub mod scroll_area;
/// Initializes everything the components need at startup.
pub fn init(cx: &mut App) {
gpui_native_theme::Theme::init(cx);
+223
View File
@@ -0,0 +1,223 @@
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, MouseDownEvent,
MouseMoveEvent, ParentElement, Pixels, Refineable as _, RenderOnce, ScrollHandle, SharedString,
StatefulInteractiveElement as _, Styled, Window, canvas, div, fill, point,
};
use gpui_native_theme::ActiveTheme as _;
/// Which directions the content scrolls in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScrollAxes {
/// Vertical only; the default.
#[default]
Vertical,
/// Horizontal only.
Horizontal,
/// Both directions.
Both,
}
/// A scrollable container with an overlay scrollbar.
#[derive(IntoElement)]
pub struct ScrollArea {
id: ElementId,
handle: Option<ScrollHandle>,
axes: ScrollAxes,
a11y_label: Option<SharedString>,
style: gpui::StyleRefinement,
children: Vec<gpui::AnyElement>,
}
impl ParentElement for ScrollArea {
fn extend(&mut self, children: impl IntoIterator<Item = gpui::AnyElement>) {
self.children.extend(children);
}
}
impl Styled for ScrollArea {
fn style(&mut self) -> &mut gpui::StyleRefinement {
&mut self.style
}
}
impl ScrollArea {
/// Creates a vertically scrolling area.
pub fn new<I>(id: I) -> Self
where
I: Into<ElementId>,
{
Self {
id: id.into(),
handle: None,
axes: ScrollAxes::Vertical,
a11y_label: None,
style: gpui::StyleRefinement::default(),
children: Vec::new(),
}
}
/// Sets which directions the content scrolls in.
pub fn axes(mut self, axes: ScrollAxes) -> Self {
self.axes = axes;
self
}
/// Scrolls with a handle held on the owning view.
pub fn handle(mut self, handle: ScrollHandle) -> Self {
self.handle = Some(handle);
self
}
/// Overrides the accessibility label of the container.
pub fn accessibility_label<L>(mut self, label: L) -> Self
where
L: Into<SharedString>,
{
self.a11y_label = Some(label.into());
self
}
}
/// Pure thumb geometry for an overlay scrollbar.
pub(crate) fn thumb_geometry(
viewport: Pixels,
content: Pixels,
offset: Pixels,
track: Pixels,
min_thumb: Pixels,
) -> (Pixels, Pixels) {
if content <= viewport || content <= Pixels::ZERO {
return (track, Pixels::ZERO);
}
let length = (viewport / content * track).max(min_thumb).min(track);
let overflow = content - viewport;
let progress = (-offset / overflow).clamp(0., 1.);
let travel = track - length;
(length, travel * progress)
}
impl RenderOnce for ScrollArea {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let mut pane = div()
.id(self.id.clone())
.overflow_hidden()
.when(self.axes != ScrollAxes::Horizontal, |area| {
area.overflow_y_scroll()
})
.when(self.axes != ScrollAxes::Vertical, |area| {
area.overflow_x_scroll()
})
.when_some(self.handle.clone(), |area, handle| {
area.track_scroll(&handle)
})
.when_some(self.a11y_label, |area, label| area.aria_label(label))
.on_scroll(|_, _, cx| {
// Keep wheel events from scrolling an outer scroll area too.
cx.stop_propagation();
});
pane.style().refine(&self.style);
pane.extend(self.children);
let mut wrapper = div().relative();
wrapper.extend(std::iter::once(pane.into_any_element()));
if let Some(handle) = self.handle {
wrapper.extend(std::iter::once(
canvas(|_, _, _| {}, {
let handle = handle.clone();
move |_, _, window, cx| {
paint_scrollbar(&handle, window, cx);
}
})
.absolute()
.inset_0()
.into_any_element(),
));
}
wrapper
}
}
/// Paints the overlay scrollbar thumb.
fn paint_scrollbar(handle: &ScrollHandle, window: &mut Window, cx: &mut App) {
let theme = cx.theme();
let color = theme.colors.scrollbar_thumb;
let width = theme.scrollbar.width;
let inset = theme.scrollbar.inset;
let min_thumb = theme.scrollbar.min_thumb;
let max_offset = handle.max_offset().y;
let bounds = handle.bounds();
if max_offset <= Pixels::ZERO || bounds.size.height <= Pixels::ZERO {
return;
}
let track = bounds.size.height - inset * 2.0;
let (thumb_length, thumb_top) = thumb_geometry(
bounds.size.height,
bounds.size.height + max_offset,
handle.offset().y,
track,
min_thumb,
);
let thumb_x = bounds.right() - width - inset;
let thumb_bounds = Bounds::from_corners(
point(thumb_x, bounds.top() + inset + thumb_top),
point(
thumb_x + width,
bounds.top() + inset + thumb_top + thumb_length,
),
);
window.paint_quad(fill(thumb_bounds, color).corner_radii(width / 2.0));
let drag = window.use_keyed_state("scrollbar-thumb-drag", cx, |_, _| {
Option::<(Pixels, Pixels)>::None
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
move |event: &MouseDownEvent, phase, _window, cx| {
if phase != DispatchPhase::Bubble
|| event.button != gpui::MouseButton::Left
|| !thumb_bounds.contains(&event.position)
{
return;
}
drag.update(cx, |drag, _| {
*drag = Some((event.position.y, handle.offset().y));
});
cx.stop_propagation();
}
});
window.on_mouse_event({
let handle = handle.clone();
let drag = drag.clone();
move |event: &MouseMoveEvent, phase, _window, cx| {
if phase != DispatchPhase::Bubble
|| event.pressed_button != Some(gpui::MouseButton::Left)
{
return;
}
let Some((start_y, start_offset)) = *drag.read(cx) else {
return;
};
if max_offset > Pixels::ZERO && track > thumb_length {
let scale = max_offset / (track - thumb_length);
let offset = (start_offset - (event.position.y - start_y) * scale)
.clamp(-max_offset, Pixels::ZERO);
handle.set_offset(point(handle.offset().x, offset));
}
}
});
}
+96
View File
@@ -0,0 +1,96 @@
use gpui::{
Context, IntoElement, Modifiers, ParentElement as _, Render, ScrollDelta, ScrollEvent,
ScrollHandle, SharedString, Styled as _, TestAppContext, VisualTestContext, Window, div, point,
px,
};
use gpui_native_core::scroll_area::ScrollArea;
use gpui_native_theme::Theme;
struct Harness {
scroll: ScrollHandle,
rows: usize,
}
impl Render for Harness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
ScrollArea::new("test-scroll")
.handle(self.scroll.clone())
.h(px(200.))
.w(px(300.))
.child(div().flex().flex_col().children((0..self.rows).map(|row| {
div()
.h(px(20.))
.child(SharedString::from(format!("row {row}")))
}))),
)
}
}
/// A 300×200 scroll area over `rows` 20px rows, with the handle the test
/// can inspect directly.
fn scroll_area_window(rows: usize) -> (TestAppContext, VisualTestContext, ScrollHandle) {
let mut cx = TestAppContext::single();
cx.update(Theme::init);
let handle = ScrollHandle::new();
let handle_for_view = handle.clone();
let window = cx.add_window(move |_, _| Harness {
scroll: handle_for_view,
rows,
});
let mut visual = VisualTestContext::from_window(window.into(), &cx);
visual.update(|window, cx| {
window.draw(cx).clear(cx);
});
(cx, visual, handle)
}
#[test]
fn wheel_scrolling_moves_the_offset_and_stays_inside_the_content() {
let (_cx, mut visual, handle) = scroll_area_window(30);
// 30 rows × 20px = 600px of content in a 200px viewport.
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-60.))),
modifiers: Modifiers::default(),
..Default::default()
});
let offset = handle.offset().y;
assert_eq!(offset, px(-60.));
// Wheeling far past the end clamps to the content.
for _ in 0..10 {
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(0.), px(-60.))),
modifiers: Modifiers::default(),
..Default::default()
});
}
// max_offset = 600 - 200 = 400.
assert_eq!(handle.offset().y, px(-400.));
}
#[test]
fn the_content_starts_unscrolled_and_horizontal_axes_scroll_x() {
let (_cx, mut visual, handle) = scroll_area_window(30);
assert_eq!(handle.offset(), gpui::point(px(0.), px(0.)));
// A vertical-only area ignores horizontal wheel deltas.
visual.simulate_event(ScrollEvent {
position: point(px(100.), px(100.)),
delta: ScrollDelta::Pixels(point(px(-60.), px(0.))),
modifiers: Modifiers::default(),
..Default::default()
});
assert_eq!(handle.offset().x, px(0.));
}
#[test]
fn the_thumb_paints_when_the_content_overflows() {
let (_cx, _visual, handle) = scroll_area_window(30);
// 30 rows × 20px in a 200px viewport: the thumb has something to report.
assert!(handle.max_offset().y > px(0.));
}