add list
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "gpui-native-data"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Data-heavy GPUI components: lists, trees, tabs, sidebars — one cargo feature each"
|
||||
|
||||
[dependencies]
|
||||
gpui = { workspace = true }
|
||||
gpui-native-icons = { workspace = true }
|
||||
gpui-native-theme = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
|
||||
[features]
|
||||
default = ["full"]
|
||||
full = ["list"]
|
||||
list = []
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Data-heavy components: lists, trees, tabs, sidebars — one cargo feature
|
||||
//! each, painted from the theme global like `gpui-native-core`.
|
||||
|
||||
#[cfg(feature = "list")]
|
||||
pub mod list;
|
||||
@@ -0,0 +1,316 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::prelude::FluentBuilder as _;
|
||||
use gpui::{
|
||||
AnyElement, App, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
|
||||
KeyDownEvent, ParentElement as _, Pixels, RenderOnce, Role, SharedString,
|
||||
StatefulInteractiveElement as _, Styled as _, Window, div,
|
||||
};
|
||||
use gpui_native_icons::{IconRole, icon};
|
||||
use gpui_native_theme::ActiveTheme as _;
|
||||
|
||||
/// The change reporter, fired with the next selection by pointer and keys.
|
||||
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
|
||||
type ItemsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<ListItem>>;
|
||||
|
||||
/// One row of a [`List`].
|
||||
pub struct ListItem {
|
||||
label: SharedString,
|
||||
icon: Option<IconRole>,
|
||||
detail: Option<SharedString>,
|
||||
disabled: bool,
|
||||
}
|
||||
|
||||
impl ListItem {
|
||||
/// Creates a row with this label.
|
||||
pub fn new<L>(label: L) -> Self
|
||||
where
|
||||
L: Into<SharedString>,
|
||||
{
|
||||
Self {
|
||||
label: label.into(),
|
||||
icon: None,
|
||||
detail: None,
|
||||
disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows an icon leading the label.
|
||||
pub fn icon(mut self, role: IconRole) -> Self {
|
||||
self.icon = Some(role);
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows muted trailing text.
|
||||
pub fn detail<D>(mut self, detail: D) -> Self
|
||||
where
|
||||
D: Into<SharedString>,
|
||||
{
|
||||
self.detail = Some(detail.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Renders the row dimmed; clicks and keyboard skip it.
|
||||
pub fn disabled(mut self, disabled: bool) -> Self {
|
||||
self.disabled = disabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-selection list.
|
||||
#[derive(IntoElement)]
|
||||
pub struct List {
|
||||
id: ElementId,
|
||||
selected: Option<usize>,
|
||||
a11y_label: Option<SharedString>,
|
||||
on_change: Option<ChangeHandler>,
|
||||
items: Option<ItemsFn>,
|
||||
}
|
||||
|
||||
impl List {
|
||||
/// Creates a list with nothing selected.
|
||||
pub fn new<I>(id: I) -> Self
|
||||
where
|
||||
I: Into<ElementId>,
|
||||
{
|
||||
Self {
|
||||
id: id.into(),
|
||||
selected: None,
|
||||
a11y_label: None,
|
||||
on_change: None,
|
||||
items: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the current selection.
|
||||
pub fn selected(mut self, selected: Option<usize>) -> Self {
|
||||
self.selected = selected;
|
||||
self
|
||||
}
|
||||
|
||||
/// Reports the next selection, from clicks and keys alike.
|
||||
pub fn on_change<F>(mut self, handler: F) -> Self
|
||||
where
|
||||
F: Fn(Option<usize>, &mut Window, &mut App) + 'static,
|
||||
{
|
||||
self.on_change = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the rows, built fresh each render.
|
||||
pub fn items<F>(mut self, items: F) -> Self
|
||||
where
|
||||
F: Fn(&mut Window, &mut App) -> Vec<ListItem> + 'static,
|
||||
{
|
||||
self.items = Some(Box::new(items));
|
||||
self
|
||||
}
|
||||
|
||||
/// Overrides the accessibility label, which defaults to the id.
|
||||
pub fn accessibility_label<L>(mut self, label: L) -> Self
|
||||
where
|
||||
L: Into<SharedString>,
|
||||
{
|
||||
self.a11y_label = Some(label.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct ListChrome {
|
||||
foreground: Hsla,
|
||||
muted: Hsla,
|
||||
muted_foreground: Hsla,
|
||||
primary: Hsla,
|
||||
primary_foreground: Hsla,
|
||||
radius_sm: Pixels,
|
||||
icon_size: Pixels,
|
||||
text_size: Pixels,
|
||||
/// The row count, for the rows' set-size a11y attributes.
|
||||
count: usize,
|
||||
}
|
||||
|
||||
impl RenderOnce for List {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let items = match self.items {
|
||||
Some(build) => build(window, cx),
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
let selectable: Vec<usize> = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, item)| !item.disabled)
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
|
||||
let focus_handle = window.with_element_namespace(self.id.clone(), |window| {
|
||||
window.use_keyed_state("list-focus", cx, |_, cx| cx.focus_handle())
|
||||
});
|
||||
let focus = focus_handle.read(cx).clone();
|
||||
|
||||
let label = self
|
||||
.a11y_label
|
||||
.clone()
|
||||
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
|
||||
|
||||
let chrome = {
|
||||
let theme = cx.theme();
|
||||
ListChrome {
|
||||
foreground: theme.colors.foreground,
|
||||
muted: theme.colors.muted,
|
||||
muted_foreground: theme.colors.muted_foreground,
|
||||
primary: theme.ramps.primary.base,
|
||||
primary_foreground: theme.colors.primary_foreground,
|
||||
radius_sm: theme.radius.sm,
|
||||
icon_size: theme.sizes.medium.icon_size,
|
||||
text_size: theme.sizes.medium.text_size,
|
||||
count: items.len(),
|
||||
}
|
||||
};
|
||||
|
||||
let rows: Vec<AnyElement> = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, item)| {
|
||||
render_row(
|
||||
index,
|
||||
item,
|
||||
self.selected == Some(index),
|
||||
&chrome,
|
||||
&self.on_change,
|
||||
&focus,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
div()
|
||||
.id(self.id)
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_0p5()
|
||||
.text_size(chrome.text_size)
|
||||
.track_focus(&focus)
|
||||
.focusable()
|
||||
.tab_stop(true)
|
||||
.role(Role::List)
|
||||
.aria_label(label)
|
||||
.on_key_down({
|
||||
let selected = self.selected;
|
||||
let on_change = self.on_change.clone();
|
||||
|
||||
move |event: &KeyDownEvent, window, cx| {
|
||||
let target = match event.keystroke.key.as_str() {
|
||||
"down" => adjacent(&selectable, selected, true),
|
||||
"up" => adjacent(&selectable, selected, false),
|
||||
"home" => selectable.first().copied(),
|
||||
"end" => selectable.last().copied(),
|
||||
_ => return,
|
||||
};
|
||||
if let Some(next) = target
|
||||
&& Some(next) != selected
|
||||
&& let Some(on_change) = &on_change
|
||||
{
|
||||
on_change(Some(next), window, cx);
|
||||
}
|
||||
cx.stop_propagation();
|
||||
}
|
||||
})
|
||||
.children(rows)
|
||||
}
|
||||
}
|
||||
|
||||
fn render_row(
|
||||
index: usize,
|
||||
item: &ListItem,
|
||||
selected: bool,
|
||||
chrome: &ListChrome,
|
||||
on_change: &Option<ChangeHandler>,
|
||||
focus: &FocusHandle,
|
||||
) -> AnyElement {
|
||||
let label_color = row_color(item, selected, chrome);
|
||||
let disabled = item.disabled;
|
||||
|
||||
div()
|
||||
.id(("list-item", index))
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_2()
|
||||
.px_2()
|
||||
.py_1()
|
||||
.rounded(chrome.radius_sm)
|
||||
.role(Role::ListItem)
|
||||
.aria_selected(selected)
|
||||
.aria_position_in_set(index + 1)
|
||||
.aria_size_of_set(chrome.count)
|
||||
.map(|row| {
|
||||
if disabled {
|
||||
row
|
||||
} else if selected {
|
||||
row.bg(chrome.primary)
|
||||
} else {
|
||||
row.hover(|row| row.bg(chrome.muted))
|
||||
}
|
||||
})
|
||||
.when(!disabled, |row| {
|
||||
row.cursor_pointer().on_click({
|
||||
let on_change = on_change.clone();
|
||||
let focus = focus.clone();
|
||||
move |_, window, cx| {
|
||||
window.focus(&focus, cx);
|
||||
if let Some(on_change) = &on_change {
|
||||
on_change(Some(index), window, cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
.when_some(item.icon, |row, role| {
|
||||
row.child(icon(role).size(chrome.icon_size).color(label_color))
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.text_color(label_color)
|
||||
.child(item.label.clone()),
|
||||
)
|
||||
.when_some(item.detail.clone(), |row, detail| {
|
||||
row.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.text_sm()
|
||||
.text_color(if selected {
|
||||
chrome.primary_foreground
|
||||
} else {
|
||||
chrome.muted_foreground
|
||||
})
|
||||
.child(detail),
|
||||
)
|
||||
})
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
/// The row's label/icon color.
|
||||
fn row_color(item: &ListItem, selected: bool, chrome: &ListChrome) -> Hsla {
|
||||
if item.disabled {
|
||||
chrome.muted_foreground
|
||||
} else if selected {
|
||||
chrome.primary_foreground
|
||||
} else {
|
||||
chrome.foreground
|
||||
}
|
||||
}
|
||||
|
||||
/// The next selectable row in the direction.
|
||||
fn adjacent(selectable: &[usize], selected: Option<usize>, forward: bool) -> Option<usize> {
|
||||
if forward {
|
||||
selectable
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|index| Some(*index) > selected)
|
||||
} else {
|
||||
selectable
|
||||
.iter()
|
||||
.copied()
|
||||
.rev()
|
||||
.find(|index| Some(*index) < selected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use gpui::{
|
||||
Context, IntoElement, Modifiers, MouseButton, ParentElement as _, Render, Styled as _,
|
||||
TestAppContext, VisualTestContext, Window, WindowHandle, div, point, px,
|
||||
};
|
||||
use gpui_native_data::list::{List, ListItem};
|
||||
use gpui_native_theme::Theme;
|
||||
|
||||
struct Harness {
|
||||
selected: Option<usize>,
|
||||
changes: Rc<RefCell<Vec<Option<usize>>>>,
|
||||
}
|
||||
|
||||
impl Render for Harness {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let changes = self.changes.clone();
|
||||
let view = cx.entity();
|
||||
div().size_full().child(
|
||||
List::new("test-list")
|
||||
.selected(self.selected)
|
||||
.on_change(move |next, _, cx| {
|
||||
changes.borrow_mut().push(next);
|
||||
view.update(cx, |harness, cx| {
|
||||
harness.selected = next;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.items(|_, _| {
|
||||
vec![
|
||||
ListItem::new("One"),
|
||||
ListItem::new("Two"),
|
||||
ListItem::new("Unavailable").disabled(true),
|
||||
ListItem::new("Three"),
|
||||
]
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type Changes = Rc<RefCell<Vec<Option<usize>>>>;
|
||||
|
||||
type ListWindow = (
|
||||
TestAppContext,
|
||||
VisualTestContext,
|
||||
WindowHandle<Harness>,
|
||||
Changes,
|
||||
);
|
||||
|
||||
/// Rows paint at the top-left with no outer padding: one row per ~34 px band
|
||||
/// (16 px text line + 2×4 px padding + 2 px gap), so clicks at `(50, 16/48/80/112)`
|
||||
/// land on One / Two / the disabled Unavailable / Three.
|
||||
fn list_window(selected: Option<usize>) -> ListWindow {
|
||||
let mut cx = TestAppContext::single();
|
||||
cx.update(Theme::init);
|
||||
let changes = Rc::new(RefCell::new(Vec::new()));
|
||||
let harness_changes = changes.clone();
|
||||
let window = cx.add_window(move |_, _| Harness {
|
||||
selected,
|
||||
changes: harness_changes,
|
||||
});
|
||||
let mut visual = VisualTestContext::from_window(window.into(), &cx);
|
||||
visual.update(|window, cx| {
|
||||
window.draw(cx).clear(cx);
|
||||
});
|
||||
(cx, visual, window, changes)
|
||||
}
|
||||
|
||||
fn draw(visual: &mut VisualTestContext) {
|
||||
visual.update(|window, cx| {
|
||||
window.draw(cx).clear(cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn click(visual: &mut VisualTestContext, position: gpui::Point<gpui::Pixels>) {
|
||||
visual.simulate_mouse_down(position, MouseButton::Left, Modifiers::default());
|
||||
visual.simulate_mouse_up(position, MouseButton::Left, Modifiers::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_row_selects_it_and_hands_the_list_the_keyboard() {
|
||||
let (_cx, mut visual, _window, changes) = list_window(None);
|
||||
|
||||
click(&mut visual, point(px(50.), px(16.)));
|
||||
assert_eq!(*changes.borrow(), vec![Some(0)]);
|
||||
|
||||
// The click focused the list, so the arrows navigate from here.
|
||||
visual.simulate_keystrokes("down");
|
||||
draw(&mut visual);
|
||||
assert_eq!(*changes.borrow(), vec![Some(0), Some(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_a_disabled_row_reports_nothing() {
|
||||
let (_cx, mut visual, _window, changes) = list_window(None);
|
||||
|
||||
click(&mut visual, point(px(50.), px(80.)));
|
||||
draw(&mut visual);
|
||||
assert_eq!(*changes.borrow(), Vec::<Option<usize>>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_navigation_skips_disabled_rows_and_never_wraps() {
|
||||
let (_cx, mut visual, _window, changes) = list_window(None);
|
||||
|
||||
click(&mut visual, point(px(50.), px(16.)));
|
||||
visual.simulate_keystrokes("down"); // over the disabled row → Two
|
||||
visual.simulate_keystrokes("down"); // over the disabled row → Three
|
||||
visual.simulate_keystrokes("down"); // last selectable; no wrap
|
||||
draw(&mut visual);
|
||||
assert_eq!(*changes.borrow(), vec![Some(0), Some(1), Some(3)]);
|
||||
|
||||
visual.simulate_keystrokes("home");
|
||||
visual.simulate_keystrokes("end");
|
||||
visual.simulate_keystrokes("up"); // over the disabled row → Two
|
||||
draw(&mut visual);
|
||||
assert_eq!(
|
||||
*changes.borrow(),
|
||||
vec![Some(0), Some(1), Some(3), Some(0), Some(3), Some(1)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_down_with_no_selection_picks_the_first_selectable_row() {
|
||||
let (mut cx, mut visual, window, changes) = list_window(Some(1));
|
||||
|
||||
// Focus the list, then clear the selection app-side.
|
||||
click(&mut visual, point(px(50.), px(48.)));
|
||||
window
|
||||
.update(&mut cx, |harness, _, cx| {
|
||||
harness.selected = None;
|
||||
cx.notify();
|
||||
})
|
||||
.unwrap();
|
||||
draw(&mut visual);
|
||||
|
||||
visual.simulate_keystrokes("down");
|
||||
draw(&mut visual);
|
||||
assert_eq!(*changes.borrow(), vec![Some(1), Some(0)]);
|
||||
}
|
||||
Reference in New Issue
Block a user