diff --git a/packages/frontend/desktop/src/workbench/topbar/tabs/drag.rs b/packages/frontend/desktop/src/workbench/topbar/tabs/drag.rs new file mode 100644 index 0000000000..c07fb22836 --- /dev/null +++ b/packages/frontend/desktop/src/workbench/topbar/tabs/drag.rs @@ -0,0 +1,489 @@ +//! Horizontal drag-reordering of app tabs within their pinned or unpinned section. + +use std::{cell::Cell, ops::Range, rc::Rc}; + +use ui::{ + AnyElement, App, DispatchPhase, Entity, FocusHandle, InteractiveElement, IntoElement, + KeyDownEvent, MouseButton, MouseMoveEvent, MouseUpEvent, Styled, Window, div, px, +}; + +use crate::split_view::{SplitLayout, TabItem}; + +use super::{ + DesktopPalette, DesktopShellView, StripLayout, TAB_GAP, TAB_HEIGHT, TAB_RING, TabStripScroll, +}; + +const DRAG_THRESHOLD: f32 = 6.0; +const DROP_INDICATOR_WIDTH: f32 = 2.0; + +#[derive(Clone, Copy, Default)] +pub(super) struct StripBounds { + pub(super) origin_x: f32, + pub(super) top: f32, + pub(super) bottom: f32, +} + +impl StripBounds { + pub(super) fn contains_y(self, y: f32) -> bool { + self.bottom > self.top && (self.top..=self.bottom).contains(&y) + } +} + +#[derive(Clone)] +pub(super) struct TabDrag { + pub(super) tab_id: u64, + origin_x: f32, + pub(super) active: bool, + pub(super) canceled: bool, + pub(super) drop_index: Option, + in_spacer: bool, + previous_focus: Option, +} + +impl TabDrag { + pub(super) fn new(tab_id: u64, origin_x: f32) -> Self { + Self { + tab_id, + origin_x, + active: false, + canceled: false, + drop_index: None, + in_spacer: false, + previous_focus: None, + } + } + + pub(super) fn is_active(&self) -> bool { + self.active && !self.canceled + } +} + +fn section_bounds(tabs: &[TabItem], tab_index: usize) -> Range { + let pinned_count = tabs.iter().take_while(|tab| tab.pinned).count(); + if tabs[tab_index].pinned { + 0..pinned_count + } else { + pinned_count..tabs.len() + } +} + +/// Computes the insertion index within the dragged tab's pinned or unpinned section, +/// or `None` when dropping at `insert_at` would leave the tab order unchanged. +pub(super) fn drop_insertion_index( + layout: &StripLayout, + tabs: &[TabItem], + from_index: usize, + content_x: f32, +) -> Option { + let section = section_bounds(tabs, from_index); + if section.len() <= 1 { + return None; + } + let (mut low, mut high) = (section.start, section.end); + while low < high { + let mid = (low + high) / 2; + let (x, width) = layout.span(mid); + if content_x < x + width * 0.5 { + high = mid; + } else { + low = mid + 1; + } + } + if low == from_index || low == from_index + 1 { + None + } else { + Some(low) + } +} + +/// Computes the `left` offset of the `2px` drop indicator inside `desktop.app_tabs.labels` +/// (before subtracting `scroll_x`). +pub(super) fn drop_indicator_x(layout: &StripLayout, from_pinned: bool, insert_at: usize) -> f32 { + let total = layout.count(); + let pinned_count = layout.pinned.len(); + if insert_at == 0 || (insert_at == pinned_count && !from_pinned && layout.separator().is_none()) + { + 0.0 + } else if insert_at == total { + let (x, width) = layout.span(total - 1); + TAB_RING + x + width - DROP_INDICATOR_WIDTH / 2.0 + } else if insert_at == pinned_count && !from_pinned { + let (x, _) = layout.span(pinned_count); + TAB_RING + x - TAB_GAP + (TAB_GAP - DROP_INDICATOR_WIDTH) / 2.0 + } else { + let (x, width) = layout.span(insert_at - 1); + TAB_RING + x + width + (TAB_GAP - DROP_INDICATOR_WIDTH) / 2.0 + } +} + +/// Moves `tab_id` to `insert_at` (clamped inside its pinned/unpinned section) while keeping +/// the active tab ID and split panes unchanged. Returns `true` if the order changed. +pub(super) fn move_app_tab(split: &mut SplitLayout, tab_id: u64, insert_at: usize) -> bool { + let pane = &mut split.panes[0]; + let Some(from_index) = pane.tab_index(tab_id) else { + return false; + }; + let section = section_bounds(&pane.tabs, from_index); + let insert_at = insert_at.clamp(section.start, section.end); + if insert_at == from_index || insert_at == from_index + 1 { + return false; + } + let active_id = pane.active_tab().id; + let tab = pane.tabs.remove(from_index); + let target_index = if from_index < insert_at { + insert_at - 1 + } else { + insert_at + }; + pane.tabs.insert(target_index, tab); + pane.active_tab = pane.tab_index(active_id).unwrap_or(0); + true +} + +pub(super) fn render_drop_indicator( + layout: &StripLayout, + drag: &TabDrag, + tabs: &[TabItem], + scroll_x: f32, + palette: DesktopPalette, +) -> Option { + if !drag.is_active() { + return None; + } + let insert_at = drag.drop_index?; + let from_pinned = tabs.iter().find(|tab| tab.id == drag.tab_id)?.pinned; + let left = drop_indicator_x(layout, from_pinned, insert_at) - scroll_x; + Some( + div() + .id("desktop.app_tabs.drop_indicator") + .snapshot( + ui::snap_id!("desktop.app_tabs.drop_indicator"), + Some("desktop.app_tabs"), + ) + .absolute() + .top(px(0.0)) + .left(px(left)) + .w(px(DROP_INDICATOR_WIDTH)) + .h(px(TAB_HEIGHT + 2.0 * TAB_RING)) + .rounded(px(DROP_INDICATOR_WIDTH)) + .bg(palette.accent) + .into_any_element(), + ) +} + +fn restore_focus( + previous_focus: Option, + drag_focus: &FocusHandle, + shell_entity: &Entity, + window: &mut Window, + app: &mut App, +) { + if drag_focus.is_focused(window) { + let target = previous_focus.unwrap_or_else(|| shell_entity.read(app).focus_handle.clone()); + window.focus(&target, app); + } +} + +pub(super) fn cancel_on_escape( + event: &KeyDownEvent, + state: &Entity, + shell_entity: &Entity, + window: &mut Window, + app: &mut App, +) { + if event.keystroke.key != "escape" + || !state + .read(app) + .drag + .as_ref() + .is_some_and(TabDrag::is_active) + { + return; + } + let (drag_focus, previous_focus) = state.update(app, |stored, cx| { + let previous = stored.drag.as_mut().and_then(|drag| { + drag.active = false; + drag.canceled = true; + drag.drop_index = None; + drag.in_spacer = false; + drag.previous_focus.take() + }); + cx.notify(); + (stored.drag_focus.clone(), previous) + }); + restore_focus(previous_focus, &drag_focus, shell_entity, window, app); + window.prevent_default(); + app.stop_propagation(); +} + +/// Updates `(drop_index, in_spacer)` following JS `0.27.5-beta.4` `useDropTarget` rules: +/// tabs are `isSticky: true`, the trailing spacer is non-sticky, and moving outside the strip +/// never recalculates `drop_index` from `pointer_x`. +#[allow(clippy::too_many_arguments)] +fn next_drop_target( + split: &SplitLayout, + tab_id: u64, + pointer_x: f32, + pointer_y: f32, + bounds: StripBounds, + scroll_x: f32, + current_drop: Option, + was_in_spacer: bool, +) -> Option<(Option, bool)> { + let pane = &split.panes[0]; + let from_index = pane.tab_index(tab_id)?; + if !bounds.contains_y(pointer_y) { + return Some(if was_in_spacer { + (None, false) + } else { + (current_drop, false) + }); + } + let layout = StripLayout::new(split); + let content_x = pointer_x - bounds.origin_x - TAB_RING + scroll_x; + if content_x < 0.0 { + return Some(if was_in_spacer { + (None, false) + } else { + (current_drop, false) + }); + } + let in_spacer = content_x > layout.content_width(); + let drop_index = drop_insertion_index(&layout, &pane.tabs, from_index, content_x); + Some((drop_index, in_spacer)) +} + +pub(super) fn register_window_drag_listeners( + window: &mut Window, + state: Entity, + shell_entity: Entity, + strip_bounds: Rc>, +) { + let move_state = state.clone(); + let move_shell = shell_entity.clone(); + let move_bounds = strip_bounds.clone(); + window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, app| { + if phase != DispatchPhase::Capture || move_state.read(app).drag.is_none() { + return; + } + if event.pressed_button != Some(MouseButton::Left) { + let (drag_focus, previous_focus) = move_state.update(app, |stored, cx| { + let previous = stored.drag.take().and_then(|drag| drag.previous_focus); + cx.notify(); + (stored.drag_focus.clone(), previous) + }); + restore_focus(previous_focus, &drag_focus, &move_shell, window, app); + return; + } + let pointer_x = f32::from(event.position.x); + let pointer_y = f32::from(event.position.y); + let ( + tab_id, + origin_x, + was_active, + canceled, + current_drop, + was_in_spacer, + scroll_x, + drag_focus, + ) = { + let stored = move_state.read(app); + let Some(drag) = &stored.drag else { + return; + }; + ( + drag.tab_id, + drag.origin_x, + drag.active, + drag.canceled, + drag.drop_index, + drag.in_spacer, + stored.scroll_x, + stored.drag_focus.clone(), + ) + }; + if canceled { + app.stop_propagation(); + return; + } + let active = was_active || (pointer_x - origin_x).abs() > DRAG_THRESHOLD; + if !active { + return; + } + let Some((drop_index, in_spacer)) = next_drop_target( + &move_shell.read(app).state.split, + tab_id, + pointer_x, + pointer_y, + move_bounds.get(), + scroll_x, + current_drop, + was_in_spacer, + ) else { + let previous = move_state.update(app, |stored, cx| { + cx.notify(); + stored.drag.take().and_then(|drag| drag.previous_focus) + }); + restore_focus(previous, &drag_focus, &move_shell, window, app); + return; + }; + let previous_focus = if !was_active { + let prev = window.focused(app); + window.focus(&drag_focus, app); + prev + } else { + None + }; + move_state.update(app, |stored, cx| { + if let Some(drag) = &mut stored.drag { + let changed = !drag.active || drag.drop_index != drop_index; + if !drag.active { + drag.previous_focus = previous_focus; + } + drag.active = true; + drag.drop_index = drop_index; + drag.in_spacer = in_spacer; + if changed { + cx.notify(); + } + } + }); + app.stop_propagation(); + }); + + window.on_mouse_event(move |event: &MouseUpEvent, phase, window, app| { + if phase != DispatchPhase::Capture + || event.button != MouseButton::Left + || state.read(app).drag.is_none() + { + return; + } + let (drag, drag_focus, scroll_x) = state.update(app, |stored, _| { + ( + stored.drag.take(), + stored.drag_focus.clone(), + stored.scroll_x, + ) + }); + let Some(mut drag) = drag else { + return; + }; + if !drag.active && !drag.canceled { + return; + } + let previous_focus = drag.previous_focus.take(); + restore_focus(previous_focus, &drag_focus, &shell_entity, window, app); + if drag.active && !drag.canceled { + let pointer_x = f32::from(event.position.x); + let pointer_y = f32::from(event.position.y); + let bounds = strip_bounds.get(); + shell_entity.update(app, |shell, cx| { + if let Some((Some(insert_at), _)) = next_drop_target( + &shell.state.split, + drag.tab_id, + pointer_x, + pointer_y, + bounds, + scroll_x, + drag.drop_index, + drag.in_spacer, + ) && move_app_tab(&mut shell.state.split, drag.tab_id, insert_at) + { + shell.save_local_workspaces(); + cx.notify(); + } + }); + } + state.update(app, |stored, cx| { + stored.suppressed_click_tab = Some(drag.tab_id); + cx.notify(); + }); + app.stop_propagation(); + }); +} + +#[cfg(test)] +mod tests { + use affine_client::Scope; + + use super::*; + use crate::split_view::{DesktopRoute, DocViewMode}; + + fn test_layout(pinned_count: usize, unpinned_count: usize) -> SplitLayout { + let doc = |i: usize| DesktopRoute::Doc(format!("doc-{i}")); + let mut layout = SplitLayout::single( + Scope::new("u", "https://app.affine.pro", "ws"), + doc(0), + DocViewMode::Page, + ); + for i in 1..(pinned_count + unpinned_count) { + layout.panes[0].push_tab( + Scope::new("u", "https://app.affine.pro", "ws"), + doc(i), + DocViewMode::Page, + ); + } + for i in 0..pinned_count { + layout.panes[0].set_tab_pinned(i, true); + } + layout.sync_app_tab(); + layout + } + + #[test] + fn drop_insertion_enforces_section_boundaries_and_ignores_no_ops() { + // [P0, P1, U2, U3]: pinned tabs stay in 0..2, unpinned tabs stay in 2..4. + let split = test_layout(2, 2); + let tabs = &split.panes[0].tabs; + let strip = StripLayout::new(&split); + let mid = |idx: usize| { + let (x, w) = strip.span(idx); + x + w * 0.5 + }; + + for (from, content_x, expected, desc) in [ + ( + 3, + 0.0, + Some(2), + "unpinned far left clamps to unpinned start", + ), + ( + 3, + mid(1), + Some(2), + "unpinned over pinned clamps to unpinned start", + ), + (3, mid(2) - 1.0, Some(2), "unpinned before U2 midpoint"), + (3, mid(2) + 1.0, None, "unpinned in own left slot is no-op"), + (3, mid(3) + 50.0, None, "unpinned past end is no-op"), + (2, mid(3) + 1.0, Some(4), "unpinned U2 past U3 midpoint"), + (2, 0.0, None, "first unpinned far left is no-op"), + (1, 0.0, Some(0), "second pinned before first pinned"), + ( + 1, + mid(3) + 50.0, + None, + "second pinned far right stays clamped", + ), + ( + 0, + mid(3) + 50.0, + Some(2), + "first pinned dragged right moves to pinned end", + ), + ( + 0, + mid(0) + 1.0, + None, + "first pinned between P0 and P1 is no-op", + ), + ] { + assert_eq!( + drop_insertion_index(&strip, tabs, from, content_x), + expected, + "{desc}" + ); + } + } +} diff --git a/packages/frontend/desktop/src/workbench/topbar/tabs/label.rs b/packages/frontend/desktop/src/workbench/topbar/tabs/label.rs index b5af84dd73..69d519d8ba 100644 --- a/packages/frontend/desktop/src/workbench/topbar/tabs/label.rs +++ b/packages/frontend/desktop/src/workbench/topbar/tabs/label.rs @@ -102,6 +102,7 @@ pub(super) fn render_tab_range( range: Range, focus: &HashMap, menu_state: &Entity, + drag_tab_id: Option, scroll_x: f32, palette: DesktopPalette, window: &Window, @@ -165,6 +166,7 @@ pub(super) fn render_tab_range( .h(px(TAB_HEIGHT)) .rounded(px(4.0)) .bg(default_background) + .when(drag_tab_id == Some(tab_id), |label| label.opacity(0.6)) .when(tab_active, |label| { let ring = BoxShadow::new(px(0.0), px(0.0), active_border).spread_radius(px(TAB_RING)); @@ -204,11 +206,29 @@ pub(super) fn render_tab_range( .items_center() .tab_index(0) .focus_visible(move |style| style.bg(palette.bg_active)) - .on_click(cx.listener(move |shell, _, window, cx| { - shell.sync_editors(cx); - if shell.state.split.activate_app_tab_view(tab_id, view) { - window.focus(&shell.focus_handle, cx); - cx.notify(); + .on_mouse_down(MouseButton::Left, { + let state = menu_state.clone(); + move |event, _, app| { + state.update(app, |stored, _| { + stored.suppressed_click_tab = None; + stored.drag = + Some(super::drag::TabDrag::new(tab_id, event.position.x.into())); + }); + } + }) + .on_click(cx.listener({ + let state = menu_state.clone(); + move |shell, event: &ui::ClickEvent, window, cx| { + if matches!(event, ui::ClickEvent::Mouse(_)) + && state.update(cx, |stored, _| stored.take_suppressed_click(tab_id)) + { + return; + } + shell.sync_editors(cx); + if shell.state.split.activate_app_tab_view(tab_id, view) { + window.focus(&shell.focus_handle, cx); + cx.notify(); + } } })) .on_mouse_down(MouseButton::Middle, { diff --git a/packages/frontend/desktop/src/workbench/topbar/tabs/menu.rs b/packages/frontend/desktop/src/workbench/topbar/tabs/menu.rs index 64b5660d2f..70703c304e 100644 --- a/packages/frontend/desktop/src/workbench/topbar/tabs/menu.rs +++ b/packages/frontend/desktop/src/workbench/topbar/tabs/menu.rs @@ -41,6 +41,7 @@ pub(super) fn open_listener( let focus = app.focus_handle(); window.focus(&focus, app); state.update(app, |stored, cx| { + stored.drag = None; stored.menu = Some(TabMenu { tab, view, diff --git a/packages/frontend/desktop/src/workbench/topbar/tabs/mod.rs b/packages/frontend/desktop/src/workbench/topbar/tabs/mod.rs index 2800002b4e..7c07e40652 100644 --- a/packages/frontend/desktop/src/workbench/topbar/tabs/mod.rs +++ b/packages/frontend/desktop/src/workbench/topbar/tabs/mod.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, ops::Range}; +use std::{cell::Cell, collections::HashMap, ops::Range, rc::Rc}; use blocksuite_editor::scroll::{ScrollAxis, dominant_axis_delta, wheel_delta}; use ui::{ @@ -18,6 +18,7 @@ use super::{ }; mod dividers; +mod drag; mod label; mod menu; mod saved; @@ -138,8 +139,15 @@ fn render_strip( let menu = menu::render_tab_menu(shell, state.clone(), palette, window, cx); let new_is_focused = new.is_focused(window); let new_button_focus = new.clone(); + let drag_focus = state.read(cx).drag_focus.clone(); let count = shell.state.split.panes[0].tabs.len(); + let escape_state = state.clone(); + let escape_shell = cx.entity(); strip + .track_focus(&drag_focus) + .capture_key_down(move |event, window, app| { + drag::cancel_on_escape(event, &escape_state, &escape_shell, window, app); + }) .on_key_down(move |event, window, app| { let key = &event.keystroke; if key.key != "tab" @@ -375,10 +383,14 @@ struct TabStripScroll { focused_tab: Option, tabs: HashMap, new: FocusHandle, + drag_focus: FocusHandle, entry: Option, menu: Option, /// The tab and view button under the middle button press. middle_down: Option<(u64, Option)>, + drag: Option, + suppressed_click_tab: Option, + strip_bounds: Rc>, } impl TabStripScroll { @@ -391,11 +403,21 @@ impl TabStripScroll { focused_tab: None, tabs: HashMap::new(), new: app.focus_handle().tab_stop(true), + drag_focus: app.focus_handle(), entry: None, menu: None, middle_down: None, + drag: None, + suppressed_click_tab: None, + strip_bounds: Rc::new(Cell::new(drag::StripBounds::default())), } } + + fn take_suppressed_click(&mut self, tab_id: u64) -> bool { + self.suppressed_click_tab + .take_if(|suppressed| *suppressed == tab_id) + .is_some() + } } /// Mount the tabs in the viewport and the overscan. @@ -485,8 +507,26 @@ fn render_tab_labels( ) }) .collect::>(); + let drag_tab_id = stored + .drag + .as_ref() + .filter(|drag| drag.is_active()) + .map(|drag| drag.tab_id); + let drop_indicator = stored + .drag + .as_ref() + .and_then(|drag| drag::render_drop_indicator(&layout, drag, &pane.tabs, scroll_x, palette)); let labels = render_tab_range( - shell, &layout, range, &tabs, &state, scroll_x, palette, window, cx, + shell, + &layout, + range, + &tabs, + &state, + drag_tab_id, + scroll_x, + palette, + window, + cx, ); let pending_entry = entry.and_then(|entry| { let Some(tab) = entry_index @@ -516,8 +556,19 @@ fn render_tab_labels( let measure_state = state.clone(); let measure_layout = layout.clone(); + let strip_bounds = state.read(cx).strip_bounds.clone(); + let drag_state = state.clone(); + let drag_shell = cx.entity(); + let drag_bounds = strip_bounds.clone(); let measure = canvas( move |bounds, window, app| { + let strip_top = f32::from(bounds.origin.y) + - (APP_TABS_HEIGHT - (TAB_HEIGHT + 2.0 * TAB_RING)) * 0.5; + strip_bounds.set(drag::StripBounds { + origin_x: f32::from(bounds.origin.x), + top: strip_top, + bottom: strip_top + APP_TABS_HEIGHT, + }); let width = f32::from(bounds.size.width) - 2.0 * TAB_RING; if measure_state.read(app).measured != Some((content, width)) { window.defer(app, move |_, app| { @@ -533,7 +584,9 @@ fn render_tab_labels( }); } }, - |_, (), _, _| {}, + move |_, (), window, _| { + drag::register_window_drag_listeners(window, drag_state, drag_shell, drag_bounds); + }, ) .absolute() .inset_0(); @@ -559,6 +612,7 @@ fn render_tab_labels( }); }) .children(labels) + .children(drop_indicator) .child(measure) } @@ -1601,4 +1655,445 @@ mod tests { ); } } + + struct MemoryTabStore(std::cell::RefCell>); + + impl crate::workbench::LocalDocStore for MemoryTabStore { + fn push_update(&self, _: &str, _: &str, _: Vec) {} + fn delete_doc(&self, _: &str, _: &str) {} + fn set_route(&self, _: &str, _: Option<&str>) {} + fn set_tabs(&self, workspace_id: &str, tabs: &str) { + self.0 + .borrow_mut() + .insert(workspace_id.to_owned(), tabs.to_owned()); + } + fn tabs(&self, workspace_id: &str) -> Option { + self.0.borrow().get(workspace_id).cloned() + } + } + + fn seeded_tab_shell(theme: ThemeMode, routes: &[&str], active: usize) -> Shell { + use crate::split_view::DesktopRoute; + + let mut state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + for doc_id in routes.iter().skip(1) { + state.open_app_tab(DocViewMode::Page); + state.navigate_active_pane(DesktopRoute::Doc((*doc_id).to_owned())); + } + state.split.panes[0].select_tab(active); + state.split.sync_app_tab(); + Shell::with_state(state) + } + + fn drag_tab_step(shell: &Shell, from: &str, to_x: f32) { + let start = shell.bounds(from).expect(from); + let y = start.y + start.height / 2.0; + let down = point(px(start.x + start.width / 2.0), px(y)); + shell.pointer(down, None); + shell.button(down, true); + shell.pointer(point(px(to_x), px(y)), Some(MouseButton::Left)); + } + + #[test] + fn dragging_unpinned_tab_reorders_strip_preserves_active_tab_and_updates_saved_tabs() { + use crate::{split_view::DesktopRoute, workbench::local_workspace::LocalDocStore}; + + let store = std::rc::Rc::new(MemoryTabStore(Default::default())); + let (mut state, sessions) = + DesktopAppState::open_local(&Default::default(), ThemeMode::Light, "2026-12-02", 1_000) + .expect("open local showcase"); + let ws_id = state.store.active_workspace().id.clone(); + state.navigate_active_pane(DesktopRoute::AllDocs); + for doc_id in ["doc-arch", "doc-sync"] { + state.open_app_tab(DocViewMode::Page); + state.navigate_active_pane(DesktopRoute::Doc(doc_id.to_owned())); + } + state.split.panes[0].select_tab(1); + state.split.sync_app_tab(); + let shell = Shell::with_state(state); + shell.update(|view, _, cx| { + view.bind_local_workspaces(sessions, store.clone(), 1_000, cx); + }); + shell.frame(); + + let ids_before = shell.tab_ids(); + let active_id = ids_before[1]; + let b_bounds = shell.bounds("desktop.app_tabs.tab.1").expect("tab 1"); + let target_x = b_bounds.x + b_bounds.width * 0.75; + drag_tab_step(&shell, "desktop.app_tabs.tab.0", target_x); + + let indicator = shell + .bounds("desktop.app_tabs.drop_indicator") + .expect("drop indicator"); + assert_eq!(indicator.width, 2.0); + assert!( + indicator.x > b_bounds.x + b_bounds.width + && indicator.x < shell.bounds("desktop.app_tabs.tab.2").expect("tab 2").x, + "indicator at {:?} should sit in gap after tab 1", + indicator + ); + let drag_img = shell.image(); + let accent = rgb(crate::palette_for(ThemeMode::Light).accent); + assert_pixel( + &drag_img, + (indicator.x + 1.0, indicator.y + indicator.height / 2.0), + accent, + "drop indicator accent", + ); + let a_bounds = shell.bounds("desktop.app_tabs.tab.0").expect("dragged tab"); + let strip_bg = rgb(crate::palette_for(ThemeMode::Light).bg_sidebar); + let faded = over( + app_tab_background(ThemeMode::Light, false).opacity(0.6), + strip_bg, + ); + assert_pixel( + &drag_img, + (a_bounds.x + a_bounds.width - 2.0, a_bounds.y + 4.0), + faded, + "dragged tab reduced opacity", + ); + + let y = b_bounds.y + b_bounds.height / 2.0; + shell.button(point(px(target_x), px(y)), false); + + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + assert_eq!( + shell.tab_ids(), + [ids_before[1], ids_before[0], ids_before[2]] + ); + assert_eq!( + shell.update(|view, _, _| view.state.split.panes[0].active_tab().id), + active_id + ); + assert_eq!(shell.active(), (0, 3)); + + let saved_json = store.tabs(&ws_id).expect("saved tabs written on drop"); + assert_eq!( + Some(saved_json.clone()), + shell.update(|view, _, _| SavedTabs::json(&view.state.split)) + ); + let mut restored = DesktopAppState::seed_showcase(ThemeMode::Light, "2026-12-02"); + restored.restore_saved_tabs(|id| (id == ws_id).then(|| saved_json.clone())); + let routes: Vec<_> = restored.split.panes[0] + .tabs + .iter() + .map(|tab| tab.route.clone()) + .collect(); + assert_eq!( + routes, + vec![ + DesktopRoute::Doc("doc-arch".into()), + DesktopRoute::AllDocs, + DesktopRoute::Doc("doc-sync".into()), + ] + ); + assert_eq!(restored.split.panes[0].active_tab, 0); + + if let Some(dir) = std::env::var_os("AFFINE_TAB_DRAG_EVIDENCE_DIR") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).expect("evidence dir"); + for theme in [ThemeMode::Light, ThemeMode::Dark] { + let tag = match theme { + ThemeMode::Light => "light", + ThemeMode::Dark => "dark", + }; + let mut ev_state = DesktopAppState::seed_showcase(theme, "2026-12-02"); + ev_state.navigate_active_pane(DesktopRoute::AllDocs); + for doc_id in ["doc-arch", "doc-sync"] { + ev_state.open_app_tab(DocViewMode::Page); + ev_state.navigate_active_pane(DesktopRoute::Doc(doc_id.to_owned())); + } + ev_state.split.panes[0].select_tab(1); + ev_state.split.sync_app_tab(); + let ev = Shell::with_state(ev_state); + ev.image() + .save(dir.join(format!("before-{tag}.png"))) + .expect("save before"); + let b = ev.bounds("desktop.app_tabs.tab.1").expect("tab 1"); + let tx = b.x + b.width * 0.75; + drag_tab_step(&ev, "desktop.app_tabs.tab.0", tx); + ev.image() + .save(dir.join(format!("dragging-{tag}.png"))) + .expect("save dragging"); + ev.button(point(px(tx), px(b.y + b.height / 2.0)), false); + ev.image() + .save(dir.join(format!("after-{tag}.png"))) + .expect("save after"); + } + } + } + + #[test] + fn dragging_tabs_enforces_pinned_and_unpinned_partition_boundaries() { + for theme in [ThemeMode::Light, ThemeMode::Dark] { + let shell = seeded_tab_shell(theme, &["a", "doc-arch", "doc-sync", "doc-board"], 2); + shell.update(|view, _, cx| { + view.state.split.panes[0].set_tab_pinned(0, true); + view.state.split.panes[0].set_tab_pinned(1, true); + cx.notify(); + }); + shell.frame(); + let [p1, p2, u1, u2] = shell.tab_ids()[..] else { + panic!("expected 4 tabs"); + }; + + // Drag U2 all the way left over P1 -> clamped to start of unpinned section. + let p1_b = shell.bounds("desktop.app_tabs.tab.0").expect("p1"); + let u1_b = shell.bounds("desktop.app_tabs.tab.2").expect("u1"); + drag_tab_step(&shell, "desktop.app_tabs.tab.3", p1_b.x + 8.0); + let indicator = shell + .bounds("desktop.app_tabs.drop_indicator") + .expect("unpinned start indicator"); + assert!( + indicator.x > p1_b.x + p1_b.width && indicator.x < u1_b.x, + "{theme:?} indicator {indicator:?} must follow pin separator before u1 {u1_b:?}" + ); + assert_pixel( + &shell.image(), + (indicator.x + 1.0, indicator.y + indicator.height / 2.0), + rgb(crate::palette_for(theme).accent), + "themed drop indicator", + ); + shell.button( + point(px(p1_b.x + 8.0), px(p1_b.y + p1_b.height / 2.0)), + false, + ); + assert_eq!(shell.tab_ids(), [p1, p2, u2, u1]); + assert_eq!(shell.pinned(), [true, true, false, false]); + + // Drag P2 to the right over unpinned tabs -> clamped at pinned end (no-op). + let u2_b = shell.bounds("desktop.app_tabs.tab.2").expect("u2"); + drag_tab_step(&shell, "desktop.app_tabs.tab.1", u2_b.x + u2_b.width * 0.8); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button( + point( + px(u2_b.x + u2_b.width * 0.8), + px(u2_b.y + u2_b.height / 2.0), + ), + false, + ); + assert_eq!(shell.tab_ids(), [p1, p2, u2, u1]); + + // Drag P2 left over P1 -> [P2, P1, U2, U1], then drag P2 right over U1 -> [P1, P2, U2, U1]. + drag_tab_step(&shell, "desktop.app_tabs.tab.1", p1_b.x + 8.0); + shell.button( + point(px(p1_b.x + 8.0), px(p1_b.y + p1_b.height / 2.0)), + false, + ); + assert_eq!(shell.tab_ids(), [p2, p1, u2, u1]); + + let u1_b = shell.bounds("desktop.app_tabs.tab.3").expect("u1"); + drag_tab_step(&shell, "desktop.app_tabs.tab.0", u1_b.x + u1_b.width * 0.8); + let pin_end_ind = shell + .bounds("desktop.app_tabs.drop_indicator") + .expect("pinned end indicator"); + assert!(pin_end_ind.x < u2_b.x, "pinned drop stays before unpinned"); + shell.button( + point( + px(u1_b.x + u1_b.width * 0.8), + px(u1_b.y + u1_b.height / 2.0), + ), + false, + ); + assert_eq!(shell.tab_ids(), [p1, p2, u2, u1]); + assert_eq!(shell.pinned(), [true, true, false, false]); + } + } + + #[test] + fn sub_threshold_click_switches_tab_and_split_view_and_escape_cancels_drag() { + let shell = seeded_tab_shell(ThemeMode::Light, &["a", "doc-arch", "doc-sync"], 2); + let [t0, t1, t2] = shell.tab_ids()[..] else { + panic!("expected 3 tabs"); + }; + shell.update(|view, _, cx| { + let scope = view.state.current_scope(); + view.state.split.open_all_docs_beside_app_tab(scope, t1); + cx.notify(); + }); + shell.frame(); + + // < 6px jitter on a split view still activates that tab and pane. + let view1 = shell + .bounds("desktop.app_tabs.tab.1.view.1") + .expect("split view 1"); + let y = view1.y + view1.height / 2.0; + let down = point(px(view1.x + view1.width / 2.0), px(y)); + shell.pointer(down, None); + shell.button(down, true); + let jitter = point(px(f32::from(down.x) + 4.0), px(y)); + shell.pointer(jitter, Some(MouseButton::Left)); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button(jitter, false); + assert_eq!(shell.active(), (1, 3)); + assert_eq!(shell.update(|view, _, _| view.state.split.active_pane), 1); + assert_eq!(shell.tab_ids(), [t0, t1, t2]); + + // < 6px click on tab 0 selects tab 0. + let tab0 = shell.bounds("desktop.app_tabs.tab.0").expect("tab 0"); + let tab0_down = point(px(tab0.x + 20.0), px(tab0.y + tab0.height / 2.0)); + shell.pointer(tab0_down, None); + shell.button(tab0_down, true); + shell.pointer( + point( + px(f32::from(tab0_down.x) + 4.0), + px(tab0.y + tab0.height / 2.0), + ), + Some(MouseButton::Left), + ); + shell.button( + point( + px(f32::from(tab0_down.x) + 4.0), + px(tab0.y + tab0.height / 2.0), + ), + false, + ); + assert_eq!(shell.active(), (0, 3)); + + // Pressing on close button and dragging > 6px does not start tab drag. + let close0 = shell.bounds("desktop.pane.0.tab.0.close").expect("close 0"); + let close_down = point( + px(close0.x + close0.width / 2.0), + px(close0.y + close0.height / 2.0), + ); + shell.pointer(close_down, None); + shell.button(close_down, true); + shell.pointer( + point( + px(f32::from(close_down.x) + 40.0), + px(close0.y + close0.height / 2.0), + ), + Some(MouseButton::Left), + ); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button( + point( + px(f32::from(close_down.x) + 40.0), + px(close0.y + close0.height / 2.0), + ), + false, + ); + assert_eq!(shell.tab_ids(), [t0, t1, t2]); + + // Dragging a split composite tab past tab 0 moves all its views together. + let tab0 = shell.bounds("desktop.app_tabs.tab.0").expect("tab 0"); + drag_tab_step(&shell, "desktop.app_tabs.tab.1", tab0.x + 8.0); + assert!(shell.has("desktop.app_tabs.drop_indicator")); + shell.button( + point(px(tab0.x + 8.0), px(tab0.y + tab0.height / 2.0)), + false, + ); + assert_eq!(shell.tab_ids(), [t1, t0, t2]); + assert!(shell.has("desktop.app_tabs.tab.0.view.1")); + assert_eq!(shell.active(), (1, 3)); + + // Dragging past threshold and pressing Escape cancels drag and preserves order. + let tab0_after = shell.bounds("desktop.app_tabs.tab.0").expect("tab 0 after"); + drag_tab_step(&shell, "desktop.app_tabs.tab.1", tab0_after.x + 8.0); + assert!(shell.has("desktop.app_tabs.drop_indicator")); + shell.key("escape"); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.pointer( + point( + px(tab0_after.x + 2.0), + px(tab0_after.y + tab0_after.height / 2.0), + ), + Some(MouseButton::Left), + ); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button( + point( + px(tab0_after.x + 2.0), + px(tab0_after.y + tab0_after.height / 2.0), + ), + false, + ); + assert_eq!(shell.tab_ids(), [t1, t0, t2]); + assert_eq!(shell.active(), (1, 3)); + } + + #[test] + fn dragging_outside_vertical_strip_bounds_keeps_sticky_tab_target_and_clears_spacer_or_untargeted() + { + use crate::{split_view::DesktopRoute, workbench::local_workspace::LocalDocStore}; + + let store = std::rc::Rc::new(MemoryTabStore(Default::default())); + let (mut state, sessions) = + DesktopAppState::open_local(&Default::default(), ThemeMode::Light, "2026-12-02", 1_000) + .expect("open local showcase"); + let ws_id = state.store.active_workspace().id.clone(); + state.navigate_active_pane(DesktopRoute::AllDocs); + for doc_id in ["doc-arch", "doc-sync"] { + state.open_app_tab(DocViewMode::Page); + state.navigate_active_pane(DesktopRoute::Doc(doc_id.to_owned())); + } + state.split.panes[0].select_tab(1); + state.split.sync_app_tab(); + let shell = Shell::with_state(state); + shell.update(|view, _, cx| { + view.bind_local_workspaces(sessions, store.clone(), 1_000, cx); + }); + shell.frame(); + + let ids_before = shell.tab_ids(); + let saved_before = store.tabs(&ws_id).expect("initial saved tabs"); + let tab0 = shell.bounds("desktop.app_tabs.tab.0").expect("tab 0"); + let tab1 = shell.bounds("desktop.app_tabs.tab.1").expect("tab 1"); + let tab2 = shell.bounds("desktop.app_tabs.tab.2").expect("tab 2"); + let strip_y = tab1.y + tab1.height / 2.0; + let b_right_x = tab1.x + tab1.width * 0.75; + let c_right_x = tab2.x + tab2.width * 0.75; + let spacer_x = tab2.x + tab2.width + 60.0; + + // 1. Drag straight down from tab A into body, then horizontally under C and release: + // no target was ever hit, so order stays [A, B, C] and SavedTabs is unchanged. + let a_down = point(px(tab0.x + tab0.width / 2.0), px(strip_y)); + shell.pointer(a_down, None); + shell.button(a_down, true); + shell.pointer(point(a_down.x, px(300.0)), Some(MouseButton::Left)); + shell.pointer(point(px(c_right_x), px(300.0)), Some(MouseButton::Left)); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button(point(px(c_right_x), px(300.0)), false); + assert_eq!(shell.tab_ids(), ids_before); + assert_eq!(store.tabs(&ws_id).as_deref(), Some(saved_before.as_str())); + + // 2. Drag into trailing spacer (non-sticky), leave into body (clears), return to strip + // (recovers), then leave again and release in body: leaves [A, B, C] unchanged. + drag_tab_step(&shell, "desktop.app_tabs.tab.0", spacer_x); + assert!(shell.has("desktop.app_tabs.drop_indicator")); + shell.pointer(point(px(spacer_x), px(300.0)), Some(MouseButton::Left)); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.pointer(point(px(spacer_x), px(strip_y)), Some(MouseButton::Left)); + assert!(shell.has("desktop.app_tabs.drop_indicator")); + shell.pointer(point(px(c_right_x), px(300.0)), Some(MouseButton::Left)); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + shell.button(point(px(c_right_x), px(300.0)), false); + assert_eq!(shell.tab_ids(), ids_before); + assert_eq!(store.tabs(&ws_id).as_deref(), Some(saved_before.as_str())); + + // 3. Drag A over B's right half (sticky tab target after B), then move down into body + // and horizontally under C and release: body horizontal motion does not overwrite the + // sticky target, so A drops after B -> [B, A, C] and persists to SavedTabs. + drag_tab_step(&shell, "desktop.app_tabs.tab.0", b_right_x); + let sticky_ind = shell + .bounds("desktop.app_tabs.drop_indicator") + .expect("sticky indicator after B"); + assert!(sticky_ind.x > tab1.x + tab1.width && sticky_ind.x < tab2.x); + shell.pointer(point(px(b_right_x), px(300.0)), Some(MouseButton::Left)); + shell.pointer(point(px(c_right_x), px(300.0)), Some(MouseButton::Left)); + let kept_ind = shell + .bounds("desktop.app_tabs.drop_indicator") + .expect("sticky indicator preserved in body"); + assert_eq!(kept_ind.x, sticky_ind.x); + shell.button(point(px(c_right_x), px(300.0)), false); + assert!(!shell.has("desktop.app_tabs.drop_indicator")); + assert_eq!( + shell.tab_ids(), + [ids_before[1], ids_before[0], ids_before[2]] + ); + assert_eq!( + store.tabs(&ws_id), + shell.update(|view, _, _| SavedTabs::json(&view.state.split)) + ); + } }