Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Clamp tab drag overshoot to the nearest edge tab (#1640)

Dimitri POSTOLOV84a6325c8c7a
diff --git a/packages/app/src/components/EditorTabs.test.ts b/packages/app/src/components/EditorTabs.test.ts
index 2e9e27d8b..22435b951 100644
--- a/packages/app/src/components/EditorTabs.test.ts
+++ b/packages/app/src/components/EditorTabs.test.ts
@@ -145,9 +145,6 @@ describe('EditorTabs source-level guards — tab context menu', () => {
expect(SRC).not.toContain('FileIcon');
expect(SRC).not.toContain('FolderOpen');
expect(SRC).toMatch(/<Button[\s\S]*?aria-label=\{t`Close \$\{accessibleLabel\}`\}/);
- expect(SRC).toMatch(
- /aria-label=\{t`Close \$\{accessibleLabel\}`\}[\s\S]*?className=["']mr-1\.5["']/,
- );
expect(SRC).toMatch(
/<button[\s\S]*?aria-label=\{accessibleLabel\}[\s\S]*?<\/button>\s*<TabPinOrCloseButton/,
);
@@ -164,11 +161,6 @@ describe('EditorTabs source-level guards — tab context menu', () => {
expect(SRC).not.toContain("isActive ? 'font-semibold' : 'font-medium'");
});
- test('placeholder close button reveals on hover without stealing clicks while hidden', () => {
- expect(SRC).toContain('pointer-events-none opacity-0');
- expect(SRC).toContain('group-hover:pointer-events-auto group-hover:opacity-100');
- });
-
test('tab context menu exposes close, close-others, and close-all actions', () => {
expect(SRC).toMatch(/<ContextMenuItem[\s\S]*?<Trans>Close<\/Trans>\s*<\/ContextMenuItem>/);
expect(SRC).toMatch(
@@ -221,7 +213,6 @@ describe('EditorTabs source-level guards — tab drag-reorder (US-004)', () => {
test('reuses the already-eager @dnd-kit packages — no new bundle deps', () => {
expect(SRC).toContain("from '@dnd-kit/core'");
expect(SRC).toContain("from '@dnd-kit/sortable'");
- expect(SRC).toContain("from '@dnd-kit/utilities'");
expect(SRC).toContain('DndContext');
expect(SRC).toContain('SortableContext');
expect(SRC).toContain('useSortable');
@@ -236,9 +227,7 @@ describe('EditorTabs source-level guards — tab drag-reorder (US-004)', () => {
test('KeyboardSensor with sortableKeyboardCoordinates wires keyboard accessibility (FR1d)', () => {
expect(SRC).toContain('KeyboardSensor');
expect(SRC).toContain('sortableKeyboardCoordinates');
- expect(SRC).toMatch(
- /useSensor\(\s*KeyboardSensor\s*,\s*\{\s*coordinateGetter:\s*sortableKeyboardCoordinates\s*\}\s*\)/,
- );
+ expect(SRC).toContain('keyboardCodes: TAB_KEYBOARD_DRAG_CODES');
});
test('SortableContext uses horizontalListSortingStrategy keyed off visibleTabIds', () => {
@@ -279,11 +268,9 @@ describe('EditorTabs source-level guards — tab drag-reorder (US-004)', () => {
expect(SRC).toMatch(/typeof\s+document\s*!==\s*['"]undefined['"]\s*\?\s*document\.body/);
});
- test('SortableTab composes refs and merges sortable transform without dropping inline style', () => {
+ test('SortableTab composes refs for dnd-kit and Radix wrappers', () => {
expect(SRC).toContain('function composedRef');
expect(SRC).toContain('setNodeRef(node)');
- expect(SRC).toContain('CSS.Transform.toString(transform)');
- expect(SRC).toMatch(/\.\.\.outerStyle/);
});
});
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 5cdba17d8..aeb8339d7 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -1,7 +1,6 @@
// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge-legacy/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
import {
- closestCenter,
DndContext,
type DragEndEvent,
KeyboardSensor,
@@ -16,13 +15,12 @@ import {
sortableKeyboardCoordinates,
useSortable,
} from '@dnd-kit/sortable';
-import { CSS } from '@dnd-kit/utilities';
import { RenamePathSuccessSchema } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, PinIcon, PlusIcon, XIcon } from 'lucide-react';
import {
- type CSSProperties,
type HTMLAttributes,
+ type KeyboardEvent,
type ReactNode,
type Ref,
useEffect,
@@ -66,6 +64,19 @@ import { hashFromDocName } from '@/lib/doc-hash';
import { emitDocumentsChanged } from '@/lib/documents-events';
import { parseServerResponse, parseSuccessOrWarn } from '@/lib/parse-server-response';
import { cn } from '@/lib/utils';
+import {
+ createTabReorderModifier,
+ getSortableTabClassName,
+ getSortableTabKeyDownAction,
+ getSortableTabStyle,
+ getTabCloseButtonClass,
+ getTabCloseButtonTabIndex,
+ measureTabReorderBounds,
+ TAB_KEYBOARD_DRAG_CODES,
+ TAB_REORDER_AUTO_SCROLL,
+ type TabReorderBounds,
+ tabRunCollisionDetection,
+} from './editor-tabs-chrome';
import { usePageList } from './PageListContext';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
@@ -79,18 +90,7 @@ const TAB_INACTIVE_CLASS = cn(
'bg-transparent hover:bg-muted focus-visible:bg-muted border-transparent hover:border-border focus-visible:border-border',
);
const TAB_BUTTON_CLASS =
- 'flex h-full min-w-0 flex-1 cursor-pointer items-center overflow-hidden px-3 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring/50';
-const TAB_CLOSE_BUTTON_CLASS =
- 'mr-1.5 flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none transition hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:opacity-100';
-
-function tabCloseButtonClass(isActive: boolean): string {
- return cn(
- TAB_CLOSE_BUTTON_CLASS,
- isActive
- ? 'opacity-100'
- : 'pointer-events-none opacity-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100',
- );
-}
+ 'flex h-full min-w-0 flex-1 cursor-pointer items-center overflow-hidden px-3 text-left text-[13px]';
function tabDomIdPart(docName: string): string {
return docName.replace(/[^A-Za-z0-9_-]/g, '-');
@@ -122,27 +122,32 @@ function stripRenameExtensionSuffix(value: string, docExt: string): string {
}
function SortableTab({
+ activateFromKeyboard,
+ className,
tabId,
disabled,
+ onKeyDown,
ref: outerRef,
style: outerStyle,
...rest
}: {
+ activateFromKeyboard?: () => void;
tabId: string;
disabled?: boolean;
ref?: Ref<HTMLDivElement>;
} & HTMLAttributes<HTMLDivElement>) {
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
- id: tabId,
- disabled,
- });
- const style: CSSProperties = {
- ...outerStyle,
- transform: CSS.Transform.toString(transform),
+ const { attributes, listeners, rect, setNodeRef, transform, transition, isDragging } =
+ useSortable({
+ id: tabId,
+ disabled,
+ });
+ const style = getSortableTabStyle({
+ activeWidth: rect.current?.width,
+ isDragging,
+ outerStyle,
+ transform,
transition,
- opacity: isDragging ? 0.5 : outerStyle?.opacity,
- zIndex: isDragging ? 1 : outerStyle?.zIndex,
- };
+ });
function composedRef(node: HTMLDivElement | null) {
setNodeRef(node);
if (typeof outerRef === 'function') outerRef(node);
@@ -150,7 +155,35 @@ function SortableTab({
outerRef.current = node;
}
}
- return <div ref={composedRef} style={style} {...rest} {...attributes} {...listeners} />;
+ const sortableKeyDown = listeners?.onKeyDown;
+ function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
+ onKeyDown?.(event);
+ const action = getSortableTabKeyDownAction({
+ event,
+ hasKeyboardActivation: Boolean(activateFromKeyboard),
+ isDragging,
+ });
+ if (action === 'ignore') return;
+ if (action === 'activate-tab' && activateFromKeyboard) {
+ event.preventDefault();
+ activateFromKeyboard();
+ return;
+ }
+ sortableKeyDown?.(event);
+ }
+ return (
+ // biome-ignore lint/a11y/noStaticElementInteractions: dnd-kit attributes inject role and tabIndex; this composes the sortable key listener.
+ <div
+ ref={composedRef}
+ data-editor-tab-sortable=""
+ className={getSortableTabClassName({ className, isDragging })}
+ style={style}
+ {...rest}
+ {...attributes}
+ {...listeners}
+ onKeyDown={handleKeyDown}
+ />
+ );
}
function EditorTabContextMenu({
@@ -228,12 +261,14 @@ function EditorTabContextMenu({
function TabPinOrCloseButton({
accessibleLabel,
closeTab,
+ isActive,
isPinned,
tabId,
unpinTab,
}: {
accessibleLabel: string;
closeTab: (tabId: string) => void;
+ isActive: boolean;
isPinned: boolean;
tabId: string;
unpinTab: (tabId: string) => void;
@@ -265,7 +300,8 @@ function TabPinOrCloseButton({
size="icon-xs"
aria-label={t`Close ${accessibleLabel}`}
data-testid="editor-tab-close-button"
- className="mr-1.5"
+ className={getTabCloseButtonClass(isActive)}
+ tabIndex={getTabCloseButtonTabIndex(isActive)}
onClick={(event) => {
event.stopPropagation();
closeTab(tabId);
@@ -316,6 +352,7 @@ export function EditorTabs() {
const { t } = useLingui();
const { pageMeta } = usePageList();
const tabListRef = useRef<HTMLDivElement>(null);
+ const [tabReorderBounds, setTabReorderBounds] = useState<TabReorderBounds | null>(null);
const [renamingTab, setRenamingTab] = useState<{ docName: string; tabId: string } | null>(null);
const [renameValue, setRenameValue] = useState('');
const [renameError, setRenameError] = useState<string | null>(null);
@@ -500,6 +537,7 @@ export function EditorTabs() {
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const newTabIdSet = new Set(newTabIds);
+ const tabReorderModifiers = [createTabReorderModifier(tabReorderBounds)];
function closeVisibleTabs(tabIds: readonly string[]) {
const documentTabIds: string[] = [];
@@ -519,10 +557,22 @@ export function EditorTabs() {
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ keyboardCodes: TAB_KEYBOARD_DRAG_CODES,
+ }),
);
+ function handleDragStart() {
+ setTabReorderBounds(measureTabReorderBounds(tabListRef.current));
+ }
+
+ function clearTabReorderBounds() {
+ setTabReorderBounds(null);
+ }
+
function handleDragEnd(event: DragEndEvent) {
+ clearTabReorderBounds();
const activeId = String(event.active.id);
const overId = event.over ? String(event.over.id) : null;
if (!overId || activeId === overId) return;
@@ -545,8 +595,12 @@ export function EditorTabs() {
<div className={cn('flex items-end gap-1', isElectronHost && '[-webkit-app-region:no-drag]')}>
<DndContext
sensors={sensors}
- collisionDetection={closestCenter}
+ autoScroll={TAB_REORDER_AUTO_SCROLL}
+ collisionDetection={tabRunCollisionDetection}
+ modifiers={tabReorderModifiers}
+ onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
+ onDragCancel={clearTabReorderBounds}
accessibility={{
container: typeof document !== 'undefined' ? document.body : undefined,
}}
@@ -569,6 +623,7 @@ export function EditorTabs() {
>
<SortableTab
tabId={tabId}
+ activateFromKeyboard={() => activateNewTab(tabId)}
aria-current={isActive ? 'page' : undefined}
data-active-tab={isActive ? 'true' : undefined}
className={cn(
@@ -591,6 +646,7 @@ export function EditorTabs() {
data-testid="editor-new-tab-placeholder-button"
className={TAB_BUTTON_CLASS}
onClick={() => activateNewTab(tabId)}
+ tabIndex={-1}
>
<span className="min-w-0 truncate">
<Trans>New tab</Trans>
@@ -600,7 +656,8 @@ export function EditorTabs() {
type="button"
aria-label={t`Close new tab`}
data-testid="editor-new-tab-placeholder-close"
- className={tabCloseButtonClass(isActive)}
+ className={getTabCloseButtonClass(isActive)}
+ tabIndex={getTabCloseButtonTabIndex(isActive)}
onClick={(event) => {
event.stopPropagation();
closeNewTab(tabId);
@@ -632,6 +689,7 @@ export function EditorTabs() {
>
<SortableTab
tabId={tabId}
+ activateFromKeyboard={() => activateTab(tabId)}
aria-current={isActive ? 'page' : undefined}
data-active-tab={isActive ? 'true' : undefined}
className={cn(
@@ -657,6 +715,7 @@ export function EditorTabs() {
onClick={() => {
activateTab(tabId);
}}
+ tabIndex={-1}
>
{prefix && (
<span
@@ -681,6 +740,7 @@ export function EditorTabs() {
<TabPinOrCloseButton
accessibleLabel={accessibleLabel}
closeTab={closeTab}
+ isActive={isActive}
isPinned={isPinned}
tabId={tabId}
unpinTab={unpinTab}
@@ -706,6 +766,7 @@ export function EditorTabs() {
>
<SortableTab
tabId={tabId}
+ activateFromKeyboard={() => activateTab(tabId)}
aria-current={isActive ? 'page' : undefined}
data-active-tab={isActive ? 'true' : undefined}
className={cn(
@@ -730,6 +791,7 @@ export function EditorTabs() {
onClick={() => {
activateTab(tabId);
}}
+ tabIndex={-1}
>
{prefix ? (
<span
@@ -753,6 +815,7 @@ export function EditorTabs() {
<TabPinOrCloseButton
accessibleLabel={accessibleLabel}
closeTab={closeTab}
+ isActive={isActive}
isPinned={isPinned}
tabId={tabId}
unpinTab={unpinTab}
@@ -783,6 +846,7 @@ export function EditorTabs() {
>
<SortableTab
tabId={tabId}
+ activateFromKeyboard={() => activateTab(tabId)}
disabled={isRenaming}
aria-current={isActive ? 'page' : undefined}
data-active-tab={isActive ? 'true' : undefined}
@@ -865,6 +929,7 @@ export function EditorTabs() {
event.stopPropagation();
enterRenameMode(tabId, docName);
}}
+ tabIndex={-1}
>
<TabConflictBadge docName={docName} />
<span className="flex min-w-0 flex-1 items-center">
@@ -875,6 +940,7 @@ export function EditorTabs() {
<TabPinOrCloseButton
accessibleLabel={accessibleLabel}
closeTab={closeTab}
+ isActive={isActive}
isPinned={isPinned}
tabId={tabId}
unpinTab={unpinTab}
diff --git a/packages/app/src/components/editor-tabs-chrome.test.ts b/packages/app/src/components/editor-tabs-chrome.test.ts
new file mode 100644
index 000000000..4e29519f9
--- /dev/null
+++ b/packages/app/src/components/editor-tabs-chrome.test.ts
@@ -0,0 +1,345 @@
+import { describe, expect, test } from 'bun:test';
+import { type CollisionDetection, KeyboardCode, type Modifier } from '@dnd-kit/core';
+import {
+ createTabReorderModifier,
+ DRAGGING_TAB_Z_INDEX,
+ getSortableTabClassName,
+ getSortableTabKeyDownAction,
+ getSortableTabStyle,
+ getTabCloseButtonClass,
+ getTabCloseButtonTabIndex,
+ measureTabReorderBounds,
+ shouldActivateSortableTabFromKeyDown,
+ TAB_KEYBOARD_DRAG_CODES,
+ TAB_REORDER_AUTO_SCROLL,
+ type TabReorderBounds,
+ tabRunCollisionDetection,
+} from './editor-tabs-chrome';
+
+type ModifierArgs = Parameters<Modifier>[0];
+type CollisionArgs = Parameters<CollisionDetection>[0];
+type SortableTabKeyDownEvent = Parameters<typeof shouldActivateSortableTabFromKeyDown>[0];
+type SortableTabKeyDownActionArgs = Parameters<typeof getSortableTabKeyDownAction>[0];
+
+function rect(left: number, width: number, top = 0, height = 20) {
+ return {
+ bottom: top + height,
+ height,
+ left,
+ right: left + width,
+ top,
+ width,
+ };
+}
+
+function fakeRootForRects(rects: Array<ReturnType<typeof rect>>): HTMLElement {
+ return {
+ querySelectorAll: () =>
+ rects.map((r) => ({
+ getBoundingClientRect: () => r,
+ })),
+ } as unknown as HTMLElement;
+}
+
+function modifierArgs(
+ bounds: TabReorderBounds | null,
+ x: number,
+ y: number,
+): { args: ModifierArgs; bounds: TabReorderBounds | null } {
+ return {
+ args: {
+ active: null,
+ activeNodeRect: rect(120, 60),
+ activatorEvent: null,
+ containerNodeRect: null,
+ draggingNodeRect: null,
+ overlayNodeRect: null,
+ over: null,
+ scrollableAncestorRects: [],
+ scrollableAncestors: [],
+ transform: { scaleX: 1, scaleY: 1, x, y },
+ windowRect: null,
+ },
+ bounds,
+ };
+}
+
+function collisionArgs(pointerX: number): CollisionArgs {
+ const droppableContainers = [
+ {
+ data: { current: undefined },
+ disabled: false,
+ id: 'tab-a',
+ key: 'tab-a',
+ node: { current: null },
+ rect: { current: null },
+ },
+ {
+ data: { current: undefined },
+ disabled: false,
+ id: 'tab-b',
+ key: 'tab-b',
+ node: { current: null },
+ rect: { current: null },
+ },
+ ];
+
+ return {
+ active: {
+ data: { current: undefined },
+ id: 'active-tab',
+ rect: { current: { initial: null, translated: null } },
+ },
+ collisionRect: rect(118, 40),
+ droppableContainers,
+ droppableRects: new Map([
+ ['tab-a', rect(100, 40)],
+ ['tab-b', rect(160, 40)],
+ ]),
+ pointerCoordinates: { x: pointerX, y: 10 },
+ };
+}
+
+function sortableTabKeyDownEvent(
+ code: KeyboardCode,
+ targetIsCurrentTarget = true,
+): SortableTabKeyDownEvent {
+ const currentTarget = {};
+ return {
+ code,
+ currentTarget,
+ target: targetIsCurrentTarget ? currentTarget : {},
+ };
+}
+
+function sortableTabKeyDownActionArgs({
+ code,
+ defaultPrevented = false,
+ hasKeyboardActivation = true,
+ isDragging = false,
+ targetIsCurrentTarget = true,
+}: {
+ code: KeyboardCode;
+ defaultPrevented?: boolean;
+ hasKeyboardActivation?: boolean;
+ isDragging?: boolean;
+ targetIsCurrentTarget?: boolean;
+}): SortableTabKeyDownActionArgs {
+ const currentTarget = {};
+ return {
+ event: {
+ code,
+ currentTarget,
+ defaultPrevented,
+ target: targetIsCurrentTarget ? currentTarget : {},
+ },
+ hasKeyboardActivation,
+ isDragging,
+ };
+}
+
+describe('editor tab chrome helpers', () => {
+ test('inactive close controls are hover-only and skipped by tab navigation', () => {
+ const className = getTabCloseButtonClass(false);
+
+ expect(className).toContain('opacity-0');
+ expect(className).toContain('pointer-events-none');
+ expect(className).toContain('group-hover:opacity-100');
+ expect(className).toContain('group-hover:pointer-events-auto');
+ expect(className).not.toContain('group-focus-within:opacity-100');
+ expect(className).not.toContain('focus-visible:opacity-100');
+ expect(getTabCloseButtonTabIndex(false)).toBe(-1);
+ });
+
+ test('active close controls are visible and keyboard reachable', () => {
+ const className = getTabCloseButtonClass(true);
+
+ expect(className).toContain('opacity-100');
+ expect(className).not.toContain('opacity-0');
+ expect(getTabCloseButtonTabIndex(true)).toBeUndefined();
+ });
+
+ test('dragged tabs use active-tab colors even when the source tab was inactive', () => {
+ const className = getSortableTabClassName({
+ className:
+ 'bg-transparent hover:bg-muted focus-visible:bg-muted border-transparent text-muted-foreground',
+ isDragging: true,
+ });
+
+ expect(className).toContain('bg-background');
+ expect(className).toContain('hover:bg-background');
+ expect(className).toContain('focus-visible:bg-background');
+ expect(className).toContain('border-border');
+ expect(className).toContain('text-foreground');
+ expect(className).not.toContain('bg-transparent');
+ expect(className).not.toContain('hover:bg-muted');
+ expect(className).not.toContain('focus-visible:bg-muted');
+ expect(className).not.toContain('border-transparent');
+ expect(className).not.toContain('text-muted-foreground');
+ });
+
+ test('non-dragged tabs preserve caller classes', () => {
+ expect(
+ getSortableTabClassName({
+ className: 'bg-transparent border-transparent text-muted-foreground',
+ isDragging: false,
+ }),
+ ).toBe('bg-transparent border-transparent text-muted-foreground');
+ });
+
+ test('keyboard drag starts with Space so Enter can activate the focused tab', () => {
+ expect(TAB_KEYBOARD_DRAG_CODES.start).toEqual([KeyboardCode.Space]);
+ expect(TAB_KEYBOARD_DRAG_CODES.start).not.toContain(KeyboardCode.Enter);
+ expect(TAB_KEYBOARD_DRAG_CODES.cancel).toEqual([KeyboardCode.Esc]);
+ expect(TAB_KEYBOARD_DRAG_CODES.end).toContain(KeyboardCode.Enter);
+ });
+
+ test('sortable tab keyboard activation handles Enter only on the outer tab', () => {
+ expect(shouldActivateSortableTabFromKeyDown(sortableTabKeyDownEvent(KeyboardCode.Enter))).toBe(
+ true,
+ );
+ expect(shouldActivateSortableTabFromKeyDown(sortableTabKeyDownEvent(KeyboardCode.Space))).toBe(
+ false,
+ );
+ expect(
+ shouldActivateSortableTabFromKeyDown(sortableTabKeyDownEvent(KeyboardCode.Enter, false)),
+ ).toBe(false);
+ });
+
+ test('sortable tab keydown action activates Enter only before dragging starts', () => {
+ expect(
+ getSortableTabKeyDownAction(sortableTabKeyDownActionArgs({ code: KeyboardCode.Enter })),
+ ).toBe('activate-tab');
+ expect(
+ getSortableTabKeyDownAction(
+ sortableTabKeyDownActionArgs({ code: KeyboardCode.Enter, isDragging: true }),
+ ),
+ ).toBe('delegate-sortable');
+ expect(
+ getSortableTabKeyDownAction(
+ sortableTabKeyDownActionArgs({ code: KeyboardCode.Enter, hasKeyboardActivation: false }),
+ ),
+ ).toBe('delegate-sortable');
+ expect(
+ getSortableTabKeyDownAction(sortableTabKeyDownActionArgs({ code: KeyboardCode.Space })),
+ ).toBe('delegate-sortable');
+ expect(
+ getSortableTabKeyDownAction(
+ sortableTabKeyDownActionArgs({
+ code: KeyboardCode.Enter,
+ targetIsCurrentTarget: false,
+ }),
+ ),
+ ).toBe('delegate-sortable');
+ });
+
+ test('sortable tab keydown action ignores caller-prevented events', () => {
+ expect(
+ getSortableTabKeyDownAction(
+ sortableTabKeyDownActionArgs({ code: KeyboardCode.Enter, defaultPrevented: true }),
+ ),
+ ).toBe('ignore');
+ });
+
+ test('tab reorder disables edge auto-scroll so pointer drags stay bounded', () => {
+ expect(TAB_REORDER_AUTO_SCROLL).toBe(false);
+ });
+
+ test('dragged tab style stays opaque and stacks above sibling tabs', () => {
+ const style = getSortableTabStyle({
+ isDragging: true,
+ outerStyle: { opacity: 0.9, zIndex: 3 },
+ transform: { scaleX: 1, scaleY: 1, x: 12, y: 8 },
+ transition: 'transform 150ms ease',
+ });
+
+ expect(style.opacity).toBe(0.9);
+ expect(style.transition).toBe('transform 150ms ease');
+ expect(style.zIndex).toBe(DRAGGING_TAB_Z_INDEX);
+ });
+
+ test('dragged tab style keeps measured width and removes transform scaling', () => {
+ const style = getSortableTabStyle({
+ activeWidth: 144,
+ isDragging: true,
+ transform: { scaleX: 0.5, scaleY: 0.75, x: 12, y: 8 },
+ transition: undefined,
+ });
+
+ expect(style.width).toBe(144);
+ expect(style.minWidth).toBe(144);
+ expect(style.maxWidth).toBe(144);
+ expect(style.flexBasis).toBe(144);
+ expect(style.transform).toBe('translate3d(12px, 8px, 0) scaleX(1) scaleY(1)');
+ });
+
+ test('non-dragged tab style preserves caller stacking', () => {
+ const style = getSortableTabStyle({
+ isDragging: false,
+ outerStyle: { opacity: 0.8, zIndex: 7 },
+ transform: null,
+ transition: undefined,
+ });
+
+ expect(style.opacity).toBe(0.8);
+ expect(style.zIndex).toBe(7);
+ });
+
+ test('measures reorder bounds from sortable tab nodes only', () => {
+ const bounds = measureTabReorderBounds(fakeRootForRects([rect(80, 40), rect(150, 60)]));
+
+ expect(bounds).toEqual({ left: 80, right: 210 });
+ });
+
+ test('measureTabReorderBounds returns null without a tab root', () => {
+ expect(measureTabReorderBounds(null)).toBeNull();
+ });
+
+ test('measureTabReorderBounds returns null when no sortable tab nodes are present', () => {
+ expect(measureTabReorderBounds(fakeRootForRects([]))).toBeNull();
+ });
+
+ test('horizontal modifier clamps x to measured tab bounds and removes y movement', () => {
+ const { args, bounds } = modifierArgs({ left: 100, right: 220 }, 200, 48);
+ const clampedRight = createTabReorderModifier(bounds)(args);
+
+ expect(clampedRight.x).toBe(40);
+ expect(clampedRight.y).toBe(0);
+
+ const leftInput = modifierArgs({ left: 100, right: 220 }, -100, -24);
+ const clampedLeft = createTabReorderModifier(leftInput.bounds)(leftInput.args);
+
+ expect(clampedLeft.x).toBe(-20);
+ expect(clampedLeft.y).toBe(0);
+ });
+
+ test('horizontal modifier without measured bounds only removes y movement', () => {
+ const { args } = modifierArgs(null, 50, 30);
+ const result = createTabReorderModifier(null)(args);
+
+ expect(result.x).toBe(50);
+ expect(result.y).toBe(0);
+ });
+
+ test('collision detection clamps pointer overshoot to the nearest edge tab', () => {
+ expect(tabRunCollisionDetection(collisionArgs(90))[0]?.id).toBe('tab-a');
+ expect(tabRunCollisionDetection(collisionArgs(210))[0]?.id).toBe('tab-b');
+ });
+
+ test('collision detection delegates within the tab run', () => {
+ const collisions = tabRunCollisionDetection(collisionArgs(125));
+
+ expect(collisions.length).toBeGreaterThan(0);
+ expect(collisions[0]?.id).toBe('tab-a');
+ });
+
+ test('collision detection delegates when pointer coordinates are absent for keyboard drag', () => {
+ const collisions = tabRunCollisionDetection({
+ ...collisionArgs(125),
+ pointerCoordinates: null,
+ });
+
+ expect(collisions.length).toBeGreaterThan(0);
+ expect(collisions[0]?.id).toBe('tab-a');
+ });
+});
diff --git a/packages/app/src/components/editor-tabs-chrome.ts b/packages/app/src/components/editor-tabs-chrome.ts
new file mode 100644
index 000000000..5670f305a
--- /dev/null
+++ b/packages/app/src/components/editor-tabs-chrome.ts
@@ -0,0 +1,161 @@
+import type { CollisionDetection, KeyboardCodes, Modifier } from '@dnd-kit/core';
+import { closestCenter, KeyboardCode } from '@dnd-kit/core';
+import { CSS, type Transform } from '@dnd-kit/utilities';
+import type { CSSProperties } from 'react';
+import { cn } from '@/lib/utils';
+
+type TabDroppableContainer = Parameters<CollisionDetection>[0]['droppableContainers'][number];
+type SortableTabKeyDownEvent = Pick<KeyboardEvent, 'code' | 'currentTarget' | 'target'>;
+type SortableTabKeyDownDecisionEvent = SortableTabKeyDownEvent &
+ Pick<KeyboardEvent, 'defaultPrevented'>;
+type SortableTabKeyDownAction = 'activate-tab' | 'delegate-sortable' | 'ignore';
+
+const TAB_CLOSE_BUTTON_CLASS =
+ 'mr-1.5 flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground outline-none transition hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/50';
+const DRAGGING_TAB_ACTIVE_CLASS =
+ 'border-border bg-background text-foreground hover:bg-background focus-visible:bg-background';
+export const DRAGGING_TAB_Z_INDEX = 20;
+export const TAB_REORDER_AUTO_SCROLL = false;
+export const TAB_KEYBOARD_DRAG_CODES = {
+ start: [KeyboardCode.Space],
+ cancel: [KeyboardCode.Esc],
+ end: [KeyboardCode.Space, KeyboardCode.Enter],
+} satisfies KeyboardCodes;
+
+export interface TabReorderBounds {
+ left: number;
+ right: number;
+}
+
+export function getTabCloseButtonClass(isActive: boolean): string {
+ return cn(
+ TAB_CLOSE_BUTTON_CLASS,
+ isActive
+ ? 'opacity-100'
+ : 'pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100',
+ );
+}
+
+export function getTabCloseButtonTabIndex(isActive: boolean): -1 | undefined {
+ return isActive ? undefined : -1;
+}
+
+export function getSortableTabClassName({
+ className,
+ isDragging,
+}: {
+ className?: string;
+ isDragging: boolean;
+}): string {
+ return cn(className, isDragging && DRAGGING_TAB_ACTIVE_CLASS);
+}
+
+export function shouldActivateSortableTabFromKeyDown(event: SortableTabKeyDownEvent): boolean {
+ return event.code === KeyboardCode.Enter && event.target === event.currentTarget;
+}
+
+export function getSortableTabKeyDownAction({
+ event,
+ hasKeyboardActivation,
+ isDragging,
+}: {
+ event: SortableTabKeyDownDecisionEvent;
+ hasKeyboardActivation: boolean;
+ isDragging: boolean;
+}): SortableTabKeyDownAction {
+ if (event.defaultPrevented) return 'ignore';
+ if (!isDragging && hasKeyboardActivation && shouldActivateSortableTabFromKeyDown(event)) {
+ return 'activate-tab';
+ }
+ return 'delegate-sortable';
+}
+
+export function getSortableTabStyle({
+ activeWidth,
+ isDragging,
+ outerStyle,
+ transform,
+ transition,
+}: {
+ activeWidth?: number | null;
+ isDragging: boolean;
+ outerStyle?: CSSProperties;
+ transform: Transform | null;
+ transition: string | undefined;
+}): CSSProperties {
+ const stableWidth = isDragging && activeWidth ? activeWidth : undefined;
+ return {
+ ...outerStyle,
+ transform: CSS.Transform.toString(transform ? { ...transform, scaleX: 1, scaleY: 1 } : null),
+ transition,
+ flexBasis: stableWidth ?? outerStyle?.flexBasis,
+ maxWidth: stableWidth ?? outerStyle?.maxWidth,
+ minWidth: stableWidth ?? outerStyle?.minWidth,
+ opacity: outerStyle?.opacity,
+ width: stableWidth ?? outerStyle?.width,
+ zIndex: isDragging ? DRAGGING_TAB_Z_INDEX : outerStyle?.zIndex,
+ };
+}
+
+export function measureTabReorderBounds(root: HTMLElement | null): TabReorderBounds | null {
+ const tabNodes = root?.querySelectorAll<HTMLElement>('[data-editor-tab-sortable]') ?? [];
+ let left = Number.POSITIVE_INFINITY;
+ let right = Number.NEGATIVE_INFINITY;
+
+ for (const tabNode of tabNodes) {
+ const rect = tabNode.getBoundingClientRect();
+ left = Math.min(left, rect.left);
+ right = Math.max(right, rect.right);
+ }
+
+ return Number.isFinite(left) && Number.isFinite(right) ? { left, right } : null;
+}
+
+export function createTabReorderModifier(bounds: TabReorderBounds | null): Modifier {
+ return ({ activeNodeRect, transform }) => {
+ const next = { ...transform, y: 0 };
+ if (!bounds || !activeNodeRect) return next;
+
+ const minX = bounds.left - activeNodeRect.left;
+ const maxX = bounds.right - activeNodeRect.right;
+ next.x = Math.min(Math.max(next.x, minX), maxX);
+ return next;
+ };
+}
+
+export const tabRunCollisionDetection: CollisionDetection = (args) => {
+ const { droppableContainers, droppableRects, pointerCoordinates } = args;
+ if (pointerCoordinates) {
+ let left = Number.POSITIVE_INFINITY;
+ let right = Number.NEGATIVE_INFINITY;
+ let leftContainer: TabDroppableContainer | null = null;
+ let rightContainer: TabDroppableContainer | null = null;
+
+ for (const container of droppableContainers) {
+ const rect = droppableRects.get(container.id);
+ if (!rect) continue;
+ if (rect.left < left) {
+ left = rect.left;
+ leftContainer = container;
+ }
+ if (rect.right > right) {
+ right = rect.right;
+ rightContainer = container;
+ }
+ }
+
+ if (!Number.isFinite(left) || !Number.isFinite(right)) {
+ return [];
+ }
+ const edgeContainer =
+ pointerCoordinates.x < left
+ ? leftContainer
+ : pointerCoordinates.x > right
+ ? rightContainer
+ : null;
+ if (edgeContainer)
+ return [{ id: edgeContainer.id, data: { droppableContainer: edgeContainer, value: 0 } }];
+ }
+
+ return closestCenter(args);
+};