From 33f8856bc2332c426e90f5392b3f0e50d711ea05 Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Sat, 14 Nov 2026 19:27:50 +0700 Subject: [PATCH] tabs: add overflow popover for tabs that do not fit --- crates/core/src/popover.rs | 8 +- crates/data/Cargo.toml | 2 + crates/data/src/tabs.rs | 337 +++++++++++++++++++++++++++++++++-- crates/layout/src/dock.rs | 29 ++- examples/gallery/src/main.rs | 60 ++++++- 5 files changed, 414 insertions(+), 22 deletions(-) diff --git a/crates/core/src/popover.rs b/crates/core/src/popover.rs index 0dc2ebf..fef0033 100644 --- a/crates/core/src/popover.rs +++ b/crates/core/src/popover.rs @@ -14,8 +14,8 @@ use crate::common::{OVERLAY_LAYER, v_flex}; /// Reports the next open state of a [`Popover`]: `true` to open, `false` to close. type ChangeHandler = Rc; -type TriggerFn = Box AnyElement>; -type ContentFn = Box AnyElement>; +type TriggerFn = Box AnyElement>; +type ContentFn = Box AnyElement>; /// Bounds captured during the last paint, shared with the dismissal listener. type BoundsCell = Rc>>>; @@ -65,7 +65,7 @@ impl Popover { /// Sets the element the panel anchors below, rendered in place. pub fn trigger(mut self, trigger: F) -> Self where - F: Fn(&mut Window, &mut App) -> AnyElement + 'static, + F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static, { self.trigger = Some(Box::new(trigger)); self @@ -74,7 +74,7 @@ impl Popover { /// Sets the panel's contents. pub fn content(mut self, content: F) -> Self where - F: Fn(&mut Window, &mut App) -> AnyElement + 'static, + F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static, { self.content = Some(Box::new(content)); self diff --git a/crates/data/Cargo.toml b/crates/data/Cargo.toml index 022ec21..63a3f7e 100644 --- a/crates/data/Cargo.toml +++ b/crates/data/Cargo.toml @@ -26,6 +26,8 @@ sidebar = [ tabs = [ "dep:gpui-native-core", "gpui-native-core/button", + "gpui-native-core/popover", + "gpui-native-core/scroll_area", "gpui-native-core/spinner", "gpui-native-core/tooltip", ] diff --git a/crates/data/src/tabs.rs b/crates/data/src/tabs.rs index e44c5cb..565626c 100644 --- a/crates/data/src/tabs.rs +++ b/crates/data/src/tabs.rs @@ -1,17 +1,21 @@ +use std::cell::RefCell; +use std::collections::HashMap; use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ - AnyElement, App, Div, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, - ParentElement as _, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, - Styled as _, Window, div, + AnyElement, App, Bounds, ClickEvent, Div, ElementId, Global, InteractiveElement as _, + IntoElement, KeyDownEvent, ParentElement as _, Pixels, RenderOnce, Role, SharedString, + Stateful, StatefulInteractiveElement as _, Styled as _, Window, canvas, div, }; use gpui_native_core::button::{Button, ButtonVariant}; -use gpui_native_core::common::Sizable as _; +use gpui_native_core::common::{Sizable as _, v_flex}; +use gpui_native_core::popover::Popover; +use gpui_native_core::scroll_area::{ScrollArea, ScrollAxes}; use gpui_native_core::spinner::Spinner; use gpui_native_core::tooltip::Tooltip; use gpui_native_icons::IconRole; -use gpui_native_theme::{ActiveTheme as _, Size}; +use gpui_native_theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size}; use gpui_native_utils::adjacent_selectable; /// The change reporter, fired with the next selected tab by pointer and keys. @@ -21,6 +25,59 @@ type CloseHandler = Rc; /// Decorates the rendered tab, e.g. to attach a drag payload. type TabWrap = Box) -> AnyElement>; type TabsFn = Box Vec>; +/// The open-state reporter of the overflow popover. +type OpenHandler = Rc; +/// Identifies one strip's measurements across windows. +type MeasureKey = (u64, String); +/// Shared per-frame state that lets tab canvases read the strip's bounds. +type RootBoundsCell = Rc>>>; + +/// One inline tab's geometry relative to the strip's left edge. +#[derive(Clone, Copy, Default)] +struct TabMeasure { + left: Pixels, + width: Pixels, +} + +/// A strip's geometry captured the previous frame. +#[derive(Clone, Default)] +struct StripMeasure { + container_width: Pixels, + trigger_width: Option, + tabs: HashMap, +} + +/// The capture context handed to inline tabs, only in popover mode. +struct MeasureFrame { + key: MeasureKey, + root_bounds: RootBoundsCell, +} + +/// Measurements read a frame late, so strips render one frame behind a resize. +#[derive(Default)] +struct TabsMeasurements { + strips: HashMap, +} + +impl Global for TabsMeasurements {} + +impl TabsMeasurements { + fn record_container(&mut self, key: &MeasureKey, width: Pixels) { + self.strips.entry(key.clone()).or_default().container_width = width; + } + + fn record_trigger(&mut self, key: &MeasureKey, width: Pixels) { + self.strips.entry(key.clone()).or_default().trigger_width = Some(width); + } + + fn record_tab(&mut self, key: &MeasureKey, tab: String, measure: TabMeasure) { + self.strips + .entry(key.clone()) + .or_default() + .tabs + .insert(tab, measure); + } +} /// The visual language of a [`Tabs`] strip. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -109,9 +166,12 @@ pub struct Tabs { selected: usize, variant: TabsVariant, overflow_scroll: bool, + overflow_popover: bool, + overflow_open: bool, a11y_label: Option, on_change: Option, on_close: Option, + on_overflow_open: Option, tabs: Option, } @@ -126,9 +186,12 @@ impl Tabs { selected: 0, variant: TabsVariant::default(), overflow_scroll: false, + overflow_popover: false, + overflow_open: false, a11y_label: None, on_change: None, on_close: None, + on_overflow_open: None, tabs: None, } } @@ -151,6 +214,27 @@ impl Tabs { self } + /// Shows a popover of the tabs that do not fit, via a trigger at the strip's end. + pub fn overflow_popover(mut self, overflow_popover: bool) -> Self { + self.overflow_popover = overflow_popover; + self + } + + /// The overflow popover's current open state; read only in [`Self::overflow_popover`] mode. + pub fn overflow_open(mut self, overflow_open: bool) -> Self { + self.overflow_open = overflow_open; + self + } + + /// Reports the overflow popover's next open state, from its trigger, dismissals, and selection. + pub fn on_overflow_open(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_overflow_open = Some(Rc::new(handler)); + self + } + /// Reports the next selected tab, as an index into the `tabs` vec — not a tab key; indices shift on reorder. pub fn on_change(mut self, handler: F) -> Self where @@ -186,11 +270,110 @@ impl Tabs { self.a11y_label = Some(label.into()); self } + + /// The number of tabs that fit before the popover trigger, from last frame's geometry. + fn inline_count(tabs: &[Tab], 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(); + }; + if entry.left + entry.width > limit { + break; + } + count += 1; + } + count + } + + #[allow(clippy::too_many_arguments)] + fn render_overflow_popover( + id: &ElementId, + overflow_tabs: Vec, + inline_count: usize, + selected_index: usize, + variant: TabsVariant, + open: bool, + on_change: Option, + on_close: Option, + on_overflow_open: Option, + focus: gpui::FocusHandle, + ) -> Popover { + let id = id.clone(); + let trigger_id = id.clone(); + + let row_change: Option = match (on_change, on_overflow_open.clone()) { + (Some(on_change), Some(dismiss)) => Some(Rc::new(move |index, window, cx| { + on_change(index, window, cx); + dismiss(false, window, cx); + })), + (None, Some(dismiss)) => Some(Rc::new(move |_, window, cx| { + dismiss(false, window, cx); + })), + (on_change, None) => on_change, + }; + + Popover::new((id.clone(), "tabs-overflow")) + .open(open) + .on_change({ + let on_overflow_open = on_overflow_open.clone(); + move |next, window, cx| { + if let Some(on_overflow_open) = &on_overflow_open { + on_overflow_open(next, window, cx); + } + } + }) + .trigger(move |_, _| { + Button::new((trigger_id.clone(), "tabs-overflow-trigger")) + .icon(IconRole::More) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("More tabs") + .on_click({ + let on_overflow_open = on_overflow_open.clone(); + move |event, window, cx| { + // Pointer clicks toggle inside Popover; only the keyboard path lands here. + if let ClickEvent::Keyboard(_) = event + && let Some(on_overflow_open) = &on_overflow_open + { + on_overflow_open(!open, window, cx); + } + } + }) + .into_any_element() + }) + .content(move |_, cx| { + let rows: Vec = overflow_tabs + .into_iter() + .zip(inline_count..) + .map(|(tab, index)| { + tab.render_tab( + &id, + cx, + index, + selected_index, + variant, + &row_change, + &on_close, + &focus, + None, + ) + }) + .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() + }) + } } impl RenderOnce for Tabs { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { - let tabs = match self.tabs { + let mut tabs = match self.tabs { Some(build) => build(window, cx), None => Vec::new(), }; @@ -210,6 +393,29 @@ impl RenderOnce for Tabs { .clone() .unwrap_or_else(|| SharedString::from(self.id.to_string())); + let measure_key: MeasureKey = ( + window.window_handle().window_id().as_u64(), + self.id.to_string(), + ); + + let measure = if self.overflow_popover { + cx.try_global::() + .and_then(|cache| cache.strips.get(&measure_key).cloned()) + } else { + None + }; + + 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); + + let measure_frame = self.overflow_popover.then(|| MeasureFrame { + key: measure_key.clone(), + root_bounds: Rc::new(RefCell::new(None)), + }); + let strip: Vec = tabs .into_iter() .enumerate() @@ -223,10 +429,27 @@ impl RenderOnce for Tabs { &self.on_change, &self.on_close, &focus, + measure_frame.as_ref(), ) }) .collect(); + let popover = (self.overflow_popover && measure.is_some() && !overflow_tabs.is_empty()) + .then(|| { + Self::render_overflow_popover( + &self.id, + overflow_tabs, + inline_count, + self.selected, + self.variant, + self.overflow_open, + self.on_change.clone(), + self.on_close.clone(), + self.on_overflow_open.clone(), + focus.clone(), + ) + }); + div() .id(self.id.clone()) .flex() @@ -262,16 +485,72 @@ impl RenderOnce for Tabs { } TabsVariant::Pill => root.items_center().gap_1(), }) - .map(|root| match self.overflow_scroll { - true => root.min_w_0().overflow_x_scroll().child( - div() - .flex_none() - .flex() - .gap_1() - .when(self.variant == TabsVariant::Pill, |row| row.items_center()) - .children(strip), - ), - false => root.children(strip), + .map(|root| { + if self.overflow_popover { + let Some(root_bounds) = measure_frame.map(|frame| frame.root_bounds) else { + return root.children(strip); + }; + let container_canvas = canvas( + { + let key = measure_key.clone(); + move |bounds, _, cx| { + cx.default_global::() + .record_container(&key, bounds.size.width); + *root_bounds.borrow_mut() = Some(bounds); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(); + let trigger_canvas = canvas( + { + let key = measure_key; + move |bounds, _, cx| { + cx.default_global::() + .record_trigger(&key, bounds.size.width); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(); + + let control = match popover { + Some(popover) => div().flex_none().relative().child(popover), + None => div().flex_none().relative().child( + div().w(measure + .as_ref() + .and_then(|measure| measure.trigger_width) + .unwrap_or(Pixels::ZERO)), + ), + }; + + root.min_w_0() + .flex_grow(1.0) + .overflow_hidden() + .child(container_canvas) + .child( + div() + .flex_none() + .flex() + .gap_1() + .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .children(strip), + ) + .child(control.child(trigger_canvas)) + } else if self.overflow_scroll { + root.min_w_0().overflow_x_scroll().child( + div() + .flex_none() + .flex() + .gap_1() + .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .children(strip), + ) + } else { + root.children(strip) + } }) } } @@ -288,6 +567,7 @@ impl Tab { on_change: &Option, on_close: &Option, focus: &gpui::FocusHandle, + measure: Option<&MeasureFrame>, ) -> AnyElement { let selected = index == selected_index; @@ -368,6 +648,31 @@ impl Tab { ) }) .when_some(close, |strip_tab, close| strip_tab.child(close)) + .when_some(measure, |strip_tab, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let tab_key = self.key.to_string(); + strip_tab.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + tab_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) .when(!self.disabled, |strip_tab| { strip_tab.cursor_pointer().on_click({ let on_change = on_change.clone(); diff --git a/crates/layout/src/dock.rs b/crates/layout/src/dock.rs index 0d0b25d..a054d2a 100644 --- a/crates/layout/src/dock.rs +++ b/crates/layout/src/dock.rs @@ -146,6 +146,7 @@ struct Pane { key: u64, tabs: Vec, active: Option, + overflow_open: bool, } /// An internal node: two children along an axis. @@ -183,6 +184,7 @@ impl DockState { key: 0, tabs: Vec::new(), active: None, + overflow_open: false, }), panels: HashMap::new(), active_pane: 0, @@ -321,6 +323,17 @@ impl DockState { cx.notify(); } + /// Shows or hides the pane's overflow popover. + pub fn set_pane_overflow_open(&mut self, key: u64, open: bool, cx: &mut Context) { + let Some(pane) = self.pane_mut(key) else { + return; + }; + if pane.overflow_open != open { + pane.overflow_open = open; + cx.notify(); + } + } + /// Closes every other tab in the panel's pane, keeping this one active. pub fn close_others(&mut self, id: &str, cx: &mut Context) { let Some((pane_key, _)) = self.locate(id) else { @@ -437,6 +450,7 @@ impl DockState { key: new_key, tabs: vec![tab], active: Some(SharedString::from(id)), + overflow_open: false, }); Self::wrap_in(&mut self.root, target_key, new_pane, direction, split_key); @@ -693,6 +707,7 @@ impl DockState { }) .collect(), active: pane.active.clone(), + overflow_open: pane.overflow_open, }), Node::Split(split) => TreeView::Split(SplitView { key: split.key, @@ -740,6 +755,7 @@ impl DockState { key: u64::MAX, tabs: Vec::new(), active: None, + overflow_open: false, }), ) } @@ -757,6 +773,7 @@ struct PaneView { key: u64, tabs: Vec, active: Option, + overflow_open: bool, } struct SplitView { @@ -1064,7 +1081,17 @@ fn render_pane( pane.key ))) .variant(TabsVariant::Pill) - .overflow_scroll(true) + .overflow_popover(true) + .overflow_open(pane.overflow_open) + .on_overflow_open({ + let state = state.clone(); + let pane_key = pane.key; + move |open, _, cx| { + state.update(cx, |dock, cx| { + dock.set_pane_overflow_open(pane_key, open, cx) + }); + } + }) .selected(selected) .tabs({ let tabs = pane.tabs.clone(); diff --git a/examples/gallery/src/main.rs b/examples/gallery/src/main.rs index 9e888fc..e277b15 100644 --- a/examples/gallery/src/main.rs +++ b/examples/gallery/src/main.rs @@ -510,6 +510,8 @@ impl Gallery { ], pill_selected: 0, lead_selected: 0, + overflow_selected: 0, + overflow_open: false, }) }); dock.register_panel("alert", { @@ -2328,6 +2330,8 @@ struct TabsDemo { pill_tabs: Vec, pill_selected: usize, lead_selected: usize, + overflow_selected: usize, + overflow_open: bool, } impl Panel for TabsDemo { @@ -2342,6 +2346,8 @@ impl Render for TabsDemo { let view_pill = view.clone(); let view_close = view.clone(); let view_leads = view.clone(); + let view_overflow = view.clone(); + let view_overflow_open = view.clone(); let colors = cx.theme().colors; let pill_count = self.pill_tabs.len(); @@ -2447,7 +2453,59 @@ impl Render for TabsDemo { Tab::new("plain", "Plain"), ] }), - )), + )) + .child(demo_section( + "overflow popover", + colors, + div().w_96().child( + Tabs::new("tabs-demo-overflow") + .variant(TabsVariant::Pill) + .overflow_popover(true) + .overflow_open(self.overflow_open) + .on_overflow_open({ + let view = view_overflow_open.clone(); + move |open, _, cx| { + view.update(cx, |demo, cx| { + demo.overflow_open = open; + cx.notify(); + }); + } + }) + .selected(self.overflow_selected) + .on_change({ + let view = view_overflow.clone(); + move |selected, _, cx| { + view.update(cx, |demo, cx| { + demo.overflow_selected = selected; + cx.notify(); + }); + } + }) + .tabs(|_, _| { + [ + "Overview", + "Documents", + "Media", + "Archives", + "Projects", + "Snippets", + "Backups", + "Notes", + ] + .iter() + .map(|label| Tab::new(*label, *label)) + .collect() + }), + ), + )) + .child( + div() + .text_xs() + .text_color(colors.muted_foreground) + .child( + "Tabs that do not fit fold into the \"More tabs\" popover; picking one selects it", + ), + ), ) } }