add sidebar

This commit is contained in:
2026-10-30 14:45:55 +07:00
parent cbd307d3fd
commit b4a996e44c
6 changed files with 530 additions and 3 deletions
+369
View File
@@ -0,0 +1,369 @@
//! The sidebar: a controlled list with section headers — the Finder
//! sidebar's model of rows grouped under non-selectable labels.
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 selected row by pointer and keys.
type ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
type EntriesFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<SidebarEntry>>;
/// One entry of a [`Sidebar`], a section header or a selectable row.
#[derive(Clone)]
pub enum SidebarEntry {
/// A non-selectable section label.
Header { label: SharedString },
/// A selectable row.
Row {
label: SharedString,
icon: Option<IconRole>,
detail: Option<SharedString>,
disabled: bool,
},
}
impl SidebarEntry {
/// Creates a section header.
pub fn header<L>(label: L) -> Self
where
L: Into<SharedString>,
{
Self::Header {
label: label.into(),
}
}
/// Creates a selectable row.
pub fn row<L>(label: L) -> Self
where
L: Into<SharedString>,
{
Self::Row {
label: label.into(),
icon: None,
detail: None,
disabled: false,
}
}
/// Shows an icon leading the label.
pub fn icon(mut self, role: IconRole) -> Self {
if let Self::Row { icon, .. } = &mut self {
*icon = Some(role);
}
self
}
/// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self
where
D: Into<SharedString>,
{
if let Self::Row {
detail: row_detail, ..
} = &mut self
{
*row_detail = Some(detail.into());
}
self
}
/// Renders the row dimmed; clicks and keyboard skip it.
pub fn disabled(mut self, disabled: bool) -> Self {
if let Self::Row {
disabled: row_disabled,
..
} = &mut self
{
*row_disabled = disabled;
}
self
}
}
/// A sidebar.
#[derive(IntoElement)]
pub struct Sidebar {
id: ElementId,
selected: Option<usize>,
a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>,
entries: Option<EntriesFn>,
}
impl Sidebar {
/// Creates a sidebar 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,
entries: None,
}
}
/// Sets the current selection.
pub fn selected(mut self, selected: Option<usize>) -> Self {
self.selected = selected;
self
}
/// Reports the next selected row, 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 entries, built fresh each render.
pub fn entries<F>(mut self, entries: F) -> Self
where
F: Fn(&mut Window, &mut App) -> Vec<SidebarEntry> + 'static,
{
self.entries = Some(Box::new(entries));
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 SidebarChrome {
foreground: Hsla,
muted: Hsla,
muted_foreground: Hsla,
primary: Hsla,
primary_foreground: Hsla,
radius_sm: Pixels,
icon_size: Pixels,
text_size: Pixels,
/// The entry count, for the rows' set-size a11y attributes.
count: usize,
}
impl RenderOnce for Sidebar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let chrome = {
let theme = cx.theme();
SidebarChrome {
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: 0,
}
};
let entries = match self.entries {
Some(build) => build(window, cx),
None => Vec::new(),
};
// Headers are never selectable; only enabled rows are.
let selectable: Vec<usize> = entries
.iter()
.enumerate()
.filter(|(_, entry)| match entry {
SidebarEntry::Row { disabled, .. } => !disabled,
SidebarEntry::Header { .. } => false,
})
.map(|(index, _)| index)
.collect();
// Keyboard focus rides the container across frames.
let focus_handle = window.with_element_namespace(self.id.clone(), |window| {
window.use_keyed_state("sidebar-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 = SidebarChrome {
count: entries.len(),
..chrome
};
let children: Vec<AnyElement> = entries
.iter()
.enumerate()
.map(|(index, entry)| {
render_entry(
entry,
index,
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(children)
}
}
fn render_entry(
entry: &SidebarEntry,
index: usize,
selected: bool,
chrome: &SidebarChrome,
on_change: &Option<ChangeHandler>,
focus: &FocusHandle,
) -> AnyElement {
match entry {
SidebarEntry::Header { label } => div()
.px_2()
.pt_2()
.pb_1()
.text_sm()
.font_weight(gpui::FontWeight::MEDIUM)
.text_color(chrome.muted_foreground)
.child(label.clone())
.into_any_element(),
SidebarEntry::Row {
label,
icon: row_icon,
detail,
disabled: row_disabled,
} => {
let label_color = if *row_disabled {
chrome.muted_foreground
} else if selected {
chrome.primary_foreground
} else {
chrome.foreground
};
let mut row = div()
.id(("sidebar-row", 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 *row_disabled {
row
} else if selected {
row.bg(chrome.primary)
} else {
row.hover(|row| row.bg(chrome.muted))
}
});
if !*row_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);
}
}
});
}
row = row.when_some(*row_icon, |row, role| {
row.child(icon(role).size(chrome.icon_size).color(label_color))
});
row = row.child(div().flex_1().text_color(label_color).child(label.clone()));
if let Some(detail) = detail {
row = row.child(
div()
.flex_none()
.text_sm()
.text_color(if selected {
chrome.primary_foreground
} else {
chrome.muted_foreground
})
.child(detail.clone()),
);
}
row.into_any_element()
}
}
}
/// 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)
}
}