tabs: collapse same-kind tabs into group chips

This commit is contained in:
2026-11-15 14:50:48 +07:00
parent f6ba9c0d47
commit daca373f77
5 changed files with 668 additions and 90 deletions
+315 -35
View File
@@ -79,6 +79,33 @@ impl TabsMeasurements {
}
}
/// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip.
enum StripItem {
/// A tab outside any two-member kind group, at its original index.
Single(usize, Tab),
/// Tabs of one kind collapsed into a chip, at the first member's index.
Group {
kind: SharedString,
/// The collapsed tabs with their original indices.
members: Vec<(usize, Tab)>,
},
}
impl StripItem {
/// The key the strip's geometry records the item under.
fn measure_key(&self, tabs_id: &ElementId) -> String {
match self {
StripItem::Single(_, tab) => tab.key.to_string(),
StripItem::Group { kind, .. } => group_key(tabs_id, kind).to_string(),
}
}
}
/// The group chip's identity for one strip and kind.
fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId {
SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into()
}
/// The visual language of a [`Tabs`] strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabsVariant {
@@ -97,6 +124,7 @@ pub struct Tab {
busy: bool,
disabled: bool,
closeable: bool,
kind: Option<SharedString>,
wrap: Option<TabWrap>,
}
@@ -114,6 +142,7 @@ impl Tab {
busy: false,
disabled: false,
closeable: false,
kind: None,
wrap: None,
}
}
@@ -145,6 +174,15 @@ impl Tab {
self
}
/// Sets the kind the tab belongs to; same-kind tabs collapse into one group.
pub fn kind<K>(mut self, kind: K) -> Self
where
K: Into<SharedString>,
{
self.kind = Some(kind.into());
self
}
/// Hands the rendered tab through `wrap`, e.g. to attach a drag payload.
pub fn wrap<F>(mut self, wrap: F) -> Self
where
@@ -271,13 +309,13 @@ impl Tabs {
self
}
/// The number of tabs that fit before the popover trigger, from last frame's geometry.
fn inline_count(tabs: &[Tab], measure: &StripMeasure) -> usize {
/// The number of items that fit before the popover trigger, from last frame's geometry.
fn inline_count(tabs_id: &ElementId, items: &[StripItem], measure: &StripMeasure) -> usize {
let limit = measure.container_width - measure.trigger_width.unwrap_or(Pixels::ZERO);
let mut count = 0;
for tab in tabs {
let Some(entry) = measure.tabs.get(&tab.key.to_string()) else {
return tabs.len();
for item in items {
let Some(entry) = measure.tabs.get(&item.measure_key(tabs_id)) else {
return items.len();
};
if entry.left + entry.width > limit {
break;
@@ -290,8 +328,7 @@ impl Tabs {
#[allow(clippy::too_many_arguments)]
fn render_overflow_popover(
id: &ElementId,
overflow_tabs: Vec<Tab>,
inline_count: usize,
overflow_items: Vec<StripItem>,
selected_index: usize,
variant: TabsVariant,
open: bool,
@@ -344,11 +381,10 @@ impl Tabs {
.into_any_element()
})
.content(move |_, cx| {
let rows: Vec<AnyElement> = overflow_tabs
let rows: Vec<AnyElement> = overflow_items
.into_iter()
.zip(inline_count..)
.map(|(tab, index)| {
tab.render_tab(
.flat_map(|item| match item {
StripItem::Single(index, tab) => vec![tab.render_tab(
&id,
cx,
index,
@@ -358,35 +394,264 @@ impl Tabs {
&on_close,
&focus,
None,
)],
StripItem::Group { members, .. } => members
.into_iter()
.map(|(index, tab)| {
tab.render_tab(
&id,
cx,
index,
selected_index,
variant,
&row_change,
&on_close,
&focus,
None,
)
})
.collect::<Vec<_>>(),
})
.collect();
ScrollArea::new((id.clone(), "tabs-overflow-list"))
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.child(v_flex().gap_0p5().p_1().children(rows))
.into_any_element()
})
}
/// Collapses same-kind tabs (two or more) into group chips, keeping strip order.
fn group_by_kind(tabs: Vec<Tab>) -> Vec<StripItem> {
let mut counts: HashMap<SharedString, usize> = HashMap::new();
for tab in &tabs {
if let Some(kind) = &tab.kind {
*counts.entry(kind.clone()).or_default() += 1;
}
}
let mut items: Vec<StripItem> = Vec::new();
let mut group_slots: HashMap<SharedString, usize> = HashMap::new();
for (index, tab) in tabs.into_iter().enumerate() {
let grouped_kind = tab
.kind
.clone()
.filter(|kind| counts.get(kind).copied().unwrap_or(0) >= 2);
match grouped_kind {
Some(kind) => match group_slots.get(&kind).copied() {
Some(slot) => {
if let StripItem::Group { members, .. } = &mut items[slot] {
members.push((index, tab));
}
}
None => {
group_slots.insert(kind.clone(), items.len());
items.push(StripItem::Group {
kind,
members: vec![(index, tab)],
});
}
},
None => items.push(StripItem::Single(index, tab)),
}
}
items
}
/// Renders a group chip labeled with the kind and its member count.
#[allow(clippy::too_many_arguments)]
fn render_group_tab(
tabs_id: &ElementId,
kind: SharedString,
members: Vec<(usize, Tab)>,
selected_index: usize,
variant: TabsVariant,
on_change: Option<ChangeHandler>,
on_close: Option<CloseHandler>,
focus: &gpui::FocusHandle,
measure: Option<&MeasureFrame>,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let tabs_id = tabs_id.clone();
let focus = focus.clone();
let count = members.len();
let selected = members.iter().any(|(index, _)| *index == selected_index);
let open = window
.use_keyed_state((group_key(&tabs_id, &kind), "open"), cx, |_, _| false)
.clone();
let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::default());
let small = theme.sizes.small;
let label_color = match variant {
TabsVariant::Underline => {
if selected {
theme.ramps.primary.base
} else {
theme.colors.foreground
}
}
TabsVariant::Pill => theme.colors.foreground,
};
let group_key = group_key(&tabs_id, &kind);
let chip = div()
.id((group_key.clone(), "group-tab"))
.debug_selector({
let tabs_id = tabs_id.clone();
let label = kind.clone();
move || format!("{tabs_id}-group-{label}")
})
.flex()
.items_center()
.gap_1p5()
.cursor_pointer()
.role(Role::Tab)
.aria_selected(selected)
.aria_label(SharedString::from(format!("{kind}, {count} tabs")))
.text_color(label_color)
.when(!selected, |chip| {
chip.hover(|chip| chip.bg(theme.colors.muted))
})
.map(|chip| match variant {
TabsVariant::Underline => chip
.px_2()
.py_1()
.rounded_tl(theme.radius.sm)
.rounded_tr(theme.radius.sm)
.border_b_2()
.border_color(gpui::transparent_black())
.when(selected, |chip| chip.border_color(theme.ramps.primary.base)),
TabsVariant::Pill => chip
.h(small.control_height + metrics.plate_inset * 2.0)
.px(metrics.dense_padding_x)
.pr(metrics.plate_inset)
.rounded(theme.radius.control)
.when(selected, |chip| {
chip.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
})
.child(SharedString::from(format!("{kind} ({count})")))
.when(variant == TabsVariant::Pill, |chip| {
chip.child(div().flex_none().w(metrics.padding_x * 1.5))
})
.when_some(measure, |chip, measure| {
let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone();
let item_key = group_key.to_string();
chip.child(
canvas(
move |bounds, _, cx| {
let root = root_bounds.borrow();
if let Some(root) = root.as_ref() {
cx.default_global::<TabsMeasurements>().record_tab(
&key,
item_key,
TabMeasure {
left: bounds.origin.x - root.origin.x,
width: bounds.size.width,
},
);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0(),
)
});
// Selecting a row also dismisses the popover, mirroring the overflow popover.
let row_change: Option<ChangeHandler> = {
let open = open.clone();
Some(Rc::new(move |index, window, cx| {
open.update(cx, |open, cx| {
*open = false;
cx.notify();
});
if let Some(on_change) = &on_change {
on_change(index, window, cx);
}
}))
};
Popover::new((group_key.clone(), "group-popover"))
.open(*open.read(cx))
.on_change({
let open = open.clone();
move |next, _, cx| {
open.update(cx, |open, cx| {
*open = next;
cx.notify();
});
}
})
.trigger(move |_, _| chip.into_any_element())
.content(move |_, cx| {
let rows: Vec<AnyElement> = members
.into_iter()
.map(|(index, tab)| {
tab.render_tab(
&tabs_id,
cx,
index,
selected_index,
variant,
&row_change,
&on_close,
&focus,
None,
)
})
.collect();
ScrollArea::new((id.clone(), "tabs-overflow-list"))
ScrollArea::new((group_key.clone(), "tabs-group-list"))
.axes(ScrollAxes::Vertical)
.max_h(POPUP_MAX_HEIGHT)
.child(v_flex().gap_0p5().p_1().children(rows))
.into_any_element()
})
.into_any_element()
}
}
impl RenderOnce for Tabs {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let mut tabs = match self.tabs {
let tabs = match self.tabs {
Some(build) => build(window, cx),
None => Vec::new(),
};
let mut items = Self::group_by_kind(tabs);
let selectable: Vec<usize> = tabs
let selectable: Vec<usize> = items
.iter()
.enumerate()
.filter(|(_, tab)| !tab.disabled)
.map(|(index, _)| index)
.flat_map(|item| match item {
StripItem::Single(index, tab) => (!tab.disabled)
.then_some(*index)
.into_iter()
.collect::<Vec<_>>(),
StripItem::Group { members, .. } => members
.iter()
.filter(|(_, tab)| !tab.disabled)
.map(|(index, _)| *index)
.collect::<Vec<_>>(),
})
.collect();
let focus = gpui_native_utils::focus_handle(&self.id, window, cx);
let theme = cx.theme();
// Theme reads end here, so the strip's group chips can take `cx` mutably.
let (medium_text_size, border_color) = {
let theme = cx.theme();
(theme.sizes.medium.text_size, theme.colors.border)
};
let label = self
.a11y_label
@@ -407,20 +672,19 @@ impl RenderOnce for Tabs {
let inline_count = measure
.as_ref()
.map(|measure| Self::inline_count(&tabs, measure))
.unwrap_or(tabs.len());
let overflow_tabs = tabs.split_off(inline_count);
.map(|measure| Self::inline_count(&self.id, &items, measure))
.unwrap_or(items.len());
let overflow_items = items.split_off(inline_count);
let measure_frame = self.overflow_popover.then(|| MeasureFrame {
key: measure_key.clone(),
root_bounds: Rc::new(RefCell::new(None)),
});
let strip: Vec<AnyElement> = tabs
let strip: Vec<AnyElement> = items
.into_iter()
.enumerate()
.map(|(index, tab)| {
tab.render_tab(
.map(|item| match item {
StripItem::Single(index, tab) => tab.render_tab(
&self.id,
cx,
index,
@@ -430,16 +694,28 @@ impl RenderOnce for Tabs {
&self.on_close,
&focus,
measure_frame.as_ref(),
)
),
StripItem::Group { kind, members } => Self::render_group_tab(
&self.id,
kind,
members,
self.selected,
self.variant,
self.on_change.clone(),
self.on_close.clone(),
&focus,
measure_frame.as_ref(),
window,
cx,
),
})
.collect();
let popover = (self.overflow_popover && measure.is_some() && !overflow_tabs.is_empty())
let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty())
.then(|| {
Self::render_overflow_popover(
&self.id,
overflow_tabs,
inline_count,
overflow_items,
self.selected,
self.variant,
self.overflow_open,
@@ -453,7 +729,7 @@ impl RenderOnce for Tabs {
div()
.id(self.id.clone())
.flex()
.text_size(theme.sizes.medium.text_size)
.text_size(medium_text_size)
.track_focus(&focus)
.focusable()
.tab_stop(true)
@@ -480,9 +756,7 @@ impl RenderOnce for Tabs {
}
})
.map(|root| match self.variant {
TabsVariant::Underline => {
root.gap_1().border_b_1().border_color(theme.colors.border)
}
TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color),
TabsVariant::Pill => root.items_center().gap_1(),
})
.map(|root| {
@@ -629,10 +903,16 @@ impl Tab {
.px(metrics.dense_padding_x)
.pr(metrics.plate_inset)
.rounded(theme.radius.control)
.when(selected, |strip_tab| strip_tab.bg(theme.colors.muted_hover)),
// The active tab is a small island: the panel's fill, with
// the platform's control shadow lifting it off the strip.
.when(selected, |strip_tab| {
strip_tab
.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows())
}),
})
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(self.label.clone())
.child(div().flex_grow(1.0).child(self.label.clone()))
.when(variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w(metrics.padding_x * 1.5))
})
+96
View File
@@ -0,0 +1,96 @@
#![cfg(feature = "tabs")]
//! Grouped tabs: same-kind tabs collapse into one chip that opens a popover
//! listing the members; picking one selects it by its original index.
use std::cell::RefCell;
use std::rc::Rc;
use gpui::{
Context, IntoElement, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext,
VisualTestContext, Window, div, px, size,
};
use gpui_native_data::tabs::{Tab, Tabs, TabsVariant};
use gpui_native_theme::Theme;
struct StripHarness {
changed: Rc<RefCell<Vec<usize>>>,
}
impl Render for StripHarness {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let changed = self.changed.clone();
div().size_full().child(
Tabs::new("strip")
.variant(TabsVariant::Pill)
.tabs(|_, _| {
vec![
Tab::new("a", "Alpha").kind("Kind"),
Tab::new("b", "Beta").kind("Kind"),
Tab::new("c", "Gamma"),
Tab::new("d", "Delta").kind("Lone"),
]
})
.on_change(move |index, _, _| changed.borrow_mut().push(index)),
)
}
}
fn strip_window(cx: &mut TestAppContext, changed: Rc<RefCell<Vec<usize>>>) -> VisualTestContext {
cx.update(Theme::init);
let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness { changed });
let cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked();
cx
}
#[gpui::test]
fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) {
let mut cx = strip_window(cx, Rc::new(RefCell::new(Vec::new())));
assert!(
cx.debug_bounds("strip-group-Kind").is_some(),
"two same-kind tabs draw one group chip"
);
assert!(
cx.debug_bounds("strip-tab-Alpha").is_none(),
"grouped members do not draw inline"
);
assert!(cx.debug_bounds("strip-tab-Beta").is_none());
// A tab outside any two-member kind group draws itself, kinded or not.
assert!(cx.debug_bounds("strip-tab-Gamma").is_some());
assert!(cx.debug_bounds("strip-tab-Delta").is_some());
assert!(
cx.debug_bounds("strip-group-Lone").is_none(),
"a lone kinded tab is not grouped"
);
}
#[gpui::test]
fn picking_a_group_member_selects_it(cx: &mut TestAppContext) {
let changed = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(cx, changed.clone());
let chip = cx
.debug_bounds("strip-group-Kind")
.expect("group chip drawn");
cx.simulate_click(chip.center(), Modifiers::none());
cx.run_until_parked();
let beta = cx
.debug_bounds("strip-tab-Beta")
.expect("the popover lists the members");
cx.simulate_click(beta.center(), Modifiers::none());
cx.run_until_parked();
assert_eq!(
changed.borrow().as_slice(),
&[1],
"picking a member reports its original index"
);
assert!(
cx.debug_bounds("strip-tab-Beta").is_none(),
"a selection dismisses the popover"
);
}
+24 -11
View File
@@ -7,30 +7,51 @@ use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _,
Render, RenderOnce, StyleRefinement, Styled as _, Window, div, rems,
Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, rems,
};
use gpui_native_theme::ActiveTheme as _;
use crate::resizable::{Resizable, ResizableState};
pub trait Panel: Render + 'static {}
/// A user-defined panel the row can show.
#[allow(unused_variables)]
pub trait Panel: Render + 'static {
/// The kind the panel belongs to; same-kind panels group in the tab bar.
fn kind(&self, cx: &App) -> Option<SharedString> {
None
}
}
/// An object-safe handle to a panel, so apps can hold panels by kind.
#[allow(unused_variables)]
pub trait PanelView: 'static {
/// The panel's view.
fn view(&self) -> AnyView;
/// The panel's kind, read live from the panel.
fn kind(&self, cx: &App) -> Option<SharedString> {
None
}
}
impl<T: Panel> PanelView for Entity<T> {
fn view(&self) -> AnyView {
self.clone().into()
}
fn kind(&self, cx: &App) -> Option<SharedString> {
self.read(cx).kind(cx)
}
}
impl<P: PanelView + ?Sized> PanelView for Arc<P> {
fn view(&self) -> AnyView {
(**self).view()
}
fn kind(&self, cx: &App) -> Option<SharedString> {
(**self).kind(cx)
}
}
/// The layout the cached panel content lays out with.
@@ -131,14 +152,6 @@ impl RenderOnce for PanelRow {
None => div().w_full().h_full().child(main),
};
div()
.flex_1()
.min_w_0()
.h_full()
// the titlebar's centered tabs leave slack above the strip's
// bottom edge, so the top gutter is narrower to even out.
.p_2()
.pt_1()
.child(row)
div().flex_1().min_w_0().h_full().p_2().pt_1().child(row)
}
}