From 4f67f9e1c226205cc14dfb52102ad4cee9d843bc Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Sun, 15 Nov 2026 16:14:28 +0700 Subject: [PATCH] tabs: add drag-to-reorder and pinned tabs --- crates/data/src/tabs.rs | 456 +++++++++++++++++++++++++---------- crates/data/tests/tabs.rs | 195 +++++++++++++-- docs/CHECKLIST.md | 10 +- examples/gallery/src/main.rs | 24 +- 4 files changed, 534 insertions(+), 151 deletions(-) diff --git a/crates/data/src/tabs.rs b/crates/data/src/tabs.rs index 3228a35..0739d78 100644 --- a/crates/data/src/tabs.rs +++ b/crates/data/src/tabs.rs @@ -4,9 +4,10 @@ use std::rc::Rc; use gpui::prelude::FluentBuilder; use gpui::{ - 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, + AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, + 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::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_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; -/// 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; +/// Reports a tab moved from one index to another by a drag. +type ReorderHandler = Rc; /// Decorates the rendered tab, e.g. to attach a drag payload. type TabWrap = Box) -> AnyElement>; type TabsFn = Box Vec>; @@ -48,6 +51,7 @@ struct StripMeasure { } /// The capture context handed to inline tabs, only in popover mode. +#[derive(Clone)] struct MeasureFrame { key: MeasureKey, 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, + on_close: Option, + on_reorder: Option, + focus: gpui::FocusHandle, + measure: Option, + /// 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, +} + +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 { + 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, + /// Where the drag's first move landed, anchoring the axis lock. + origin: Option>, + /// Whether the gesture locked as a horizontal (`Some(true)`) or vertical + /// (`Some(false)`) drag; `None` until it moved [`TAB_DRAG_AXIS_LOCK`]. + horizontal: Option, +} + +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. enum StripItem { /// 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() } +/// 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) -> 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. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TabsVariant { @@ -124,6 +218,7 @@ pub struct Tab { busy: bool, disabled: bool, closeable: bool, + pinned: bool, kind: Option, wrap: Option, } @@ -142,6 +237,7 @@ impl Tab { busy: false, disabled: false, closeable: false, + pinned: false, kind: None, wrap: None, } @@ -174,6 +270,12 @@ impl Tab { 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. pub fn kind(mut self, kind: K) -> Self where @@ -206,9 +308,11 @@ pub struct Tabs { overflow_scroll: bool, overflow_popover: bool, overflow_open: bool, + draggable: bool, a11y_label: Option, on_change: Option, on_close: Option, + on_reorder: Option, on_overflow_open: Option, tabs: Option, } @@ -226,9 +330,11 @@ impl Tabs { overflow_scroll: false, overflow_popover: false, overflow_open: false, + draggable: false, a11y_label: None, on_change: None, on_close: None, + on_reorder: None, on_overflow_open: None, tabs: None, } @@ -264,6 +370,12 @@ impl Tabs { 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. pub fn on_overflow_open(mut self, handler: F) -> Self where @@ -291,6 +403,15 @@ impl Tabs { self } + /// Reports a tab moved by a drag. + pub fn on_reorder(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. pub fn tabs(mut self, tabs: F) -> Self where @@ -325,20 +446,15 @@ impl Tabs { count } - #[allow(clippy::too_many_arguments)] fn render_overflow_popover( - id: &ElementId, + ctx: &StripCtx, overflow_items: Vec, - 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 id = ctx.id.clone(); let trigger_id = id.clone(); + let on_change = ctx.on_change.clone(); let row_change: Option = match (on_change, on_overflow_open.clone()) { (Some(on_change), Some(dismiss)) => Some(Rc::new(move |index, window, cx| { @@ -351,6 +467,11 @@ impl Tabs { (on_change, None) => on_change, }; + let row_ctx = StripCtx { + on_change: row_change, + ..ctx.for_popover() + }; + Popover::new((id.clone(), "tabs-overflow")) .open(open) .on_change({ @@ -384,32 +505,13 @@ impl Tabs { let rows: Vec = overflow_items .into_iter() .flat_map(|item| match item { - StripItem::Single(index, tab) => vec![tab.render_tab( - &id, - cx, - index, - selected_index, - variant, - &row_change, - &on_close, - &focus, - None, - )], + StripItem::Single(index, tab) => { + vec![tab.render_tab(&row_ctx, cx, index)] + } + // A group that ran out of room lists its members inline. StripItem::Group { members, .. } => members .into_iter() - .map(|(index, tab)| { - tab.render_tab( - &id, - cx, - index, - selected_index, - variant, - &row_change, - &on_close, - &focus, - None, - ) - }) + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) .collect::>(), }) .collect(); @@ -463,24 +565,18 @@ impl Tabs { } /// Renders a group chip labeled with the kind and its member count. - #[allow(clippy::too_many_arguments)] fn render_group_tab( - tabs_id: &ElementId, + ctx: &StripCtx, kind: SharedString, members: Vec<(usize, Tab)>, - selected_index: usize, - variant: TabsVariant, - on_change: Option, - on_close: Option, - focus: &gpui::FocusHandle, - measure: Option<&MeasureFrame>, window: &mut Window, cx: &mut App, ) -> AnyElement { - let tabs_id = tabs_id.clone(); - let focus = focus.clone(); + let tabs_id = ctx.id.clone(); 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 .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 small = theme.sizes.small; - let label_color = match variant { + let label_color = match ctx.variant { TabsVariant::Underline => { - if selected { + if active { theme.ramps.primary.base } else { theme.colors.foreground @@ -517,10 +613,10 @@ impl Tabs { .aria_selected(selected) .aria_label(SharedString::from(format!("{kind}, {count} tabs"))) .text_color(label_color) - .when(!selected, |chip| { + .when(!active, |chip| { chip.hover(|chip| chip.bg(theme.colors.muted)) }) - .map(|chip| match variant { + .map(|chip| match ctx.variant { TabsVariant::Underline => chip .px_2() .py_1() @@ -528,22 +624,22 @@ impl Tabs { .rounded_tr(theme.radius.sm) .border_b_2() .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 .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| { + .when(active, |chip| { chip.bg(theme.colors.background) .shadow(theme.elevations.control.shadows()) }), }) .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)) }) - .when_some(measure, |chip, measure| { + .when_some(ctx.measure.clone(), |chip, measure| { let key = measure.key.clone(); let root_bounds = measure.root_bounds.clone(); let item_key = group_key.to_string(); @@ -572,6 +668,7 @@ impl Tabs { // Selecting a row also dismisses the popover, mirroring the overflow popover. let row_change: Option = { let open = open.clone(); + let on_change = ctx.on_change.clone(); Some(Rc::new(move |index, window, cx| { open.update(cx, |open, cx| { *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")) .open(*open.read(cx)) .on_change({ @@ -598,19 +700,7 @@ impl Tabs { .content(move |_, cx| { let rows: Vec = members .into_iter() - .map(|(index, tab)| { - tab.render_tab( - &tabs_id, - cx, - index, - selected_index, - variant, - &row_change, - &on_close, - &focus, - None, - ) - }) + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) .collect(); ScrollArea::new((group_key.clone(), "tabs-group-list")) @@ -681,48 +771,40 @@ impl RenderOnce for Tabs { 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 = items .into_iter() .map(|item| match item { - StripItem::Single(index, tab) => tab.render_tab( - &self.id, - 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, - ), + StripItem::Single(index, tab) => tab.render_tab(&ctx, cx, index), + StripItem::Group { kind, members } => { + Self::render_group_tab(&ctx, kind, members, window, cx) + } }) .collect(); let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty()) .then(|| { Self::render_overflow_popover( - &self.id, + &ctx, overflow_items, - self.selected, - self.variant, self.overflow_open, - self.on_change.clone(), - self.on_close.clone(), self.on_overflow_open.clone(), - focus.clone(), ) }); @@ -755,6 +837,50 @@ impl RenderOnce for Tabs { cx.stop_propagation(); } }) + .when(ctx.draggable, |root| { + root.on_drag_move::({ + 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::({ + 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 { TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color), TabsVariant::Pill => root.items_center().gap_1(), @@ -830,30 +956,20 @@ impl RenderOnce for Tabs { } impl Tab { - #[allow(clippy::too_many_arguments)] - fn render_tab( - mut self, - tabs_id: &ElementId, - cx: &App, - index: usize, - selected_index: usize, - variant: TabsVariant, - on_change: &Option, - on_close: &Option, - focus: &gpui::FocusHandle, - measure: Option<&MeasureFrame>, - ) -> AnyElement { - let selected = index == selected_index; + fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { + let selected = index == ctx.selected; + // A pinned tab always wears the active treatment, selected or not. + let active = selected || self.pinned; let theme = cx.theme(); let metrics = theme.sizes.resolve(Size::default()); let small = theme.sizes.small; - let label_color = match variant { + let label_color = match ctx.variant { TabsVariant::Underline => { if self.disabled { theme.colors.muted_foreground - } else if selected { + } else if active { theme.ramps.primary.base } else { theme.colors.foreground @@ -868,13 +984,13 @@ impl Tab { } }; - let close = (self.closeable && on_close.is_some() && !self.disabled) - .then(|| self.render_tab_close(tabs_id, index, on_close)); + let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) + .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); let strip_tab = div() .id((self.key.clone(), "tab")) .debug_selector({ - let tabs_id = tabs_id.clone(); + let tabs_id = ctx.id.clone(); let label = self.label.clone(); move || format!("{tabs_id}-tab-{}", label) }) @@ -884,10 +1000,10 @@ impl Tab { .role(Role::Tab) .aria_selected(selected) .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)) }) - .map(|strip_tab| match variant { + .map(|strip_tab| match ctx.variant { TabsVariant::Underline => strip_tab .px_2() .py_1() @@ -895,7 +1011,7 @@ impl Tab { .rounded_tr(theme.radius.sm) .border_b_2() .border_color(gpui::transparent_black()) - .when(selected, |strip_tab| { + .when(active, |strip_tab| { strip_tab.border_color(theme.ramps.primary.base) }), TabsVariant::Pill => strip_tab @@ -903,9 +1019,7 @@ impl Tab { .px(metrics.dense_padding_x) .pr(metrics.plate_inset) .rounded(theme.radius.control) - // 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| { + .when(active, |strip_tab| { strip_tab .bg(theme.colors.background) .shadow(theme.elevations.control.shadows()) @@ -913,7 +1027,7 @@ impl Tab { }) .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) .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)) }) .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(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 root_bounds = measure.root_bounds.clone(); let tab_key = self.key.to_string(); @@ -951,17 +1083,83 @@ impl Tab { }) .when(!self.disabled, |strip_tab| { strip_tab.cursor_pointer().on_click({ - let on_change = on_change.clone(); - let focus = focus.clone(); + let selected = ctx.selected; + let on_change = ctx.on_change.clone(); + let focus = ctx.focus.clone(); move |_, window, cx| { window.focus(&focus, cx); - if index != selected_index + if index != selected && let Some(on_change) = &on_change { 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::({ + 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::({ + 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 { diff --git a/crates/data/tests/tabs.rs b/crates/data/tests/tabs.rs index 75b0184..1b0f49a 100644 --- a/crates/data/tests/tabs.rs +++ b/crates/data/tests/tabs.rs @@ -1,44 +1,64 @@ #![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. +//! 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::rc::Rc; use gpui::{ - Context, IntoElement, Modifiers, ParentElement as _, Render, Styled as _, TestAppContext, - VisualTestContext, Window, div, px, size, + Context, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, div, point, + px, size, }; use gpui_native_data::tabs::{Tab, Tabs, TabsVariant}; use gpui_native_theme::Theme; struct StripHarness { changed: Rc>>, + reordered: Rc>>, + pinned: bool, } impl Render for StripHarness { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { let changed = self.changed.clone(); + let reordered = self.reordered.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"), - ] + .draggable(true) + .tabs({ + let pinned = self.pinned; + move |_, _| { + vec![ + 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>>) -> VisualTestContext { +fn strip_window( + cx: &mut TestAppContext, + changed: Rc>>, + reordered: Rc>>, + pinned: bool, +) -> VisualTestContext { 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); cx.run_until_parked(); cx @@ -46,7 +66,12 @@ fn strip_window(cx: &mut TestAppContext, changed: Rc>>) -> Vi #[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()))); + let mut cx = strip_window( + cx, + Rc::new(RefCell::new(Vec::new())), + Rc::new(RefCell::new(Vec::new())), + false, + ); assert!( 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] 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 mut cx = strip_window( + cx, + changed.clone(), + Rc::new(RefCell::new(Vec::new())), + false, + ); let chip = cx .debug_bounds("strip-group-Kind") @@ -94,3 +124,138 @@ fn picking_a_group_member_selects_it(cx: &mut TestAppContext) { "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" + ); +} diff --git a/docs/CHECKLIST.md b/docs/CHECKLIST.md index f807742..8fe595e 100644 --- a/docs/CHECKLIST.md +++ b/docs/CHECKLIST.md @@ -198,12 +198,10 @@ Gaps surfaced by the signed comparison; ordered by signed's usage. ### data (`crates/data`) - [x] List, Tree, Tabs (underline default + signed pill), Sidebar (scrolls - internally) -- [x] Tab kind groups — tabs carrying the same `Tab::kind` (two or more) - collapse into one chip labeled with the kind and its member count; - clicking it opens a popover listing the members vertically, and picking - one reports its original index through `on_change`/`on_close`; lone - kinded tabs stay inline, and the chip composes with both overflow modes + internally); tab kind groups collapse into one chip that opens a + popover of the members, tabs drag onto each other to reorder + (`draggable` + `on_reorder`), and `Tab::pinned` tabs wear the active + treatment at all times ### editor (`crates/editor`) diff --git a/examples/gallery/src/main.rs b/examples/gallery/src/main.rs index c7e7616..74f02bf 100644 --- a/examples/gallery/src/main.rs +++ b/examples/gallery/src/main.rs @@ -288,6 +288,15 @@ impl Gallery { .variant(TabsVariant::Pill) .overflow_scroll(true) .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({ let tabs = self.tabs.clone(); let kinds: Vec> = self @@ -299,7 +308,9 @@ impl Gallery { tabs.iter() .zip(kinds.iter()) .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 { Some(kind) => tab.kind(kind.clone()), None => tab, @@ -458,6 +469,17 @@ impl Gallery { 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) { + 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. fn create_view( &self,