sidebar: add header, footer, and custom content slots

This commit is contained in:
2026-11-11 10:20:10 +07:00
parent 65509ccde1
commit d862559643
2 changed files with 244 additions and 90 deletions
+156 -90
View File
@@ -1,5 +1,7 @@
//! 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. //! sidebar's model of rows grouped under non-selectable labels. Custom content
//! can replace the list, leaving a bare container with the header and footer
//! slots around it.
use std::rc::Rc; use std::rc::Rc;
@@ -119,6 +121,9 @@ pub struct Sidebar {
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>,
} }
impl Sidebar { impl Sidebar {
@@ -134,6 +139,9 @@ impl Sidebar {
a11y_label: None, a11y_label: None,
on_change: None, on_change: None,
entries: None, entries: None,
header: None,
content: None,
footer: None,
} }
} }
@@ -172,6 +180,33 @@ impl Sidebar {
self self
} }
/// Pins an element above the body, below nothing else.
pub fn header<E>(mut self, header: E) -> Self
where
E: IntoElement,
{
self.header = Some(header.into_any_element());
self
}
/// Replaces the entries with custom content.
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 body, above nothing else.
pub fn footer<E>(mut self, footer: E) -> Self
where
E: IntoElement,
{
self.footer = Some(footer.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
@@ -184,108 +219,139 @@ impl Sidebar {
impl RenderOnce for Sidebar { impl RenderOnce for Sidebar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let entries = match self.entries { let Self {
Some(build) => build(window, cx), id,
None => Vec::new(), selected,
}; transparent: material,
a11y_label,
on_change,
entries,
header,
content,
footer,
} = self;
// Headers are never selectable; only enabled rows are. let custom = content.is_some();
let selectable: Vec<usize> = entries let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string()));
.iter() let debug_id = id.clone();
.enumerate()
.filter(|(_, entry)| match entry {
SidebarEntry::Row { disabled, .. } => !disabled,
SidebarEntry::Header { .. } => false,
})
.map(|(index, _)| index)
.collect();
let focus = gpui_native_utils::focus_handle(&self.id, window, cx); let body = match content {
let scroll = window.with_element_namespace(self.id.clone(), |window| { Some(content) => div()
window .flex_1()
.use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) .min_h_0()
.clone() .overflow_hidden()
}); .child(content)
let theme = cx.theme(); .into_any_element(),
let material = self.transparent; None => {
let entries = match entries {
let label = self Some(build) => build(window, cx),
.a11y_label None => Vec::new(),
.clone()
.unwrap_or_else(|| SharedString::from(self.id.to_string()));
let scroll_area_id = (self.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)
}; };
entry.render_entry( // Headers are never selectable; only enabled rows are.
cx, let selectable: Vec<usize> = entries
index, .iter()
position_in_set, .enumerate()
size_of_set, .filter(|(_, entry)| match entry {
self.selected == Some(index), SidebarEntry::Row { disabled, .. } => !disabled,
material, SidebarEntry::Header { .. } => false,
&self.on_change, })
&focus, .map(|(index, _)| index)
) .collect();
})
.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)
};
entry.render_entry(
cx,
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(
ScrollArea::new(scroll_area_id)
.handle(scroll.read(cx).clone())
.h_full()
.px_1()
.gap_0p5()
.children(children),
)
.into_any_element()
}
};
let theme = cx.theme();
let id = self.id;
div() div()
.id(id.clone()) .id(id.clone())
.debug_selector(move || format!("sidebar-{id}")) .debug_selector(move || format!("sidebar-{debug_id}"))
.size_full() .size_full()
.flex() .flex()
.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)
.track_focus(&focus) .when(custom, |sidebar| {
.focusable() sidebar.role(Role::Group).aria_label(label)
.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| {
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( .when_some(header, |sidebar, header| sidebar.child(header))
ScrollArea::new(scroll_area_id) .child(body)
.handle(scroll.read(cx).clone()) .when_some(footer, |sidebar, footer| sidebar.child(footer))
.h_full()
.px_1()
.gap_0p5()
.children(children),
)
} }
} }
+88
View File
@@ -3852,6 +3852,7 @@ struct SidebarDemo {
impl Render for SidebarDemo { impl Render for SidebarDemo {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let view = cx.entity(); let view = cx.entity();
let view_slots = view.clone();
let theme = cx.theme(); let theme = cx.theme();
let colors = theme.colors; let colors = theme.colors;
let radius = theme.radius; let radius = theme.radius;
@@ -3909,6 +3910,93 @@ impl Render for SidebarDemo {
}), }),
), ),
)) ))
.child(demo_section(
"header and footer slots stay pinned around the list",
colors,
div()
.w(rems(17.5))
.h(rems(22.5))
.rounded(radius.control)
.border_1()
.border_color(colors.border)
.overflow_hidden()
.child(
Sidebar::new("sidebar-demo-slots")
.selected(self.selected)
.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| {
view_slots.update(cx, |demo, cx| {
demo.selected = selected;
cx.notify();
});
})
.entries(|_, _| {
vec![
SidebarEntry::header("Favorites"),
SidebarEntry::row("Documents", "Documents"),
SidebarEntry::row("Pictures", "Pictures").detail("24"),
SidebarEntry::header("Locations"),
SidebarEntry::row("Trash", "Trash"),
]
}),
),
))
.child(demo_section(
"custom content replaces the list; the sidebar is a bare container",
colors,
div()
.w(rems(17.5))
.h(rems(13.))
.rounded(radius.control)
.border_1()
.border_color(colors.border)
.overflow_hidden()
.child(
Sidebar::new("sidebar-demo-custom")
.transparent(true)
.header(
div()
.px_2()
.py_2()
.text_sm()
.font_weight(FontWeight::MEDIUM)
.child("Welcome"),
)
.content(
div()
.size_full()
.flex()
.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(
div() div()
.text_xs() .text_xs()