Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): hand-rolled tab drag with pin/unpin across the divider (#20650)

Innei37fefa44c0a7
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index 5dd674ec92e..aaf5c2e6204 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -1,13 +1,12 @@
'use client';
-import { useSortable } from '@dnd-kit/sortable';
import { ContextMenuTrigger, type GenericItemType, Icon, Tooltip } from '@lobehub/ui';
import { ActionIcon } from '@lobehub/ui/base-ui';
import { cx } from 'antd-style';
import { X } from 'lucide-react';
-import { useMotionValue, useSpring, useTransform } from 'motion/react';
+import { type MotionValue, useMotionValue, useSpring, useTransform } from 'motion/react';
import * as m from 'motion/react-m';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Avatar from '@/components/Avatar';
@@ -20,6 +19,7 @@ import { useTabUnread } from './hooks/useTabUnread';
import { TAB_SPRING } from './motion';
import { useStyles } from './styles';
import { buildTabContextMenuItems } from './tabContextMenu';
+import { rubberBand } from './tabDrag';
import { resolveTabInset, type TabTier } from './tabLayout';
// 20px box on an 8px-round tab, inset a uniform 3px: 8 - 3 = 5 keeps the button's curve
@@ -30,7 +30,14 @@ import { resolveTabInset, type TabTier } from './tabLayout';
// falls back to a 24px glyph inside the 20px box.
const CLOSE_BUTTON_STYLE = { borderRadius: 5, height: 20, width: 20 } as const;
+interface TabDragFollow {
+ grabFraction: number;
+ maxX: number;
+ pointerX: MotionValue<number>;
+}
+
interface TabItemProps {
+ drag?: TabDragFollow;
/**
* Where the tab's offset spring starts on the very first render — the strip's previous
* total width, i.e. the point a newly opened tab is appended at. Seeding it at the
@@ -50,6 +57,8 @@ interface TabItemProps {
onCloseOthers: (id: string) => void;
onCloseRight: (id: string) => void;
onCloseSplitView: () => void;
+ onDragStart: (id: string, event: React.PointerEvent<HTMLElement>) => void;
+ onMoveBy: (id: string, delta: -1 | 1) => void;
onOpenInSplitView: (id: string) => void;
onTogglePin: (id: string) => void;
pinnedCount: number;
@@ -72,6 +81,7 @@ const TabItem = memo<TabItemProps>(
totalCount,
width,
x,
+ drag,
enterWidth,
enterX,
onActivate,
@@ -80,6 +90,8 @@ const TabItem = memo<TabItemProps>(
onCloseLeft,
onCloseRight,
onCloseSplitView,
+ onDragStart,
+ onMoveBy,
onOpenInSplitView,
onTogglePin,
}) => {
@@ -98,9 +110,7 @@ const TabItem = memo<TabItemProps>(
const closable = totalCount > 1;
const closeInert = tier !== 'full' && tier !== 'compact';
- const { attributes, listeners, setNodeRef, transform, isDragging, isSorting } = useSortable({
- id,
- });
+ const isDragging = !!drag;
// A newly opened tab springs out from zero rather than popping in at full width; the
// motion value starts collapsed and is set to the real width on mount.
@@ -117,35 +127,77 @@ const TabItem = memo<TabItemProps>(
const targetInset = useMotionValue(resolveTabInset(width));
const springInset = useSpring(targetInset, TAB_SPRING);
const inset = useTransform(springInset, (value) => `${value}px`);
- const wasSorting = useRef(false);
+ const zIndex = useMotionValue(pinned ? 1 : 0);
useEffect(() => {
targetWidth.set(width);
targetInset.set(resolveTabInset(width));
}, [width, targetWidth, targetInset]);
- // Dropping a drag must jump, not animate. dnd-kit clears its transform in the same
- // commit that the reordered store lands, and up to that frame the tab is already
- // sitting at its new offset (springX at the old slot plus dnd-kit's displacement).
- // Animating from there would send it back to where it was picked up and re-slide it.
useEffect(() => {
- const settledFromDrag = wasSorting.current && !isSorting;
- wasSorting.current = isSorting;
-
- if (!settledFromDrag) {
+ if (!drag) {
targetX.set(x);
return;
}
- targetX.jump(x);
- springX.jump(x);
- }, [x, isSorting, targetX, springX]);
+ // Held from the same spot of the tab while its width springs between pill and full,
+ // so it re-follows on width changes as well as pointer moves.
+ const follow = () => {
+ const next = rubberBand(
+ drag.pointerX.get() - drag.grabFraction * springWidth.get(),
+ 0,
+ drag.maxX,
+ );
+ targetX.jump(next);
+ springX.jump(next);
+ };
+ follow();
+ const offPointer = drag.pointerX.on('change', follow);
+ const offWidth = springWidth.on('change', follow);
+
+ return () => {
+ offPointer();
+ offWidth();
+ };
+ }, [drag, x, targetX, springX, springWidth]);
- const handleClick = useCallback(() => {
- if (!isActive || isSplitVisible) {
- onActivate(id, tab.url);
+ // A dropped tab springs from the release point into its slot; it stays above its
+ // neighbours until it lands, or it would slide underneath the one it overlaps.
+ useEffect(() => {
+ const resting = pinned ? 1 : 0;
+ if (isDragging) {
+ zIndex.set(2);
+ return;
}
- }, [isActive, isSplitVisible, onActivate, id, tab.url]);
+
+ const settle = () => {
+ if (Math.abs(springX.get() - x) < 1) zIndex.set(resting);
+ };
+ settle();
+ return springX.on('change', settle);
+ }, [isDragging, pinned, x, springX, zIndex]);
+
+ const handlePointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (e.button !== 0 || e.ctrlKey) return;
+ if ((e.target as HTMLElement).closest('[data-tab-close]')) return;
+
+ if (!isActive || isSplitVisible) onActivate(id, tab.url);
+ onDragStart(id, e);
+ },
+ [isActive, isSplitVisible, onActivate, onDragStart, id, tab.url],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (!e.altKey || !e.shiftKey) return;
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
+
+ e.preventDefault();
+ onMoveBy(id, e.key === 'ArrowLeft' ? -1 : 1);
+ },
+ [onMoveBy, id],
+ );
const handleClose = useCallback(
(e: React.MouseEvent) => {
@@ -228,7 +280,8 @@ const TabItem = memo<TabItemProps>(
<m.div
data-active={isActive ? 'true' : undefined}
data-tier={tier}
- ref={setNodeRef}
+ role="button"
+ tabIndex={0}
className={cx(
electronStylish.nodrag,
styles.tab,
@@ -239,20 +292,15 @@ const TabItem = memo<TabItemProps>(
)}
style={{
paddingInlineStart: inset,
- // dnd-kit's displacement rides the standalone `translate` property while the
- // offset spring owns `transform`. Both are pure x translations, so they
- // compose, and neither has to be folded into the other's value.
- translate: transform ? `${transform.x}px` : undefined,
width: springWidth,
x: springX,
- zIndex: isDragging ? 2 : pinned ? 1 : undefined,
+ zIndex,
}}
onAuxClick={handleAuxClick}
- onClick={handleClick}
+ onKeyDown={handleKeyDown}
+ onPointerDown={handlePointerDown}
onPointerEnter={() => setHovered(true)}
onPointerLeave={() => setHovered(false)}
- {...attributes}
- {...listeners}
>
{indicator}
<span data-tab-title className={styles.tabTitle}>
@@ -281,7 +329,7 @@ const TabItem = memo<TabItemProps>(
return (
<ContextMenuTrigger items={contextMenuItems}>
<Tooltip
- disabled={tier === 'full' && !preview}
+ disabled={isDragging || (tier === 'full' && !preview)}
title={
preview ? (
<span className={styles.previewCard}>
diff --git a/src/features/Electron/titlebar/TabBar/hooks/useTabDrag.ts b/src/features/Electron/titlebar/TabBar/hooks/useTabDrag.ts
new file mode 100644
index 00000000000..b90aecb402e
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/hooks/useTabDrag.ts
@@ -0,0 +1,127 @@
+import { useLatest } from 'ahooks';
+import { type MotionValue, useMotionValue } from 'motion/react';
+import {
+ type PointerEvent as ReactPointerEvent,
+ type RefObject,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+
+import { resolveDropTarget } from '../tabDrag';
+import { type StripTab } from '../tabLayout';
+
+// Same as the dnd-kit PointerSensor it replaces: a plain click must not start a drag.
+const DRAG_THRESHOLD = 4;
+
+export interface TabDragSession {
+ grabFraction: number;
+ id: string;
+ pinned: boolean;
+ toIndex: number;
+}
+
+interface UseTabDragOptions {
+ activeTabId: string | null;
+ onDrop: (id: string, toIndex: number, pinned: boolean) => void;
+ stripRef: RefObject<HTMLElement | null>;
+ stripWidth: number;
+ tabs: StripTab[];
+}
+
+export interface TabDrag {
+ /** Pointer x relative to the strip's origin, updated on every move without a render. */
+ pointerX: MotionValue<number>;
+ session: TabDragSession | null;
+ startDrag: (id: string, event: ReactPointerEvent<HTMLElement>) => void;
+}
+
+export const useTabDrag = (options: UseTabDragOptions): TabDrag => {
+ const latest = useLatest(options);
+ const pointerX = useMotionValue(0);
+ const [session, setSession] = useState<TabDragSession | null>(null);
+ const teardown = useRef<(() => void) | null>(null);
+
+ useEffect(() => () => teardown.current?.(), []);
+
+ const startDrag = useCallback(
+ (id: string, event: ReactPointerEvent<HTMLElement>) => {
+ const strip = latest.current.stripRef.current;
+ if (!strip || teardown.current) return;
+
+ const { pointerId, clientX: startX } = event;
+ const originX = strip.getBoundingClientRect().left;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const grabFraction = rect.width > 0 ? (startX - rect.left) / rect.width : 0.5;
+ let current: TabDragSession | null = null;
+
+ const finish = (commit: boolean) => {
+ teardown.current?.();
+ if (commit && current) latest.current.onDrop(current.id, current.toIndex, current.pinned);
+ setSession(null);
+ };
+
+ const update = (clientX: number) => {
+ const { activeTabId, stripWidth, tabs } = latest.current;
+ const own = tabs.find((tab) => tab.id === id);
+ if (!own) return finish(false);
+
+ const pinned = current ? current.pinned : own.pinned;
+ const x = clientX - originX;
+ pointerX.set(x);
+
+ const target = resolveDropTarget({
+ activeId: activeTabId,
+ draggedId: id,
+ grabFraction,
+ pointerX: x,
+ stripWidth,
+ tabs: tabs.map((tab) => (tab.id === id ? { id, pinned } : tab)),
+ });
+ const toIndex = target.findIndex((tab) => tab.id === id);
+ const next = { grabFraction, id, pinned: target[toIndex].pinned, toIndex };
+ if (current && current.toIndex === next.toIndex && current.pinned === next.pinned) return;
+
+ current = next;
+ setSession(next);
+ };
+
+ const handleMove = (e: PointerEvent) => {
+ if (e.pointerId !== pointerId) return;
+ if (!current && Math.abs(e.clientX - startX) < DRAG_THRESHOLD) return;
+ update(e.clientX);
+ };
+ const handleUp = (e: PointerEvent) => {
+ if (e.pointerId === pointerId) finish(true);
+ };
+ const handleCancel = (e: PointerEvent) => {
+ if (e.pointerId === pointerId) finish(false);
+ };
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key !== 'Escape' || !current) return;
+ e.preventDefault();
+ e.stopPropagation();
+ finish(false);
+ };
+ const handleBlur = () => finish(false);
+
+ window.addEventListener('pointermove', handleMove);
+ window.addEventListener('pointerup', handleUp);
+ window.addEventListener('pointercancel', handleCancel);
+ window.addEventListener('keydown', handleKeyDown, true);
+ window.addEventListener('blur', handleBlur);
+ teardown.current = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ window.removeEventListener('pointercancel', handleCancel);
+ window.removeEventListener('keydown', handleKeyDown, true);
+ window.removeEventListener('blur', handleBlur);
+ teardown.current = null;
+ };
+ },
+ [latest, pointerX],
+ );
+
+ return { pointerX, session, startDrag };
+};
diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsx
index 964ad1d7491..5b329c3a227 100644
--- a/src/features/Electron/titlebar/TabBar/index.tsx
+++ b/src/features/Electron/titlebar/TabBar/index.tsx
@@ -1,16 +1,5 @@
'use client';
-import {
- closestCenter,
- DndContext,
- type DragEndEvent,
- KeyboardSensor,
- type Modifier,
- PointerSensor,
- useSensor,
- useSensors,
-} from '@dnd-kit/core';
-import { horizontalListSortingStrategy, SortableContext } from '@dnd-kit/sortable';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, type DropdownItem, DropdownMenu } from '@lobehub/ui/base-ui';
@@ -34,25 +23,20 @@ import { electronStylish } from '@/styles/electron';
import { useResolvedTabs } from './hooks/useResolvedTabs';
import { useStripWidth } from './hooks/useStripWidth';
+import { useTabDrag } from './hooks/useTabDrag';
import { TAB_SPRING } from './motion';
import { resolveTabScope } from './scope';
import { useStyles } from './styles';
import TabItem from './TabItem';
import {
- allocateTabWidths,
+ layoutStrip,
OVERFLOW_CONTROL_WIDTH,
- PINNED_DIVIDER_WIDTH,
- PINNED_TAB_WIDTH,
- resolvePlacements,
resolveTabTier,
+ type StripTab,
TAB_GAP,
} from './tabLayout';
const NEW_TAB_URL = '/';
-const NEW_TAB_BUTTON_WIDTH = 26 + TAB_GAP;
-
-// Tabs only reorder along the horizontal axis, so lock the drag transform to X.
-const restrictToHorizontalAxis: Modifier = ({ transform }) => ({ ...transform, y: 0 });
const TabBar = () => {
const styles = useStyles;
@@ -70,44 +54,43 @@ const TabBar = () => {
const closeOtherTabs = useElectronStore((s) => s.closeOtherTabs);
const closeLeftTabs = useElectronStore((s) => s.closeLeftTabs);
const closeRightTabs = useElectronStore((s) => s.closeRightTabs);
- const reorderTabs = useElectronStore((s) => s.reorderTabs);
+ const moveTab = useElectronStore((s) => s.moveTab);
const pinTab = useElectronStore((s) => s.pinTab);
const unpinTab = useElectronStore((s) => s.unpinTab);
const closeSplitView = useElectronStore((s) => s.closeSplitView);
const openTabInSplitView = useElectronStore((s) => s.openTabInSplitView);
- const sensors = useSensors(
- // Require a small drag distance so a plain click still activates the tab.
- useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
- useSensor(KeyboardSensor),
+ const tabIds = useMemo(() => tabs.map((tab) => tab.tab.id), [tabs]);
+ const pinnedCount = useMemo(() => tabs.filter((tab) => tab.tab.pinned).length, [tabs]);
+ const storeOrder = useMemo<StripTab[]>(
+ () => tabs.map((tab) => ({ id: tab.tab.id, pinned: !!tab.tab.pinned })),
+ [tabs],
);
- const tabIds = useMemo(() => tabs.map((tab) => tab.tab.id), [tabs]);
- const pinnedTabs = useMemo(() => tabs.filter((tab) => tab.tab.pinned), [tabs]);
- const flowTabs = useMemo(() => tabs.filter((tab) => !tab.tab.pinned), [tabs]);
-
- const layout = useMemo(() => {
- const pinnedWidth = pinnedTabs.length
- ? pinnedTabs.length * (PINNED_TAB_WIDTH + TAB_GAP) + PINNED_DIVIDER_WIDTH
- : 0;
-
- return allocateTabWidths({
- activeIndex: flowTabs.findIndex((tab) => tab.tab.id === activeTabId),
- count: flowTabs.length,
- usableWidth: Math.max(0, stripWidth - pinnedWidth - NEW_TAB_BUTTON_WIDTH),
- });
- }, [flowTabs, pinnedTabs.length, activeTabId, stripWidth]);
-
- const { dividerX, placements, total } = useMemo(
- () =>
- resolvePlacements({
- flowIds: flowTabs.map((tab) => tab.tab.id),
- pinnedIds: pinnedTabs.map((tab) => tab.tab.id),
- visibleIndices: layout.visibleIndices,
- widths: layout.widths,
- }),
- [flowTabs, pinnedTabs, layout],
+ const innerStripRef = useRef<HTMLDivElement>(null);
+ const drag = useTabDrag({
+ activeTabId,
+ onDrop: moveTab,
+ stripRef: innerStripRef,
+ stripWidth,
+ tabs: storeOrder,
+ });
+
+ const stripOrder = useMemo(() => {
+ if (!drag.session) return storeOrder;
+
+ const { id, pinned, toIndex } = drag.session;
+ const rest = storeOrder.filter((tab) => tab.id !== id);
+ if (rest.length === storeOrder.length) return storeOrder;
+
+ return [...rest.slice(0, toIndex), { id, pinned }, ...rest.slice(toIndex)];
+ }, [storeOrder, drag.session]);
+
+ const { dividerX, hiddenCount, placements, total, visibleIndices } = useMemo(
+ () => layoutStrip({ activeId: activeTabId, stripWidth, tabs: stripOrder }),
+ [activeTabId, stripWidth, stripOrder],
);
+ const stripPinnedCount = stripOrder.filter((tab) => tab.pinned).length;
const tabsById = useMemo(() => new Map(tabs.map((tab) => [tab.tab.id, tab])), [tabs]);
@@ -155,20 +138,28 @@ const TabBar = () => {
return buildWorkspaceAwarePath(NEW_TAB_URL, activeSlug);
}, [location.pathname, location.search]);
- const handleDragEnd = useCallback(
- (event: DragEndEvent) => {
- const { active, over } = event;
- if (!over || active.id === over.id) return;
-
- const fromIndex = tabIds.indexOf(active.id as string);
- const toIndex = tabIds.indexOf(over.id as string);
- if (fromIndex < 0 || toIndex < 0) return;
+ const handleMoveBy = useCallback(
+ (id: string, delta: -1 | 1) => {
+ const index = storeOrder.findIndex((tab) => tab.id === id);
+ const neighbour = storeOrder[index + delta];
+ if (index < 0 || !neighbour || neighbour.pinned !== storeOrder[index].pinned) return;
- reorderTabs(fromIndex, toIndex);
+ moveTab(id, index + delta, neighbour.pinned);
},
- [tabIds, reorderTabs],
+ [storeOrder, moveTab],
);
+ const dragFollow = useMemo(() => {
+ const placement = placements.find((item) => item.id === drag.session?.id);
+ if (!drag.session || !placement) return undefined;
+
+ return {
+ grabFraction: drag.session.grabFraction,
+ maxX: total - placement.width,
+ pointerX: drag.pointerX,
+ };
+ }, [drag.session, drag.pointerX, placements, total]);
+
const handleActivate = useCallback(
(id: string) => {
switchTab(id);
@@ -238,17 +229,16 @@ const TabBar = () => {
});
const overflowItems = useCallback((): DropdownItem[] => {
- const visible = new Set(layout.visibleIndices);
-
- return flowTabs
- .map((tab, index) => ({ index, tab }))
- .filter(({ index }) => !visible.has(index))
- .map(({ tab }) => ({
- key: tab.tab.id,
- label: tab.meta.title,
- onClick: () => handleActivate(tab.tab.id),
- }));
- }, [flowTabs, layout.visibleIndices, handleActivate]);
+ const visible = new Set(visibleIndices);
+
+ return stripOrder
+ .filter((tab) => !tab.pinned)
+ .filter((_, index) => !visible.has(index))
+ .flatMap(({ id }) => {
+ const tab = tabsById.get(id);
+ return tab ? [{ key: id, label: tab.meta.title, onClick: () => handleActivate(id) }] : [];
+ });
+ }, [stripOrder, visibleIndices, tabsById, handleActivate]);
if (tabs.length === 0) return null;
@@ -268,58 +258,52 @@ const TabBar = () => {
>
{measured && (
<>
- <DndContext
- collisionDetection={closestCenter}
- modifiers={[restrictToHorizontalAxis]}
- sensors={sensors}
- onDragEnd={handleDragEnd}
- >
- <SortableContext items={tabIds} strategy={horizontalListSortingStrategy}>
- {/* One keyed list for pinned and flowing tabs alike. Rendering them as two
- sibling arrays scoped their keys separately, so pinning unmounted the tab
- from one and mounted a fresh one in the other — losing its springs, which
- is why the tab used to pop rather than travel. */}
- <m.div className={styles.strip} style={{ width: springTotal }}>
- {placements.map((placement) => {
- const tab = tabsById.get(placement.id);
- if (!tab) return null;
-
- return (
- <TabItem
- enterWidth={settleInstantly ? placement.width : 0}
- enterX={settleInstantly ? placement.x : previousTotal.current}
- index={tabIds.indexOf(placement.id)}
- isActive={placement.id === activeTabId}
- item={tab}
- key={placement.id}
- pinnedCount={pinnedTabs.length}
- splitViewEnabled={splitViewEnabled}
- tier={resolveTabTier(placement.width)}
- totalCount={tabs.length}
- width={placement.width}
- x={placement.x}
- isSplitVisible={
- splitView?.primaryTabId === placement.id ||
- splitView?.secondaryTabId === placement.id
- }
- onActivate={handleActivate}
- onClose={handleClose}
- onCloseLeft={handleCloseLeft}
- onCloseOthers={handleCloseOthers}
- onCloseRight={handleCloseRight}
- onCloseSplitView={closeSplitView}
- onOpenInSplitView={openTabInSplitView}
- onTogglePin={handleTogglePin}
- />
- );
- })}
- <m.span
- className={styles.pinnedDivider}
- style={{ opacity: pinnedTabs.length > 0 ? 1 : 0, x: springDividerX }}
+ {/* One keyed list for pinned and flowing tabs alike. Rendering them as two
+ sibling arrays scoped their keys separately, so pinning unmounted the tab
+ from one and mounted a fresh one in the other — losing its springs, which
+ is why the tab used to pop rather than travel. */}
+ <m.div className={styles.strip} ref={innerStripRef} style={{ width: springTotal }}>
+ {placements.map((placement) => {
+ const tab = tabsById.get(placement.id);
+ if (!tab) return null;
+
+ return (
+ <TabItem
+ drag={drag.session?.id === placement.id ? dragFollow : undefined}
+ enterWidth={settleInstantly ? placement.width : 0}
+ enterX={settleInstantly ? placement.x : previousTotal.current}
+ index={tabIds.indexOf(placement.id)}
+ isActive={placement.id === activeTabId}
+ item={tab}
+ key={placement.id}
+ pinnedCount={pinnedCount}
+ splitViewEnabled={splitViewEnabled}
+ tier={resolveTabTier(placement.width)}
+ totalCount={tabs.length}
+ width={placement.width}
+ x={placement.x}
+ isSplitVisible={
+ splitView?.primaryTabId === placement.id ||
+ splitView?.secondaryTabId === placement.id
+ }
+ onActivate={handleActivate}
+ onClose={handleClose}
+ onCloseLeft={handleCloseLeft}
+ onCloseOthers={handleCloseOthers}
+ onCloseRight={handleCloseRight}
+ onCloseSplitView={closeSplitView}
+ onDragStart={drag.startDrag}
+ onMoveBy={handleMoveBy}
+ onOpenInSplitView={openTabInSplitView}
+ onTogglePin={handleTogglePin}
/>
- </m.div>
- </SortableContext>
- </DndContext>
+ );
+ })}
+ <m.span
+ className={styles.pinnedDivider}
+ style={{ opacity: stripPinnedCount > 0 ? 1 : 0, x: springDividerX }}
+ />
+ </m.div>
<ActionIcon
className={cx(electronStylish.nodrag, styles.newTabButton)}
disabled={!canCreate}
@@ -328,7 +312,7 @@ const TabBar = () => {
title={canCreate ? t('tab.newTab') : reason}
onClick={canCreate ? () => handleNewTab() : undefined}
/>
- {layout.hiddenCount > 0 && (
+ {hiddenCount > 0 && (
<DropdownMenu items={overflowItems} placement={'bottomRight'}>
<Flexbox
horizontal
@@ -336,10 +320,10 @@ const TabBar = () => {
className={cx(electronStylish.nodrag, styles.overflowButton)}
gap={2}
style={{ width: OVERFLOW_CONTROL_WIDTH }}
- title={t('tab.overflow', { count: layout.hiddenCount })}
+ title={t('tab.overflow', { count: hiddenCount })}
>
<ChevronDown size={12} />
- {layout.hiddenCount}
+ {hiddenCount}
</Flexbox>
</DropdownMenu>
)}
diff --git a/src/features/Electron/titlebar/TabBar/styles.ts b/src/features/Electron/titlebar/TabBar/styles.ts
index 2f269b5e54c..fd33124a8e5 100644
--- a/src/features/Electron/titlebar/TabBar/styles.ts
+++ b/src/features/Electron/titlebar/TabBar/styles.ts
@@ -101,7 +101,9 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
background-color: transparent;
- transition: background-color 0.15s ${cssVar.motionEaseInOut};
+ transition:
+ background-color 0.15s ${cssVar.motionEaseInOut},
+ box-shadow 0.15s ${cssVar.motionEaseInOut};
&:hover {
background-color: ${cssVar.colorFillQuaternary};
@@ -214,7 +216,6 @@ export const useStyles = createStaticStyles(({ css, cssVar }) => ({
`,
tabDragging: css`
cursor: grabbing;
- z-index: 1;
background-color: ${cssVar.colorBgElevated};
box-shadow: ${cssVar.boxShadowSecondary};
`,
diff --git a/src/features/Electron/titlebar/TabBar/tabDrag.test.ts b/src/features/Electron/titlebar/TabBar/tabDrag.test.ts
new file mode 100644
index 00000000000..16d36ac3540
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabDrag.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveDropTarget, rubberBand } from './tabDrag';
+import { layoutStrip, type StripTab } from './tabLayout';
+
+const flow = (...ids: string[]): StripTab[] => ids.map((id) => ({ id, pinned: false }));
+const pinned = (...ids: string[]): StripTab[] => ids.map((id) => ({ id, pinned: true }));
+const ids = (tabs: StripTab[]) => tabs.map((tab) => tab.id);
+const pinnedIds = (tabs: StripTab[]) => tabs.filter((tab) => tab.pinned).map((tab) => tab.id);
+
+const WIDE_STRIP = 1200;
+
+describe('resolveDropTarget', () => {
+ it('moves a tab to the slot nearest its centre within the flowing run', () => {
+ const tabs = [...pinned('p'), ...flow('a', 'b', 'c')];
+
+ const result = resolveDropTarget({
+ activeId: 'a',
+ draggedId: 'a',
+ grabFraction: 0.5,
+ pointerX: 551,
+ stripWidth: WIDE_STRIP,
+ tabs,
+ });
+
+ expect(ids(result)).toEqual(['p', 'b', 'c', 'a']);
+ expect(pinnedIds(result)).toEqual(['p']);
+ });
+
+ it('reorders within the pinned run', () => {
+ const tabs = [...pinned('p', 'q'), ...flow('a')];
+
+ const result = resolveDropTarget({
+ activeId: 'a',
+ draggedId: 'q',
+ grabFraction: 0.5,
+ pointerX: 10,
+ stripWidth: WIDE_STRIP,
+ tabs,
+ });
+
+ expect(ids(result)).toEqual(['q', 'p', 'a']);
+ expect(pinnedIds(result)).toEqual(['q', 'p']);
+ });
+
+ it('pins a flowing tab dragged left of the divider', () => {
+ const tabs = [...pinned('p'), ...flow('a', 'b', 'c')];
+
+ const result = resolveDropTarget({
+ activeId: 'b',
+ draggedId: 'b',
+ grabFraction: 0.5,
+ pointerX: 10,
+ stripWidth: WIDE_STRIP,
+ tabs,
+ });
+
+ expect(ids(result)).toEqual(['b', 'p', 'a', 'c']);
+ expect(pinnedIds(result)).toEqual(['b', 'p']);
+ });
+
+ it('unpins a pinned tab dragged right of the divider', () => {
+ const tabs = [...pinned('p'), ...flow('a', 'b', 'c')];
+
+ const result = resolveDropTarget({
+ activeId: 'p',
+ draggedId: 'p',
+ grabFraction: 0.5,
+ pointerX: 300,
+ stripWidth: WIDE_STRIP,
+ tabs,
+ });
+
+ expect(ids(result)).toEqual(['a', 'p', 'b', 'c']);
+ expect(pinnedIds(result)).toEqual([]);
+ });
+
+ it('keeps the current group while the pointer hovers on the divider', () => {
+ const resolveAt = (tabs: StripTab[]) =>
+ pinnedIds(
+ resolveDropTarget({
+ activeId: 'a',
+ draggedId: 'a',
+ grabFraction: 0.1,
+ pointerX: 58,
+ stripWidth: WIDE_STRIP,
+ tabs,
+ }),
+ );
+
+ expect(resolveAt([...pinned('p'), ...flow('a', 'b')])).toEqual(['p']);
+ expect(resolveAt([...pinned('p', 'a'), ...flow('b')])).toEqual(['p', 'a']);
+ });
+
+ it('swaps the wider active tab once it passes a narrower neighbour', () => {
+ const tabs = flow('a', 'b', 'c', 'd', 'e');
+ const stripWidth = 540;
+ const before = layoutStrip({ activeId: 'b', stripWidth, tabs }).placements;
+ const active = before.find((placement) => placement.id === 'b')!;
+ const next = before.find((placement) => placement.id === 'c')!;
+ expect(active.width).toBeGreaterThan(next.width);
+
+ const result = resolveDropTarget({
+ activeId: 'b',
+ draggedId: 'b',
+ grabFraction: 0.5,
+ pointerX: active.x + active.width / 2 + (next.width + 2) / 2 + 4,
+ stripWidth,
+ tabs,
+ });
+
+ expect(ids(result)).toEqual(['a', 'c', 'b', 'd', 'e']);
+ });
+
+ it('leaves tabs hidden in the overflow menu in their order', () => {
+ const tabs = flow('t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9');
+ const stripWidth = 400;
+ const { hiddenCount } = layoutStrip({ activeId: 't0', stripWidth, tabs });
+ expect(hiddenCount).toBeGreaterThan(0);
+ const visibleCount = tabs.length - hiddenCount;
+
+ const result = resolveDropTarget({
+ activeId: 't0',
+ draggedId: 't0',
+ grabFraction: 0.5,
+ pointerX: 2000,
+ stripWidth,
+ tabs,
+ });
+
+ expect(result[visibleCount - 1].id).toBe('t0');
+ expect(ids(result.slice(visibleCount))).toEqual(ids(tabs.slice(visibleCount)));
+ });
+});
+
+describe('rubberBand', () => {
+ it('passes values inside the range through', () => {
+ expect(rubberBand(50, 0, 100)).toBe(50);
+ });
+
+ it('resists overshoot and never exceeds the limit', () => {
+ const slight = rubberBand(110, 0, 100);
+ const far = rubberBand(10_000, 0, 100);
+
+ expect(slight).toBeGreaterThan(100);
+ expect(slight).toBeLessThan(110);
+ expect(far).toBeLessThan(140);
+ expect(rubberBand(-10, 0, 100)).toBeCloseTo(100 - slight, 5);
+ });
+});
diff --git a/src/features/Electron/titlebar/TabBar/tabDrag.ts b/src/features/Electron/titlebar/TabBar/tabDrag.ts
new file mode 100644
index 00000000000..8f9e34205fa
--- /dev/null
+++ b/src/features/Electron/titlebar/TabBar/tabDrag.ts
@@ -0,0 +1,78 @@
+import { layoutStrip, type StripTab } from './tabLayout';
+
+// Switching between the pinned and flowing runs reflows the whole strip (the divider
+// appears or moves, the tab morphs between pill and full width), so a pointer resting on
+// the divider must not flip the tab back and forth on every move.
+const GROUP_SWITCH_PENALTY = 12;
+const RUBBER_BAND_FACTOR = 0.55;
+const RUBBER_BAND_LIMIT = 40;
+
+export interface DropTargetInput {
+ activeId: string | null;
+ draggedId: string;
+ /** Where along the dragged tab the pointer holds it, as a fraction of its width. */
+ grabFraction: number;
+ /** Pointer x relative to the strip's origin. */
+ pointerX: number;
+ stripWidth: number;
+ /** Current order, with the dragged tab wherever the last preview put it. */
+ tabs: StripTab[];
+}
+
+/**
+ * Every slot of both runs is a candidate; the one whose centre is nearest the dragged tab's
+ * centre wins. The dragged tab's centre is measured at the candidate's own width, so a tab
+ * crossing into the pinned run is judged as the pill it would become, held at the same spot.
+ * Ties keep the earliest slot, which stops a tab dragged past the visible end from being
+ * filed behind the tabs hidden in the overflow menu.
+ */
+export const resolveDropTarget = ({
+ activeId,
+ draggedId,
+ grabFraction,
+ pointerX,
+ stripWidth,
+ tabs,
+}: DropTargetInput): StripTab[] => {
+ const dragged = tabs.find((tab) => tab.id === draggedId);
+ if (!dragged) return tabs;
+
+ const others = tabs.filter((tab) => tab.id !== draggedId);
+ let best = tabs;
+ let bestDistance = Infinity;
+
+ for (const pinned of [true, false]) {
+ const run = others.filter((tab) => tab.pinned === pinned);
+ const rest = others.filter((tab) => tab.pinned !== pinned);
+
+ for (let slot = 0; slot <= run.length; slot += 1) {
+ const candidateRun = [...run.slice(0, slot), { id: draggedId, pinned }, ...run.slice(slot)];
+ const candidate = pinned ? [...candidateRun, ...rest] : [...rest, ...candidateRun];
+ const placement = layoutStrip({ activeId, stripWidth, tabs: candidate }).placements.find(
+ (item) => item.id === draggedId,
+ );
+ if (!placement) continue;
+
+ const draggedCentre = pointerX + (0.5 - grabFraction) * placement.width;
+ const distance =
+ Math.abs(placement.x + placement.width / 2 - draggedCentre) +
+ (pinned === dragged.pinned ? 0 : GROUP_SWITCH_PENALTY);
+
+ if (distance < bestDistance) {
+ best = candidate;
+ bestDistance = distance;
+ }
+ }
+ }
+
+ return best;
+};
+
+const dampen = (overshoot: number): number =>
+ (1 - 1 / ((overshoot * RUBBER_BAND_FACTOR) / RUBBER_BAND_LIMIT + 1)) * RUBBER_BAND_LIMIT;
+
+export const rubberBand = (value: number, min: number, max: number): number => {
+ if (value < min) return min - dampen(min - value);
+ if (value > max) return max + dampen(value - max);
+ return value;
+};
diff --git a/src/features/Electron/titlebar/TabBar/tabLayout.ts b/src/features/Electron/titlebar/TabBar/tabLayout.ts
index 9537d1bcf4b..f8543c0a161 100644
--- a/src/features/Electron/titlebar/TabBar/tabLayout.ts
+++ b/src/features/Electron/titlebar/TabBar/tabLayout.ts
@@ -201,3 +201,47 @@ export const resolvePlacements = ({
return { dividerX, placements, total: Math.max(0, x - TAB_GAP) };
};
+
+export const NEW_TAB_BUTTON_WIDTH = 26 + TAB_GAP;
+
+export interface StripTab {
+ id: string;
+ pinned: boolean;
+}
+
+export interface StripLayoutInput {
+ activeId: string | null;
+ stripWidth: number;
+ tabs: StripTab[];
+}
+
+export interface StripLayout extends TabPlacementResult {
+ hiddenCount: number;
+ /** Indices into the unpinned tabs, in render order. */
+ visibleIndices: number[];
+}
+
+export const layoutStrip = ({ activeId, stripWidth, tabs }: StripLayoutInput): StripLayout => {
+ const pinnedIds = tabs.filter((tab) => tab.pinned).map((tab) => tab.id);
+ const flowIds = tabs.filter((tab) => !tab.pinned).map((tab) => tab.id);
+ const pinnedWidth = pinnedIds.length
+ ? pinnedIds.length * (PINNED_TAB_WIDTH + TAB_GAP) + PINNED_DIVIDER_WIDTH
+ : 0;
+
+ const layout = allocateTabWidths({
+ activeIndex: activeId === null ? -1 : flowIds.indexOf(activeId),
+ count: flowIds.length,
+ usableWidth: Math.max(0, stripWidth - pinnedWidth - NEW_TAB_BUTTON_WIDTH),
+ });
+
+ return {
+ ...resolvePlacements({
+ flowIds,
+ pinnedIds,
+ visibleIndices: layout.visibleIndices,
+ widths: layout.widths,
+ }),
+ hiddenCount: layout.hiddenCount,
+ visibleIndices: layout.visibleIndices,
+ };
+};
diff --git a/src/store/electron/actions/__tests__/tabPages.test.ts b/src/store/electron/actions/__tests__/tabPages.test.ts
index 38185c82335..374401fd5f5 100644
--- a/src/store/electron/actions/__tests__/tabPages.test.ts
+++ b/src/store/electron/actions/__tests__/tabPages.test.ts
@@ -710,27 +710,55 @@ describe('tabPages actions', () => {
expect(urls(result.current.tabs)).toEqual(['/b', '/a', '/c']);
});
- it('refuses a drag that would interleave pinned and unpinned tabs', () => {
+ it('reorders within the unpinned run', () => {
const result = seed();
act(() => {
result.current.pinTab('/c');
});
act(() => {
- result.current.reorderTabs(2, 0);
+ result.current.moveTab('/b', 1, false);
});
- expect(urls(result.current.tabs)).toEqual(['/c', '/a', '/b']);
+ expect(urls(result.current.tabs)).toEqual(['/c', '/b', '/a']);
+ });
+
+ it('pins a tab dropped into the pinned run at the dropped slot', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.moveTab('/b', 0, true);
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/b', '/c', '/a']);
+ expect(result.current.tabs[0].pinned).toBe(true);
+ });
+
+ it('unpins a tab dragged out of the pinned run', () => {
+ const result = seed();
+
+ act(() => {
+ result.current.pinTab('/c');
+ });
+ act(() => {
+ result.current.moveTab('/c', 2, false);
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/a', '/b', '/c']);
+ expect(result.current.tabs[2].pinned).toBe(false);
});
- it('still reorders within the unpinned run', () => {
+ it('clamps an index that would interleave pinned and unpinned tabs', () => {
const result = seed();
act(() => {
result.current.pinTab('/c');
});
act(() => {
- result.current.reorderTabs(2, 1);
+ result.current.moveTab('/b', 0, false);
});
expect(urls(result.current.tabs)).toEqual(['/c', '/b', '/a']);
diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.ts
index a07e2063ed9..157c7166573 100644
--- a/src/store/electron/actions/tabPages.ts
+++ b/src/store/electron/actions/tabPages.ts
@@ -290,19 +290,26 @@ export class TabPagesActionImpl {
this.#closeExcept((_, i) => i <= index, id, 'closeRightTabs');
};
- reorderTabs = (fromIndex: number, toIndex: number): void => {
+ moveTab = (id: string, toIndex: number, pinned: boolean): void => {
const { tabs } = this.#get();
- if (fromIndex < 0 || fromIndex >= tabs.length) return;
- if (toIndex < 0 || toIndex >= tabs.length) return;
- // Pinned tabs form a run at the head of the list; a drag across that boundary would
- // interleave the two groups and desync array order from render order.
- if (!!tabs[fromIndex].pinned !== !!tabs[toIndex].pinned) return;
-
- const newTabs = [...tabs];
- const [moved] = newTabs.splice(fromIndex, 1);
- newTabs.splice(toIndex, 0, moved);
+ const index = tabs.findIndex((t) => t.id === id);
+ if (index < 0) return;
- this.#set({ tabs: newTabs }, false, 'reorderTabs');
+ const rest = tabs.filter((_, i) => i !== index);
+ const pinnedCount = rest.filter((t) => t.pinned).length;
+ // Pinned tabs form a run at the head of the list; clamping into the dragged tab's own
+ // run keeps array order equal to render order.
+ const position = pinned
+ ? Math.min(Math.max(toIndex, 0), pinnedCount)
+ : Math.min(Math.max(toIndex, pinnedCount), rest.length);
+ if (position === index && !!tabs[index].pinned === pinned) return;
+
+ const moved: TabItem = { ...tabs[index], pinned };
+ this.#set(
+ { tabs: [...rest.slice(0, position), moved, ...rest.slice(position)] },
+ false,
+ 'moveTab',
+ );
this.#persist();
};