sidebar: replace header/footer/content slots with custom entries

This commit is contained in:
2026-11-15 20:43:05 +07:00
parent fd6a8c0342
commit 0fda22caf7
2 changed files with 173 additions and 218 deletions
+140 -174
View File
@@ -1,7 +1,6 @@
//! The sidebar: a controlled list with section headers — the Finder //! The sidebar: a controlled list with section headers — the Finder
//! sidebar's model of rows grouped under non-selectable labels. Custom content //! sidebar's model of rows grouped under non-selectable labels. Custom
//! replaces the list and takes the whole container, sliding under a pinned //! entries slot user content between the rows.
//! strip; the header and footer slots apply only to the entry list.
use std::rc::Rc; use std::rc::Rc;
@@ -13,14 +12,14 @@ use gpui::{
}; };
use gpui_native_core::grain::grain as grain_overlay; use gpui_native_core::grain::grain as grain_overlay;
use gpui_native_core::scroll_area::ScrollArea; use gpui_native_core::scroll_area::ScrollArea;
use gpui_native_theme::{ActiveTheme as _, TextRole, Typeset as _}; use gpui_native_theme::{ActiveTheme as _, BORDER_WIDTH, TextRole, Typeset as _};
use gpui_native_utils::{nav_key, paint_selectable_row, selectable_label_color}; use gpui_native_utils::{nav_key, paint_selectable_row, selectable_label_color};
/// The change reporter, fired with the next selected row by pointer and keys. /// 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 ChangeHandler = Rc<dyn Fn(Option<usize>, &mut Window, &mut App)>;
type EntriesFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<SidebarEntry>>; type EntriesFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<SidebarEntry>>;
/// One entry of a [`Sidebar`], a section header or a selectable row. /// One entry of a [`Sidebar`], a section header, a selectable row, or custom content.
#[must_use] #[must_use]
pub enum SidebarEntry { pub enum SidebarEntry {
/// A non-selectable section label. /// A non-selectable section label.
@@ -38,6 +37,8 @@ pub enum SidebarEntry {
suffix: Option<AnyElement>, suffix: Option<AnyElement>,
disabled: bool, disabled: bool,
}, },
/// Custom content occupying a slot in the list.
Custom(AnyElement),
} }
impl SidebarEntry { impl SidebarEntry {
@@ -69,6 +70,14 @@ impl SidebarEntry {
} }
} }
/// Wraps custom content occupying a slot in the list.
pub fn custom<E>(element: E) -> Self
where
E: IntoElement,
{
Self::Custom(element.into_any_element())
}
/// Shows muted trailing text. /// Shows muted trailing text.
pub fn detail<D>(mut self, detail: D) -> Self pub fn detail<D>(mut self, detail: D) -> Self
where where
@@ -88,10 +97,9 @@ impl SidebarEntry {
where where
E: IntoElement, E: IntoElement,
{ {
let slot = match &mut self { if let Self::Row { prefix: slot, .. } | Self::Header { prefix: slot, .. } = &mut self {
Self::Row { prefix: slot, .. } | Self::Header { prefix: slot, .. } => slot, *slot = Some(prefix.into_any_element());
}; }
*slot = Some(prefix.into_any_element());
self self
} }
@@ -100,10 +108,9 @@ impl SidebarEntry {
where where
E: IntoElement, E: IntoElement,
{ {
let slot = match &mut self { if let Self::Row { suffix: slot, .. } | Self::Header { suffix: slot, .. } = &mut self {
Self::Row { suffix: slot, .. } | Self::Header { suffix: slot, .. } => slot, *slot = Some(suffix.into_any_element());
}; }
*slot = Some(suffix.into_any_element());
self self
} }
@@ -131,13 +138,11 @@ pub struct Sidebar {
selected: Option<usize>, selected: Option<usize>,
transparent: bool, transparent: bool,
grain: bool, grain: bool,
border_right: bool,
padded: bool,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>, on_change: Option<ChangeHandler>,
entries: Option<EntriesFn>, entries: Option<EntriesFn>,
header: Option<AnyElement>,
content: Option<AnyElement>,
footer: Option<AnyElement>,
strip: Option<AnyElement>,
} }
impl Sidebar { impl Sidebar {
@@ -151,13 +156,11 @@ impl Sidebar {
selected: None, selected: None,
transparent: false, transparent: false,
grain: false, grain: false,
border_right: true,
padded: true,
a11y_label: None, a11y_label: None,
on_change: None, on_change: None,
entries: None, entries: None,
header: None,
content: None,
footer: None,
strip: None,
} }
} }
@@ -185,6 +188,28 @@ impl Sidebar {
self self
} }
/// Paints a hairline border on the sidebar's right edge.
pub fn border_right(mut self, border_right: bool) -> Self {
self.border_right = border_right;
self
}
/// Whether the right-edge border is painted.
pub fn has_border_right(&self) -> bool {
self.border_right
}
/// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge.
pub fn padded(mut self, padded: bool) -> Self {
self.padded = padded;
self
}
/// Whether the entry list is inset from the sidebar's edges.
pub fn is_padded(&self) -> bool {
self.padded
}
/// Reports the next selected row, from clicks and keys alike. /// Reports the next selected row, from clicks and keys alike.
pub fn on_change<F>(mut self, handler: F) -> Self pub fn on_change<F>(mut self, handler: F) -> Self
where where
@@ -203,42 +228,6 @@ impl Sidebar {
self self
} }
/// Pins an element above the list, ignored when content is set.
pub fn header<E>(mut self, header: E) -> Self
where
E: IntoElement,
{
self.header = Some(header.into_any_element());
self
}
/// Replaces the list with custom content spanning the whole container.
pub fn content<E>(mut self, content: E) -> Self
where
E: IntoElement,
{
self.content = Some(content.into_any_element());
self
}
/// Pins an element below the list, ignored when content is set.
pub fn footer<E>(mut self, footer: E) -> Self
where
E: IntoElement,
{
self.footer = Some(footer.into_any_element());
self
}
/// Pins a titlebar strip at the sidebar's top, custom content renders behind it.
pub fn strip<E>(mut self, strip: E) -> Self
where
E: IntoElement,
{
self.strip = Some(strip.into_any_element());
self
}
/// Overrides the accessibility label, which defaults to the id. /// Overrides the accessibility label, which defaults to the id.
pub fn accessibility_label<L>(mut self, label: L) -> Self pub fn accessibility_label<L>(mut self, label: L) -> Self
where where
@@ -256,135 +245,113 @@ impl RenderOnce for Sidebar {
selected, selected,
transparent: material, transparent: material,
grain, grain,
border_right,
padded,
a11y_label, a11y_label,
on_change, on_change,
entries, entries,
header,
content,
footer,
strip,
} = self; } = self;
let custom = content.is_some();
let (header, footer) = if custom {
(None, None)
} else {
(header, footer)
};
let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string())); let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string()));
let debug_id = id.clone(); let debug_id = id.clone();
let body = match content { let entries = match entries {
Some(content) => div() Some(build) => build(window, cx),
.flex_1() None => Vec::new(),
.min_h_0() };
.overflow_hidden()
.child(content) // Headers and custom entries are never selectable, only enabled rows are.
.into_any_element(), let selectable: Vec<usize> = entries
None => { .iter()
let entries = match entries { .enumerate()
Some(build) => build(window, cx), .filter(|(_, entry)| match entry {
None => Vec::new(), SidebarEntry::Row { disabled, .. } => !disabled,
SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false,
})
.map(|(index, _)| index)
.collect();
let focus = gpui_native_utils::focus_handle(&id, window, cx);
let scroll = window.with_element_namespace(id.clone(), |window| {
window
.use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new())
.clone()
});
let scroll_area_id = (id.clone(), "entries");
let row_count = entries
.iter()
.filter(|entry| matches!(entry, SidebarEntry::Row { .. }))
.count();
let mut row_position = 0usize;
let children: Vec<AnyElement> = entries
.into_iter()
.enumerate()
.map(|(index, entry)| {
let is_row = matches!(entry, SidebarEntry::Row { .. });
if is_row {
row_position += 1;
}
let (position_in_set, size_of_set) = if is_row {
(row_position, row_count)
} else {
(0, 0)
}; };
// Headers are never selectable, only enabled rows are. entry.render_entry(
let selectable: Vec<usize> = entries cx,
.iter() index,
.enumerate() position_in_set,
.filter(|(_, entry)| match entry { size_of_set,
SidebarEntry::Row { disabled, .. } => !disabled, selected == Some(index),
SidebarEntry::Header { .. } => false, material,
}) &on_change,
.map(|(index, _)| index) &focus,
.collect(); )
})
.collect();
let focus = gpui_native_utils::focus_handle(&id, window, cx); let body = div()
let scroll = window.with_element_namespace(id.clone(), |window| { .id((id.clone(), "list"))
window .flex_1()
.use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) .min_h_0()
.clone() .track_focus(&focus)
}); .focusable()
let scroll_area_id = (id.clone(), "entries"); .tab_stop(true)
.role(Role::List)
let row_count = entries .aria_label(label)
.iter() .on_key_down({
.filter(|entry| matches!(entry, SidebarEntry::Row { .. })) let on_change = on_change.clone();
.count(); move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
let mut row_position = 0usize; if let Some(on_change) = &on_change {
let children: Vec<AnyElement> = entries on_change(next, window, cx);
.into_iter()
.enumerate()
.map(|(index, entry)| {
let is_row = matches!(entry, SidebarEntry::Row { .. });
if is_row {
row_position += 1;
} }
}) {
let (position_in_set, size_of_set) = if is_row { cx.stop_propagation();
(row_position, row_count) }
} else { }
(0, 0) })
}; .child(
ScrollArea::new(scroll_area_id)
entry.render_entry( .handle(scroll.read(cx).clone())
cx, .h_full()
index,
position_in_set,
size_of_set,
selected == Some(index),
material,
&on_change,
&focus,
)
})
.collect();
div()
.id((id.clone(), "list"))
.flex_1()
.min_h_0()
.track_focus(&focus)
.focusable()
.tab_stop(true)
.role(Role::List)
.aria_label(label.clone())
.on_key_down({
let on_change = on_change.clone();
move |event: &KeyDownEvent, window, cx| {
if nav_key(&selectable, selected, &event.keystroke.key, |next| {
if let Some(on_change) = &on_change {
on_change(next, window, cx);
}
}) {
cx.stop_propagation();
}
}
})
.child( .child(
ScrollArea::new(scroll_area_id) div()
.handle(scroll.read(cx).clone()) .flex()
.h_full() .flex_col()
.gap_0p5() .gap_0p5()
.when(padded, |content| content.px_2().py_1())
.children(children), .children(children),
) ),
.into_any_element() )
} .into_any_element();
};
let theme = cx.theme(); let theme = cx.theme();
let (leading_strip, overlay_strip) = match strip {
Some(strip) if custom => (
None,
Some(div().absolute().top_0().left_0().right_0().child(strip)),
),
Some(strip) => (Some(strip), None),
None => (None, None),
};
div() div()
.id(id.clone()) .id(id.clone())
.debug_selector(move || format!("sidebar-{debug_id}")) .debug_selector(move || format!("sidebar-{debug_id}"))
@@ -393,14 +360,12 @@ impl RenderOnce for Sidebar {
.flex_col() .flex_col()
.when(material, |sidebar| sidebar.bg(theme.material.background)) .when(material, |sidebar| sidebar.bg(theme.material.background))
.text_size(theme.sizes.medium.text_size) .text_size(theme.sizes.medium.text_size)
.when(custom, |sidebar| { .when(border_right, |sidebar| {
sidebar.role(Role::Group).aria_label(label) sidebar
.border_r(BORDER_WIDTH)
.border_color(theme.colors.border)
}) })
.when_some(leading_strip, |sidebar, strip| sidebar.child(strip))
.when_some(header, |sidebar, header| sidebar.child(header))
.child(body) .child(body)
.when_some(footer, |sidebar, footer| sidebar.child(footer))
.when_some(overlay_strip, |sidebar, strip| sidebar.child(strip))
.when(material && grain, |sidebar| sidebar.child(grain_overlay())) .when(material && grain, |sidebar| sidebar.child(grain_overlay()))
} }
} }
@@ -451,6 +416,7 @@ impl SidebarEntry {
.when_some(suffix, |header, suffix| header.child(suffix)) .when_some(suffix, |header, suffix| header.child(suffix))
.into_any_element() .into_any_element()
} }
SidebarEntry::Custom(element) => element,
SidebarEntry::Row { SidebarEntry::Row {
key, key,
label, label,
+33 -44
View File
@@ -4257,7 +4257,7 @@ impl Render for SidebarDemo {
), ),
)) ))
.child(demo_section( .child(demo_section(
"header and footer slots stay pinned around the list", "custom entries slot user content around the rows",
colors, colors,
div() div()
.w(rems(17.5)) .w(rems(17.5))
@@ -4270,41 +4270,41 @@ impl Render for SidebarDemo {
Sidebar::new("sidebar-demo-slots") Sidebar::new("sidebar-demo-slots")
.selected(self.selected) .selected(self.selected)
.transparent(true) .transparent(true)
.header(
div()
.px_2()
.py_2()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.child("Library"),
)
.footer(
div()
.px_2()
.py_2()
.text_xs()
.text_color(colors.muted_foreground)
.child("3 of 7 items"),
)
.on_change(move |selected, _, cx| { .on_change(move |selected, _, cx| {
view_slots.update(cx, |demo, cx| { view_slots.update(cx, |demo, cx| {
demo.selected = selected; demo.selected = selected;
cx.notify(); cx.notify();
}); });
}) })
.entries(|_, _| { .entries(move |_, _| {
vec![ vec![
SidebarEntry::custom(
div()
.px_2()
.py_2()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.child("Library"),
),
SidebarEntry::header("Favorites"), SidebarEntry::header("Favorites"),
SidebarEntry::row("Documents", "Documents"), SidebarEntry::row("Documents", "Documents"),
SidebarEntry::row("Pictures", "Pictures").detail("24"), SidebarEntry::row("Pictures", "Pictures").detail("24"),
SidebarEntry::header("Locations"), SidebarEntry::header("Locations"),
SidebarEntry::row("Trash", "Trash"), SidebarEntry::row("Trash", "Trash"),
SidebarEntry::custom(
div()
.px_2()
.py_2()
.text_xs()
.text_color(colors.muted_foreground)
.child("3 of 7 items"),
),
] ]
}), }),
), ),
)) ))
.child(demo_section( .child(demo_section(
"custom content replaces the list; the sidebar is a bare container", "a custom entry fills the list; the right border is off",
colors, colors,
div() div()
.w(rems(17.5)) .w(rems(17.5))
@@ -4316,31 +4316,20 @@ impl Render for SidebarDemo {
.child( .child(
Sidebar::new("sidebar-demo-custom") Sidebar::new("sidebar-demo-custom")
.transparent(true) .transparent(true)
.header( .border_right(false)
div() .entries(move |_, _| {
.px_2() vec![SidebarEntry::custom(
.py_2() div()
.text_sm() .w_full()
.font_weight(FontWeight::MEDIUM) .px_2()
.child("Welcome"), .py_6()
) .flex()
.content( .items_center()
div() .justify_center()
.size_full() .text_color(colors.muted_foreground)
.flex() .child("Nothing here yet"),
.items_center() )]
.justify_center() }),
.text_color(colors.muted_foreground)
.child("Nothing here yet"),
)
.footer(
div()
.px_2()
.py_2()
.text_xs()
.text_color(colors.muted_foreground)
.child("v1.0"),
),
), ),
)) ))
.child( .child(