//! The sidebar: a controlled list with section headers — the Finder //! sidebar's model of rows grouped under non-selectable labels. Custom content //! replaces the list and takes the whole container; the header and footer //! slots apply only to the entry list. use std::rc::Rc; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, }; use gpui_native_core::scroll_area::ScrollArea; use gpui_native_theme::ActiveTheme as _; 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. type ChangeHandler = Rc, &mut Window, &mut App)>; type EntriesFn = Box Vec>; /// One entry of a [`Sidebar`], a section header or a selectable row. #[must_use] pub enum SidebarEntry { /// A non-selectable section label. Header { label: SharedString }, /// A selectable row. Row { key: ElementId, label: SharedString, detail: Option, prefix: Option, suffix: Option, disabled: bool, }, } impl SidebarEntry { /// Creates a section header. pub fn header(label: L) -> Self where L: Into, { Self::Header { label: label.into(), } } /// Creates a selectable row shown as `label`, identified by `key`. pub fn row(key: K, label: L) -> Self where K: Into, L: Into, { Self::Row { key: key.into(), label: label.into(), detail: None, prefix: None, suffix: None, disabled: false, } } /// Shows muted trailing text. pub fn detail(mut self, detail: D) -> Self where D: Into, { if let Self::Row { detail: row_detail, .. } = &mut self { *row_detail = Some(detail.into()); } self } /// Shows an element leading the row. pub fn prefix(mut self, prefix: E) -> Self where E: IntoElement, { if let Self::Row { prefix: slot, .. } = &mut self { *slot = Some(prefix.into_any_element()); } self } /// Shows an element trailing the row. pub fn suffix(mut self, suffix: E) -> Self where E: IntoElement, { if let Self::Row { suffix: slot, .. } = &mut self { *slot = Some(suffix.into_any_element()); } 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)] #[must_use] pub struct Sidebar { id: ElementId, selected: Option, transparent: bool, a11y_label: Option, on_change: Option, entries: Option, header: Option, content: Option, footer: Option, } impl Sidebar { /// Creates a sidebar with nothing selected. pub fn new(id: I) -> Self where I: Into, { Self { id: id.into(), selected: None, transparent: false, a11y_label: None, on_change: None, entries: None, header: None, content: None, footer: None, } } /// Sets the current selection. pub fn selected(mut self, selected: Option) -> Self { self.selected = selected; self } /// Paints translucent material fills so the window's native backdrop shows through. pub fn transparent(mut self, transparent: bool) -> Self { self.transparent = transparent; self } /// Whether translucent material fills are painted. pub fn is_transparent(&self) -> bool { self.transparent } /// Reports the next selected row, from clicks and keys alike. pub fn on_change(mut self, handler: F) -> Self where F: Fn(Option, &mut Window, &mut App) + 'static, { self.on_change = Some(Rc::new(handler)); self } /// Sets the entries, the closure runs during render and must not mutate entities or notify. pub fn entries(mut self, entries: F) -> Self where F: Fn(&mut Window, &mut App) -> Vec + 'static, { self.entries = Some(Box::new(entries)); self } /// Pins an element above the list, ignored when content is set. pub fn header(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(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(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. pub fn accessibility_label(mut self, label: L) -> Self where L: Into, { self.a11y_label = Some(label.into()); self } } impl RenderOnce for Sidebar { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let Self { id, selected, transparent: material, a11y_label, on_change, entries, header, content, footer, } = 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 debug_id = id.clone(); let body = match content { Some(content) => div() .flex_1() .min_h_0() .overflow_hidden() .child(content) .into_any_element(), None => { let entries = match entries { Some(build) => build(window, cx), None => Vec::new(), }; // Headers are never selectable; only enabled rows are. let selectable: Vec = entries .iter() .enumerate() .filter(|(_, entry)| match entry { SidebarEntry::Row { disabled, .. } => !disabled, SidebarEntry::Header { .. } => 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 = 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(); div() .id(id.clone()) .debug_selector(move || format!("sidebar-{debug_id}")) .size_full() .flex() .flex_col() .when(material, |sidebar| sidebar.bg(theme.material.background)) .text_size(theme.sizes.medium.text_size) .when(custom, |sidebar| { sidebar.role(Role::Group).aria_label(label) }) .when_some(header, |sidebar, header| sidebar.child(header)) .child(body) .when_some(footer, |sidebar, footer| sidebar.child(footer)) } } impl SidebarEntry { #[allow(clippy::too_many_arguments)] fn render_entry( self, cx: &App, index: usize, position_in_set: usize, size_of_set: usize, selected: bool, material: bool, on_change: &Option, focus: &FocusHandle, ) -> AnyElement { let theme = cx.theme(); match self { SidebarEntry::Header { label } => { // The id is required for the role to surface in the a11y tree. div() .id(("sidebar-header".into(), label.clone())) .px_2() .pt_2() .pb_1() .text_sm() .font_weight(gpui::FontWeight::MEDIUM) .text_color(theme.colors.muted_foreground) .role(Role::Heading) .child(label) .into_any_element() } SidebarEntry::Row { key, label, detail, prefix, suffix, disabled: row_disabled, } => { let label_color = selectable_label_color(cx, selected, row_disabled); div() .id((key.clone(), "sidebar-row")) .flex() .items_center() .gap_2() .px_2() .py_1() .rounded(theme.radius.sm) .role(Role::ListItem) .aria_selected(selected) .aria_position_in_set(position_in_set) .aria_size_of_set(size_of_set) .map(|row| { if material && !row_disabled { if selected { row.bg(theme.material.selection) } else { row.hover(|row| row.bg(theme.material.hover)) } } else { paint_selectable_row(cx, row, selected, row_disabled) } }) .when(!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); } } }) }) .when_some(prefix, |row, prefix| row.child(prefix)) .child(div().flex_1().text_color(label_color).child(label)) .when_some(detail, |row, detail| { row.child( div() .flex_none() .text_sm() .text_color(if selected { theme.colors.primary_foreground } else { theme.colors.muted_foreground }) .child(detail), ) }) .when_some(suffix, |row, suffix| row.child(suffix)) .into_any_element() } } } }