tabs: add drag-to-reorder and pinned tabs

This commit is contained in:
2026-11-15 16:14:28 +07:00
parent daca373f77
commit 4f67f9e1c2
4 changed files with 534 additions and 151 deletions
+327 -129
View File
@@ -4,9 +4,10 @@ use std::rc::Rc;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AnyElement, App, Bounds, ClickEvent, Div, ElementId, Global, InteractiveElement as _, AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global,
IntoElement, KeyDownEvent, ParentElement as _, Pixels, RenderOnce, Role, SharedString, InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels,
Stateful, StatefulInteractiveElement as _, Styled as _, Window, canvas, div, Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _,
Styled as _, Window, canvas, div, px,
}; };
use gpui_native_core::button::{Button, ButtonVariant}; use gpui_native_core::button::{Button, ButtonVariant};
use gpui_native_core::common::{Sizable as _, v_flex}; use gpui_native_core::common::{Sizable as _, v_flex};
@@ -18,10 +19,12 @@ use gpui_native_icons::IconRole;
use gpui_native_theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size}; use gpui_native_theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size};
use gpui_native_utils::adjacent_selectable; use gpui_native_utils::adjacent_selectable;
/// The change reporter, fired with the next selected tab by pointer and keys. /// Reports the next selected tab by pointer and keys.
type ChangeHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>; type ChangeHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// The close reporter, fired with the tab's index by its close control. /// Reports the tab's index by its close control.
type CloseHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>; type CloseHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
/// Reports a tab moved from one index to another by a drag.
type ReorderHandler = Rc<dyn Fn(usize, usize, &mut Window, &mut App)>;
/// Decorates the rendered tab, e.g. to attach a drag payload. /// Decorates the rendered tab, e.g. to attach a drag payload.
type TabWrap = Box<dyn FnOnce(Stateful<Div>) -> AnyElement>; type TabWrap = Box<dyn FnOnce(Stateful<Div>) -> AnyElement>;
type TabsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<Tab>>; type TabsFn = Box<dyn Fn(&mut Window, &mut App) -> Vec<Tab>>;
@@ -48,6 +51,7 @@ struct StripMeasure {
} }
/// The capture context handed to inline tabs, only in popover mode. /// The capture context handed to inline tabs, only in popover mode.
#[derive(Clone)]
struct MeasureFrame { struct MeasureFrame {
key: MeasureKey, key: MeasureKey,
root_bounds: RootBoundsCell, root_bounds: RootBoundsCell,
@@ -79,6 +83,67 @@ impl TabsMeasurements {
} }
} }
/// Everything a tab needs to draw and interact, shared across a strip's slots.
#[derive(Clone)]
struct StripCtx {
id: ElementId,
selected: usize,
variant: TabsVariant,
on_change: Option<ChangeHandler>,
on_close: Option<CloseHandler>,
on_reorder: Option<ReorderHandler>,
focus: gpui::FocusHandle,
measure: Option<MeasureFrame>,
/// Whether tabs drag onto each other to reorder; requires `on_reorder`.
draggable: bool,
/// The tab drag gesture's live state, for the drop indicator.
drop_at: gpui::Entity<TabDrop>,
}
impl StripCtx {
/// The context for tabs drawn inside a popover: no measurement, no dragging.
fn for_popover(&self) -> Self {
Self {
measure: None,
draggable: false,
..self.clone()
}
}
}
/// The index the tab at `from` occupies once dropped before the tab at `onto`,
/// or `None` when the drop is a no-op.
fn reorder_target(from: usize, onto: usize) -> Option<usize> {
match from.cmp(&onto) {
std::cmp::Ordering::Equal => None,
std::cmp::Ordering::Less => Some(onto - 1),
std::cmp::Ordering::Greater => Some(onto),
}
}
/// Displacement before a tab drag locks to an axis: horizontal reorders,
/// vertical cancels the reorder, like a browser tab strip.
const TAB_DRAG_AXIS_LOCK: Pixels = px(6.0);
/// One tab drag gesture's live state.
#[derive(Clone, Copy, Default, PartialEq)]
struct TabDrop {
/// The tab the drag currently hovers, for the drop indicator.
onto: Option<usize>,
/// Where the drag's first move landed, anchoring the axis lock.
origin: Option<Point<Pixels>>,
/// Whether the gesture locked as a horizontal (`Some(true)`) or vertical
/// (`Some(false)`) drag; `None` until it moved [`TAB_DRAG_AXIS_LOCK`].
horizontal: Option<bool>,
}
impl TabDrop {
/// Whether the gesture locked as a vertical drag, canceling the reorder.
fn canceled(&self) -> bool {
self.horizontal == Some(false)
}
}
/// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip. /// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip.
enum StripItem { enum StripItem {
/// A tab outside any two-member kind group, at its original index. /// A tab outside any two-member kind group, at its original index.
@@ -106,6 +171,35 @@ fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId {
SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into() SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into()
} }
/// The payload dragged when reordering a tab.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TabDrag {
/// The dragged tab's index into the `tabs` vec.
pub index: usize,
}
/// The floating pill that follows the cursor while a tab is dragged.
struct TabDragPreview {
label: SharedString,
}
impl Render for TabDragPreview {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
div()
.px_2()
.py_1()
.rounded(theme.radius.control)
.border_1()
.border_color(theme.colors.border)
.bg(theme.colors.background)
.text_size(theme.sizes.medium.text_size)
.text_color(theme.colors.foreground)
.shadow(theme.elevations.control.shadows())
.child(self.label.clone())
}
}
/// The visual language of a [`Tabs`] strip. /// The visual language of a [`Tabs`] strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TabsVariant { pub enum TabsVariant {
@@ -124,6 +218,7 @@ pub struct Tab {
busy: bool, busy: bool,
disabled: bool, disabled: bool,
closeable: bool, closeable: bool,
pinned: bool,
kind: Option<SharedString>, kind: Option<SharedString>,
wrap: Option<TabWrap>, wrap: Option<TabWrap>,
} }
@@ -142,6 +237,7 @@ impl Tab {
busy: false, busy: false,
disabled: false, disabled: false,
closeable: false, closeable: false,
pinned: false,
kind: None, kind: None,
wrap: None, wrap: None,
} }
@@ -174,6 +270,12 @@ impl Tab {
self self
} }
/// Draws the tab with the active treatment at all times, selected or not.
pub fn pinned(mut self, pinned: bool) -> Self {
self.pinned = pinned;
self
}
/// Sets the kind the tab belongs to; same-kind tabs collapse into one group. /// Sets the kind the tab belongs to; same-kind tabs collapse into one group.
pub fn kind<K>(mut self, kind: K) -> Self pub fn kind<K>(mut self, kind: K) -> Self
where where
@@ -206,9 +308,11 @@ pub struct Tabs {
overflow_scroll: bool, overflow_scroll: bool,
overflow_popover: bool, overflow_popover: bool,
overflow_open: bool, overflow_open: bool,
draggable: bool,
a11y_label: Option<SharedString>, a11y_label: Option<SharedString>,
on_change: Option<ChangeHandler>, on_change: Option<ChangeHandler>,
on_close: Option<CloseHandler>, on_close: Option<CloseHandler>,
on_reorder: Option<ReorderHandler>,
on_overflow_open: Option<OpenHandler>, on_overflow_open: Option<OpenHandler>,
tabs: Option<TabsFn>, tabs: Option<TabsFn>,
} }
@@ -226,9 +330,11 @@ impl Tabs {
overflow_scroll: false, overflow_scroll: false,
overflow_popover: false, overflow_popover: false,
overflow_open: false, overflow_open: false,
draggable: false,
a11y_label: None, a11y_label: None,
on_change: None, on_change: None,
on_close: None, on_close: None,
on_reorder: None,
on_overflow_open: None, on_overflow_open: None,
tabs: None, tabs: None,
} }
@@ -264,6 +370,12 @@ impl Tabs {
self self
} }
/// Lets tabs be dragged onto each other to reorder them.
pub fn draggable(mut self, draggable: bool) -> Self {
self.draggable = draggable;
self
}
/// Reports the overflow popover's next open state, from its trigger, dismissals, and selection. /// Reports the overflow popover's next open state, from its trigger, dismissals, and selection.
pub fn on_overflow_open<F>(mut self, handler: F) -> Self pub fn on_overflow_open<F>(mut self, handler: F) -> Self
where where
@@ -291,6 +403,15 @@ impl Tabs {
self self
} }
/// Reports a tab moved by a drag.
pub fn on_reorder<F>(mut self, handler: F) -> Self
where
F: Fn(usize, usize, &mut Window, &mut App) + 'static,
{
self.on_reorder = Some(Rc::new(handler));
self
}
/// Sets the tabs; the closure runs during render and must not mutate entities or notify. /// Sets the tabs; the closure runs during render and must not mutate entities or notify.
pub fn tabs<F>(mut self, tabs: F) -> Self pub fn tabs<F>(mut self, tabs: F) -> Self
where where
@@ -325,20 +446,15 @@ impl Tabs {
count count
} }
#[allow(clippy::too_many_arguments)]
fn render_overflow_popover( fn render_overflow_popover(
id: &ElementId, ctx: &StripCtx,
overflow_items: Vec<StripItem>, overflow_items: Vec<StripItem>,
selected_index: usize,
variant: TabsVariant,
open: bool, open: bool,
on_change: Option<ChangeHandler>,
on_close: Option<CloseHandler>,
on_overflow_open: Option<OpenHandler>, on_overflow_open: Option<OpenHandler>,
focus: gpui::FocusHandle,
) -> Popover { ) -> Popover {
let id = id.clone(); let id = ctx.id.clone();
let trigger_id = id.clone(); let trigger_id = id.clone();
let on_change = ctx.on_change.clone();
let row_change: Option<ChangeHandler> = match (on_change, on_overflow_open.clone()) { let row_change: Option<ChangeHandler> = match (on_change, on_overflow_open.clone()) {
(Some(on_change), Some(dismiss)) => Some(Rc::new(move |index, window, cx| { (Some(on_change), Some(dismiss)) => Some(Rc::new(move |index, window, cx| {
@@ -351,6 +467,11 @@ impl Tabs {
(on_change, None) => on_change, (on_change, None) => on_change,
}; };
let row_ctx = StripCtx {
on_change: row_change,
..ctx.for_popover()
};
Popover::new((id.clone(), "tabs-overflow")) Popover::new((id.clone(), "tabs-overflow"))
.open(open) .open(open)
.on_change({ .on_change({
@@ -384,32 +505,13 @@ impl Tabs {
let rows: Vec<AnyElement> = overflow_items let rows: Vec<AnyElement> = overflow_items
.into_iter() .into_iter()
.flat_map(|item| match item { .flat_map(|item| match item {
StripItem::Single(index, tab) => vec![tab.render_tab( StripItem::Single(index, tab) => {
&id, vec![tab.render_tab(&row_ctx, cx, index)]
cx, }
index, // A group that ran out of room lists its members inline.
selected_index,
variant,
&row_change,
&on_close,
&focus,
None,
)],
StripItem::Group { members, .. } => members StripItem::Group { members, .. } => members
.into_iter() .into_iter()
.map(|(index, tab)| { .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index))
tab.render_tab(
&id,
cx,
index,
selected_index,
variant,
&row_change,
&on_close,
&focus,
None,
)
})
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
}) })
.collect(); .collect();
@@ -463,24 +565,18 @@ impl Tabs {
} }
/// Renders a group chip labeled with the kind and its member count. /// Renders a group chip labeled with the kind and its member count.
#[allow(clippy::too_many_arguments)]
fn render_group_tab( fn render_group_tab(
tabs_id: &ElementId, ctx: &StripCtx,
kind: SharedString, kind: SharedString,
members: Vec<(usize, Tab)>, 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, window: &mut Window,
cx: &mut App, cx: &mut App,
) -> AnyElement { ) -> AnyElement {
let tabs_id = tabs_id.clone(); let tabs_id = ctx.id.clone();
let focus = focus.clone();
let count = members.len(); let count = members.len();
let selected = members.iter().any(|(index, _)| *index == selected_index); let selected = members.iter().any(|(index, _)| *index == ctx.selected);
// A pinned member keeps the chip in the active treatment, selected or not.
let active = selected || members.iter().any(|(_, tab)| tab.pinned);
let open = window let open = window
.use_keyed_state((group_key(&tabs_id, &kind), "open"), cx, |_, _| false) .use_keyed_state((group_key(&tabs_id, &kind), "open"), cx, |_, _| false)
@@ -490,9 +586,9 @@ impl Tabs {
let metrics = theme.sizes.resolve(Size::default()); let metrics = theme.sizes.resolve(Size::default());
let small = theme.sizes.small; let small = theme.sizes.small;
let label_color = match variant { let label_color = match ctx.variant {
TabsVariant::Underline => { TabsVariant::Underline => {
if selected { if active {
theme.ramps.primary.base theme.ramps.primary.base
} else { } else {
theme.colors.foreground theme.colors.foreground
@@ -517,10 +613,10 @@ impl Tabs {
.aria_selected(selected) .aria_selected(selected)
.aria_label(SharedString::from(format!("{kind}, {count} tabs"))) .aria_label(SharedString::from(format!("{kind}, {count} tabs")))
.text_color(label_color) .text_color(label_color)
.when(!selected, |chip| { .when(!active, |chip| {
chip.hover(|chip| chip.bg(theme.colors.muted)) chip.hover(|chip| chip.bg(theme.colors.muted))
}) })
.map(|chip| match variant { .map(|chip| match ctx.variant {
TabsVariant::Underline => chip TabsVariant::Underline => chip
.px_2() .px_2()
.py_1() .py_1()
@@ -528,22 +624,22 @@ impl Tabs {
.rounded_tr(theme.radius.sm) .rounded_tr(theme.radius.sm)
.border_b_2() .border_b_2()
.border_color(gpui::transparent_black()) .border_color(gpui::transparent_black())
.when(selected, |chip| chip.border_color(theme.ramps.primary.base)), .when(active, |chip| chip.border_color(theme.ramps.primary.base)),
TabsVariant::Pill => chip TabsVariant::Pill => chip
.h(small.control_height + metrics.plate_inset * 2.0) .h(small.control_height + metrics.plate_inset * 2.0)
.px(metrics.dense_padding_x) .px(metrics.dense_padding_x)
.pr(metrics.plate_inset) .pr(metrics.plate_inset)
.rounded(theme.radius.control) .rounded(theme.radius.control)
.when(selected, |chip| { .when(active, |chip| {
chip.bg(theme.colors.background) chip.bg(theme.colors.background)
.shadow(theme.elevations.control.shadows()) .shadow(theme.elevations.control.shadows())
}), }),
}) })
.child(SharedString::from(format!("{kind} ({count})"))) .child(SharedString::from(format!("{kind} ({count})")))
.when(variant == TabsVariant::Pill, |chip| { .when(ctx.variant == TabsVariant::Pill, |chip| {
chip.child(div().flex_none().w(metrics.padding_x * 1.5)) chip.child(div().flex_none().w(metrics.padding_x * 1.5))
}) })
.when_some(measure, |chip, measure| { .when_some(ctx.measure.clone(), |chip, measure| {
let key = measure.key.clone(); let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone(); let root_bounds = measure.root_bounds.clone();
let item_key = group_key.to_string(); let item_key = group_key.to_string();
@@ -572,6 +668,7 @@ impl Tabs {
// Selecting a row also dismisses the popover, mirroring the overflow popover. // Selecting a row also dismisses the popover, mirroring the overflow popover.
let row_change: Option<ChangeHandler> = { let row_change: Option<ChangeHandler> = {
let open = open.clone(); let open = open.clone();
let on_change = ctx.on_change.clone();
Some(Rc::new(move |index, window, cx| { Some(Rc::new(move |index, window, cx| {
open.update(cx, |open, cx| { open.update(cx, |open, cx| {
*open = false; *open = false;
@@ -583,6 +680,11 @@ impl Tabs {
})) }))
}; };
let row_ctx = StripCtx {
on_change: row_change,
..ctx.for_popover()
};
Popover::new((group_key.clone(), "group-popover")) Popover::new((group_key.clone(), "group-popover"))
.open(*open.read(cx)) .open(*open.read(cx))
.on_change({ .on_change({
@@ -598,19 +700,7 @@ impl Tabs {
.content(move |_, cx| { .content(move |_, cx| {
let rows: Vec<AnyElement> = members let rows: Vec<AnyElement> = members
.into_iter() .into_iter()
.map(|(index, tab)| { .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index))
tab.render_tab(
&tabs_id,
cx,
index,
selected_index,
variant,
&row_change,
&on_close,
&focus,
None,
)
})
.collect(); .collect();
ScrollArea::new((group_key.clone(), "tabs-group-list")) ScrollArea::new((group_key.clone(), "tabs-group-list"))
@@ -681,48 +771,40 @@ impl RenderOnce for Tabs {
root_bounds: Rc::new(RefCell::new(None)), root_bounds: Rc::new(RefCell::new(None)),
}); });
let drop_at = window
.use_keyed_state((self.id.clone(), "tab-drop"), cx, |_, _| TabDrop::default())
.clone();
let ctx = StripCtx {
id: self.id.clone(),
selected: self.selected,
variant: self.variant,
on_change: self.on_change.clone(),
on_close: self.on_close.clone(),
on_reorder: self.on_reorder.clone(),
focus: focus.clone(),
measure: measure_frame.clone(),
draggable: self.draggable && self.on_reorder.is_some(),
drop_at,
};
let strip: Vec<AnyElement> = items let strip: Vec<AnyElement> = items
.into_iter() .into_iter()
.map(|item| match item { .map(|item| match item {
StripItem::Single(index, tab) => tab.render_tab( StripItem::Single(index, tab) => tab.render_tab(&ctx, cx, index),
&self.id, StripItem::Group { kind, members } => {
cx, Self::render_group_tab(&ctx, kind, members, window, cx)
index, }
self.selected,
self.variant,
&self.on_change,
&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(); .collect();
let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty()) let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty())
.then(|| { .then(|| {
Self::render_overflow_popover( Self::render_overflow_popover(
&self.id, &ctx,
overflow_items, overflow_items,
self.selected,
self.variant,
self.overflow_open, self.overflow_open,
self.on_change.clone(),
self.on_close.clone(),
self.on_overflow_open.clone(), self.on_overflow_open.clone(),
focus.clone(),
) )
}); });
@@ -755,6 +837,50 @@ impl RenderOnce for Tabs {
cx.stop_propagation(); cx.stop_propagation();
} }
}) })
.when(ctx.draggable, |root| {
root.on_drag_move::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
let position = event.event.position;
let outside = !event.bounds.contains(&position);
drop_at.update(cx, |drop, cx| {
let origin = drop.origin.get_or_insert(position);
if drop.horizontal.is_none() {
let dx = (position.x - origin.x).abs();
let dy = (position.y - origin.y).abs();
if dx.max(dy) > TAB_DRAG_AXIS_LOCK {
drop.horizontal = Some(dx >= dy);
}
}
if (outside || drop.canceled()) && drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
}
})
// A drop over the strip's gaps lands on the last hovered slot.
.on_drop::<TabDrag>({
let drop_at = ctx.drop_at.clone();
let on_reorder = ctx.on_reorder.clone();
move |drag, window, cx| {
let onto = drop_at.read(cx).onto;
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
if let (Some(onto), Some(on_reorder)) = (onto, on_reorder.as_ref())
&& !canceled
&& let Some(to) = reorder_target(drag.index, onto)
{
on_reorder(drag.index, to, window, cx);
}
}
})
})
.map(|root| match self.variant { .map(|root| match self.variant {
TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color), TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color),
TabsVariant::Pill => root.items_center().gap_1(), TabsVariant::Pill => root.items_center().gap_1(),
@@ -830,30 +956,20 @@ impl RenderOnce for Tabs {
} }
impl Tab { impl Tab {
#[allow(clippy::too_many_arguments)] fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement {
fn render_tab( let selected = index == ctx.selected;
mut self, // A pinned tab always wears the active treatment, selected or not.
tabs_id: &ElementId, let active = selected || self.pinned;
cx: &App,
index: usize,
selected_index: usize,
variant: TabsVariant,
on_change: &Option<ChangeHandler>,
on_close: &Option<CloseHandler>,
focus: &gpui::FocusHandle,
measure: Option<&MeasureFrame>,
) -> AnyElement {
let selected = index == selected_index;
let theme = cx.theme(); let theme = cx.theme();
let metrics = theme.sizes.resolve(Size::default()); let metrics = theme.sizes.resolve(Size::default());
let small = theme.sizes.small; let small = theme.sizes.small;
let label_color = match variant { let label_color = match ctx.variant {
TabsVariant::Underline => { TabsVariant::Underline => {
if self.disabled { if self.disabled {
theme.colors.muted_foreground theme.colors.muted_foreground
} else if selected { } else if active {
theme.ramps.primary.base theme.ramps.primary.base
} else { } else {
theme.colors.foreground theme.colors.foreground
@@ -868,13 +984,13 @@ impl Tab {
} }
}; };
let close = (self.closeable && on_close.is_some() && !self.disabled) let close = (self.closeable && ctx.on_close.is_some() && !self.disabled)
.then(|| self.render_tab_close(tabs_id, index, on_close)); .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close));
let strip_tab = div() let strip_tab = div()
.id((self.key.clone(), "tab")) .id((self.key.clone(), "tab"))
.debug_selector({ .debug_selector({
let tabs_id = tabs_id.clone(); let tabs_id = ctx.id.clone();
let label = self.label.clone(); let label = self.label.clone();
move || format!("{tabs_id}-tab-{}", label) move || format!("{tabs_id}-tab-{}", label)
}) })
@@ -884,10 +1000,10 @@ impl Tab {
.role(Role::Tab) .role(Role::Tab)
.aria_selected(selected) .aria_selected(selected)
.text_color(label_color) .text_color(label_color)
.when(!self.disabled && !selected, |strip_tab| { .when(!self.disabled && !active, |strip_tab| {
strip_tab.hover(|strip_tab| strip_tab.bg(theme.colors.muted)) strip_tab.hover(|strip_tab| strip_tab.bg(theme.colors.muted))
}) })
.map(|strip_tab| match variant { .map(|strip_tab| match ctx.variant {
TabsVariant::Underline => strip_tab TabsVariant::Underline => strip_tab
.px_2() .px_2()
.py_1() .py_1()
@@ -895,7 +1011,7 @@ impl Tab {
.rounded_tr(theme.radius.sm) .rounded_tr(theme.radius.sm)
.border_b_2() .border_b_2()
.border_color(gpui::transparent_black()) .border_color(gpui::transparent_black())
.when(selected, |strip_tab| { .when(active, |strip_tab| {
strip_tab.border_color(theme.ramps.primary.base) strip_tab.border_color(theme.ramps.primary.base)
}), }),
TabsVariant::Pill => strip_tab TabsVariant::Pill => strip_tab
@@ -903,9 +1019,7 @@ impl Tab {
.px(metrics.dense_padding_x) .px(metrics.dense_padding_x)
.pr(metrics.plate_inset) .pr(metrics.plate_inset)
.rounded(theme.radius.control) .rounded(theme.radius.control)
// The active tab is a small island: the panel's fill, with .when(active, |strip_tab| {
// the platform's control shadow lifting it off the strip.
.when(selected, |strip_tab| {
strip_tab strip_tab
.bg(theme.colors.background) .bg(theme.colors.background)
.shadow(theme.elevations.control.shadows()) .shadow(theme.elevations.control.shadows())
@@ -913,7 +1027,7 @@ impl Tab {
}) })
.when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead))
.child(div().flex_grow(1.0).child(self.label.clone())) .child(div().flex_grow(1.0).child(self.label.clone()))
.when(variant == TabsVariant::Pill, |strip_tab| { .when(ctx.variant == TabsVariant::Pill, |strip_tab| {
strip_tab.child(div().flex_none().w(metrics.padding_x * 1.5)) strip_tab.child(div().flex_none().w(metrics.padding_x * 1.5))
}) })
.when(self.busy && !self.disabled, |strip_tab| { .when(self.busy && !self.disabled, |strip_tab| {
@@ -924,7 +1038,25 @@ impl Tab {
) )
}) })
.when_some(close, |strip_tab, close| strip_tab.child(close)) .when_some(close, |strip_tab, close| strip_tab.child(close))
.when_some(measure, |strip_tab, measure| { .when(
{
let drop = ctx.drop_at.read(cx);
drop.onto == Some(index) && !drop.canceled()
},
|strip_tab| {
strip_tab.child(
div()
.absolute()
.left_0()
.top(px(2.0))
.bottom(px(2.0))
.w(px(2.0))
.rounded(theme.radius.sm)
.bg(theme.ramps.primary.base),
)
},
)
.when_some(ctx.measure.clone(), |strip_tab, measure| {
let key = measure.key.clone(); let key = measure.key.clone();
let root_bounds = measure.root_bounds.clone(); let root_bounds = measure.root_bounds.clone();
let tab_key = self.key.to_string(); let tab_key = self.key.to_string();
@@ -951,17 +1083,83 @@ impl Tab {
}) })
.when(!self.disabled, |strip_tab| { .when(!self.disabled, |strip_tab| {
strip_tab.cursor_pointer().on_click({ strip_tab.cursor_pointer().on_click({
let on_change = on_change.clone(); let selected = ctx.selected;
let focus = focus.clone(); let on_change = ctx.on_change.clone();
let focus = ctx.focus.clone();
move |_, window, cx| { move |_, window, cx| {
window.focus(&focus, cx); window.focus(&focus, cx);
if index != selected_index if index != selected
&& let Some(on_change) = &on_change && let Some(on_change) = &on_change
{ {
on_change(index, window, cx); on_change(index, window, cx);
} }
} }
}) })
})
.when(ctx.draggable && !self.disabled, |strip_tab| {
strip_tab
.on_mouse_down(MouseButton::Left, {
let drop_at = ctx.drop_at.clone();
move |event, _, cx| {
cx.stop_propagation();
drop_at.update(cx, |drop, cx| {
let fresh = TabDrop {
origin: Some(event.position),
..TabDrop::default()
};
if *drop != fresh {
*drop = fresh;
cx.notify();
}
});
}
})
.on_drag(TabDrag { index }, {
let label = self.label.clone();
move |_, _, _, cx| {
cx.new(|_| TabDragPreview {
label: label.clone(),
})
}
})
.drag_over::<TabDrag>({
let drop_at = ctx.drop_at.clone();
move |style, drag, _, cx| {
let drop = *drop_at.read(cx);
let hovered = drag.index != index && !drop.canceled();
drop_at.update(cx, |drop, cx| match (hovered, drop.onto) {
(true, current) if current != Some(index) => {
drop.onto = Some(index);
cx.notify();
}
(false, Some(_)) => {
drop.onto = None;
cx.notify();
}
_ => {}
});
style
}
})
.on_drop::<TabDrag>({
let on_reorder = ctx.on_reorder.clone();
let drop_at = ctx.drop_at.clone();
move |drag, window, cx| {
let canceled = drop_at.read(cx).canceled();
drop_at.update(cx, |drop, cx| {
if drop.onto.is_some() {
drop.onto = None;
cx.notify();
}
});
let target = (!canceled)
.then(|| reorder_target(drag.index, index))
.flatten();
if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) {
on_reorder(drag.index, to, window, cx);
}
}
})
}); });
match self.wrap { match self.wrap {
+180 -15
View File
@@ -1,44 +1,64 @@
#![cfg(feature = "tabs")] #![cfg(feature = "tabs")]
//! Grouped tabs: same-kind tabs collapse into one chip that opens a popover //! Grouped tabs: same-kind tabs collapse into one chip that opens a popover
//! listing the members; picking one selects it by its original index. //! listing the members; picking one selects it by its original index. Tabs
//! also drag onto each other to reorder, and pinned tabs wear the active
//! treatment at all times.
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use gpui::{ use gpui::{
Context, IntoElement, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, Context, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
VisualTestContext, Window, div, px, size, ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, div, point,
px, size,
}; };
use gpui_native_data::tabs::{Tab, Tabs, TabsVariant}; use gpui_native_data::tabs::{Tab, Tabs, TabsVariant};
use gpui_native_theme::Theme; use gpui_native_theme::Theme;
struct StripHarness { struct StripHarness {
changed: Rc<RefCell<Vec<usize>>>, changed: Rc<RefCell<Vec<usize>>>,
reordered: Rc<RefCell<Vec<(usize, usize)>>>,
pinned: bool,
} }
impl Render for StripHarness { impl Render for StripHarness {
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 changed = self.changed.clone(); let changed = self.changed.clone();
let reordered = self.reordered.clone();
div().size_full().child( div().size_full().child(
Tabs::new("strip") Tabs::new("strip")
.variant(TabsVariant::Pill) .variant(TabsVariant::Pill)
.tabs(|_, _| { .draggable(true)
vec![ .tabs({
Tab::new("a", "Alpha").kind("Kind"), let pinned = self.pinned;
Tab::new("b", "Beta").kind("Kind"), move |_, _| {
Tab::new("c", "Gamma"), vec![
Tab::new("d", "Delta").kind("Lone"), Tab::new("a", "Alpha").kind("Kind"),
] Tab::new("b", "Beta").kind("Kind"),
Tab::new("c", "Gamma"),
Tab::new("d", "Delta").kind("Lone").pinned(pinned),
]
}
}) })
.on_change(move |index, _, _| changed.borrow_mut().push(index)), .on_change(move |index, _, _| changed.borrow_mut().push(index))
.on_reorder(move |from, to, _, _| reordered.borrow_mut().push((from, to))),
) )
} }
} }
fn strip_window(cx: &mut TestAppContext, changed: Rc<RefCell<Vec<usize>>>) -> VisualTestContext { fn strip_window(
cx: &mut TestAppContext,
changed: Rc<RefCell<Vec<usize>>>,
reordered: Rc<RefCell<Vec<(usize, usize)>>>,
pinned: bool,
) -> VisualTestContext {
cx.update(Theme::init); cx.update(Theme::init);
let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness { changed }); let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness {
changed,
reordered,
pinned,
});
let cx = VisualTestContext::from_window(window.into(), cx); let cx = VisualTestContext::from_window(window.into(), cx);
cx.run_until_parked(); cx.run_until_parked();
cx cx
@@ -46,7 +66,12 @@ fn strip_window(cx: &mut TestAppContext, changed: Rc<RefCell<Vec<usize>>>) -> Vi
#[gpui::test] #[gpui::test]
fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) { fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) {
let mut cx = strip_window(cx, Rc::new(RefCell::new(Vec::new()))); let mut cx = strip_window(
cx,
Rc::new(RefCell::new(Vec::new())),
Rc::new(RefCell::new(Vec::new())),
false,
);
assert!( assert!(
cx.debug_bounds("strip-group-Kind").is_some(), cx.debug_bounds("strip-group-Kind").is_some(),
@@ -70,7 +95,12 @@ fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) {
#[gpui::test] #[gpui::test]
fn picking_a_group_member_selects_it(cx: &mut TestAppContext) { fn picking_a_group_member_selects_it(cx: &mut TestAppContext) {
let changed = Rc::new(RefCell::new(Vec::new())); let changed = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(cx, changed.clone()); let mut cx = strip_window(
cx,
changed.clone(),
Rc::new(RefCell::new(Vec::new())),
false,
);
let chip = cx let chip = cx
.debug_bounds("strip-group-Kind") .debug_bounds("strip-group-Kind")
@@ -94,3 +124,138 @@ fn picking_a_group_member_selects_it(cx: &mut TestAppContext) {
"a selection dismisses the popover" "a selection dismisses the popover"
); );
} }
#[gpui::test]
fn dragging_a_tab_onto_another_reorders_it(cx: &mut TestAppContext) {
let reordered = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(
cx,
Rc::new(RefCell::new(Vec::new())),
reordered.clone(),
false,
);
// The strip's group chip hides Alpha and Beta; Gamma draws inline, so the
// drag runs from Gamma onto Delta: moving Gamma before Delta is a no-op
// shift — use Delta onto Gamma instead, reporting (3, 2).
let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn");
let delta = cx.debug_bounds("strip-tab-Delta").expect("delta drawn");
cx.simulate_event(MouseDownEvent {
position: delta.center(),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
});
cx.simulate_event(MouseMoveEvent {
position: gamma.center(),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
cx.simulate_event(MouseUpEvent {
position: gamma.center(),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
});
cx.run_until_parked();
assert_eq!(
reordered.borrow().as_slice(),
&[(3, 2)],
"dropping Delta before Gamma reports the move"
);
}
#[gpui::test]
fn dropping_a_tab_back_on_itself_reorders_nothing(cx: &mut TestAppContext) {
let reordered = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(
cx,
Rc::new(RefCell::new(Vec::new())),
reordered.clone(),
false,
);
let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn");
cx.simulate_event(MouseDownEvent {
position: gamma.center(),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
});
cx.simulate_event(MouseMoveEvent {
position: gamma.center() + point(px(2.0), px(0.0)),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
cx.simulate_event(MouseUpEvent {
position: gamma.center(),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
});
cx.run_until_parked();
assert!(
reordered.borrow().is_empty(),
"a self-drop is a no-op, not a reorder"
);
}
#[gpui::test]
fn a_vertical_drag_cancels_the_reorder(cx: &mut TestAppContext) {
let reordered = Rc::new(RefCell::new(Vec::new()));
let mut cx = strip_window(
cx,
Rc::new(RefCell::new(Vec::new())),
reordered.clone(),
false,
);
// Drag Delta straight down past the axis lock, then back onto Gamma:
// the gesture locked vertical, so the drop must not reorder.
let delta = cx.debug_bounds("strip-tab-Delta").expect("delta drawn");
let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn");
let start = delta.center();
cx.simulate_event(MouseDownEvent {
position: start,
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
});
// The drag engages a few pixels down; land the origin there.
cx.simulate_event(MouseMoveEvent {
position: start + point(px(0.0), px(3.0)),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
// Past the axis lock, vertically: dy 30 vs dx 0.
cx.simulate_event(MouseMoveEvent {
position: start + point(px(0.0), px(30.0)),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
// Back over Gamma — still canceled.
cx.simulate_event(MouseMoveEvent {
position: gamma.center(),
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
});
cx.simulate_event(MouseUpEvent {
position: gamma.center(),
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
});
cx.run_until_parked();
assert!(
reordered.borrow().is_empty(),
"a vertical drag never reorders, even dropped on another tab"
);
}
+4 -6
View File
@@ -198,12 +198,10 @@ Gaps surfaced by the signed comparison; ordered by signed's usage.
### data (`crates/data`) ### data (`crates/data`)
- [x] List, Tree, Tabs (underline default + signed pill), Sidebar (scrolls - [x] List, Tree, Tabs (underline default + signed pill), Sidebar (scrolls
internally) internally); tab kind groups collapse into one chip that opens a
- [x] Tab kind groups — tabs carrying the same `Tab::kind` (two or more) popover of the members, tabs drag onto each other to reorder
collapse into one chip labeled with the kind and its member count; (`draggable` + `on_reorder`), and `Tab::pinned` tabs wear the active
clicking it opens a popover listing the members vertically, and picking treatment at all times
one reports its original index through `on_change`/`on_close`; lone
kinded tabs stay inline, and the chip composes with both overflow modes
### editor (`crates/editor`) ### editor (`crates/editor`)
+23 -1
View File
@@ -288,6 +288,15 @@ impl Gallery {
.variant(TabsVariant::Pill) .variant(TabsVariant::Pill)
.overflow_scroll(true) .overflow_scroll(true)
.selected(selected) .selected(selected)
.draggable(true)
.on_reorder({
let gallery = gallery.clone();
move |from, to, _, cx| {
gallery
.update(cx, |gallery, cx| gallery.reorder_demo(from, to, cx))
.log_err();
}
})
.tabs({ .tabs({
let tabs = self.tabs.clone(); let tabs = self.tabs.clone();
let kinds: Vec<Option<SharedString>> = self let kinds: Vec<Option<SharedString>> = self
@@ -299,7 +308,9 @@ impl Gallery {
tabs.iter() tabs.iter()
.zip(kinds.iter()) .zip(kinds.iter())
.map(|(id, kind)| { .map(|(id, kind)| {
let tab = Tab::new(id.clone(), Self::label_of(id)).closeable(true); let tab = Tab::new(id.clone(), Self::label_of(id))
.closeable(true)
.pinned(id.as_ref() == "welcome");
match kind { match kind {
Some(kind) => tab.kind(kind.clone()), Some(kind) => tab.kind(kind.clone()),
None => tab, None => tab,
@@ -458,6 +469,17 @@ impl Gallery {
cx.notify(); cx.notify();
} }
/// Moves the demo tab at `from` to occupy `to`, both indices into the
/// open tabs as they were before the move.
fn reorder_demo(&mut self, from: usize, to: usize, cx: &mut Context<Self>) {
if from >= self.tabs.len() || to >= self.tabs.len() || from == to {
return;
}
let tab = self.tabs.remove(from);
self.tabs.insert(to, tab);
cx.notify();
}
/// Creates the view behind a demo tab. /// Creates the view behind a demo tab.
fn create_view( fn create_view(
&self, &self,