Файли
openidea/src/ui/Tabs.tsx
T
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00

653 рядки
26 KiB
TypeScript

/**
* Tab strip with the design's accent underline. Roving focus (←/→ or ↑/↓ when
* vertical, Home/End), closable tabs (button, middle click, Delete), wheel
* scrolling and an overflow dropdown when tabs don't fit.
*/
import {
createContext,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { IconButton } from "./Button";
import { Menu, type MenuItem } from "./Menu";
import { HiddenTabsPopup } from "./HiddenTabsPopup";
import { tooltipAttrs } from "./Tooltip";
import { isOutsideWindow, registerDropTarget, startPointerDrag, type DragData } from "./pointerDrag";
import { Given } from "./T";
import styles from "./Tabs.module.css";
import { tx, useGivenTx } from "@/platform/i18n";
export interface TabItem {
id: string;
label: ReactNode;
/** Plain text used by the overflow menu and type-ahead when `label` isn't a string. */
text?: string;
/** The label is data (a file, session or result name): shown as written, never looked up in the catalog. */
verbatim?: boolean;
icon?: IconName | (string & {});
closable?: boolean;
/** With `onTogglePin`, the tab shows Unpin in the action slot. */
pinned?: boolean;
/**
* Visual only: hide this tab's close button without disabling its close
* gestures (middle click, Shift+click, Delete). IDEA's "Close button
* position: None" sets this to false; the tab stays closable.
*/
showCloseButton?: boolean;
/** Unsaved changes marker. */
modified?: boolean;
/** CSS colour for the label (VCS status etc.), e.g. `var(--vcs-modified)`. */
color?: string;
/** CSS colour the tab background is tinted with (IDEA's data source / file colours). */
tint?: string;
/** How strongly `tint` shows, e.g. `var(--file-tint-strength)`; defaults to `--tint-strength`. */
tintStrength?: string;
italic?: boolean;
/** Wavy error underline on the label: the file has errors (IDEA's problem files). */
error?: boolean;
/** Greyed out, e.g. a run tab whose process has ended. */
dimmed?: boolean;
tooltip?: string;
/** Trailing content (counts, badges). */
trailing?: ReactNode;
}
/**
* Drag & drop of tabs. Strips sharing a `type` (a custom MIME type such as
* `application/x-openidea-editor-tab`) accept each other's tabs; `onDrop`
* receives the dragged tab's payload and the insertion index in this strip.
*/
export interface TabsDnd {
type: string;
payload: (id: string) => string;
onDrop: (payload: string, index: number) => void;
/** Extra drag payloads accepted onto this strip (shown with the cross-strip insertion line). */
accepts?: (data: DragData) => boolean;
onExternalDrop?: (data: DragData, index: number) => void;
/**
* A dragged tab released with no accepting target (the pointer left the
* window): the editor uses it to detach the tab into a new window. Gets the
* dragged tab's payload and the release point in client coordinates.
*/
onDropOutside?: (payload: string, x: number, y: number) => void;
}
/**
* Insertion index for a drop at (`x`, `y`) given the tabs' extents in reading
* order, possibly wrapped into rows. Exported for tests.
*/
export function dropIndex(
x: number,
y: number,
rects: ReadonlyArray<{ left: number; top: number; width: number; height: number }>,
): number {
const first = rects[0];
const last = rects[rects.length - 1];
if (!first || !last) return 0;
// Above or below the tabs counts as their first or last row.
const py = Math.max(first.top, Math.min(y, last.top + last.height - 1));
for (let i = 0; i < rects.length; i++) {
const r = rects[i]!;
if (py < r.top || (py < r.top + r.height && x < r.left + r.width / 2)) return i;
}
return rects.length;
}
/** Display position of each id with `id` moved to insertion `index` (as passed to `onDrop`). */
function previewOrder(ids: readonly string[], id: string, index: number): Map<string, number> | null {
const from = ids.indexOf(id);
if (from < 0) return null;
const order = ids.filter((it) => it !== id);
order.splice(index > from ? index - 1 : index, 0, id);
return new Map(order.map((it, i) => [it, i]));
}
/** A tab strip as seen from its container: close or pin the selected tab when it can be. */
export interface TabStripHandle {
closeSelected(): boolean;
togglePinSelected(): boolean;
}
/**
* Lets a container (a tool window header) reach the tab strips rendered inside
* it: each `Tabs` registers itself with the nearest provided function.
*/
export const TabStripRegistry = createContext<((handle: TabStripHandle) => () => void) | null>(null);
export interface TabsProps {
items: TabItem[];
activeId: string | null;
onSelect: (id: string) => void;
onClose?: (id: string) => void;
/** Alt+click on a close button (IDEA: close all other tabs). */
onCloseOthers?: (id: string) => void;
/** Toggle the pinned state of a tab. */
onTogglePin?: (id: string) => void;
/** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */
closeOnShiftClick?: boolean;
onDoubleClick?: (id: string) => void;
/** Double click on the empty part of the strip (not on a tab or button), e.g. to maximize the editor. */
onBlankDoubleClick?: () => void;
onContextMenu?: (id: string, e: MouseEvent) => void;
/** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */
variant?: "editor" | "compact";
/** Content after the tabs (breadcrumbs, actions). */
trailing?: ReactNode;
className?: string;
"aria-label"?: string;
/** Tabpanel id prefix for `aria-controls`. */
panelIdPrefix?: string;
/**
* Tab from a tab moves focus into the selected tab's content (IDEA's table, list or tree)
* instead of the next control; returns false when there is nothing to focus.
*/
focusContent?: () => boolean;
/** Enables drag & drop reordering (and moving between strips of the same type). */
dnd?: TabsDnd;
/** `fit` keeps each tab within the scrolling strip. `squeeze` shrinks tabs together and `wrap` adds rows. */
layout?: "scroll" | "fit" | "squeeze" | "wrap";
/** For editor strips, show only tabs clipped by the strip in the overflow popup. */
hiddenTabsOnly?: boolean;
/** Side of the label the close button sits on. */
closePosition?: "right" | "left";
/** `vertical`: a column of tabs (editor tabs placed left / right); always scrolls, `layout` is ignored. */
orientation?: "horizontal" | "vertical";
/**
* Clicking a tab leaves keyboard focus where it was (a scope strip under a search field, like the
* Find in Files scopes); keyboard navigation of a focused strip is unchanged.
*/
keepFocusOnClick?: boolean;
}
export function Tabs({
items,
activeId,
onSelect,
onClose,
onCloseOthers,
onTogglePin,
closeOnShiftClick,
onDoubleClick,
onBlankDoubleClick,
onContextMenu,
variant = "editor",
trailing,
className,
panelIdPrefix,
focusContent,
dnd,
layout = "scroll",
hiddenTabsOnly = false,
closePosition = "right",
orientation = "horizontal",
keepFocusOnClick = false,
...aria
}: TabsProps) {
const vertical = orientation === "vertical";
const protectPinned = variant !== "editor" && !!onTogglePin;
const given = useGivenTx();
const scrollRef = useRef<HTMLDivElement>(null);
const tabRefs = useRef(new Map<string, HTMLButtonElement>());
const middlePressedTab = useRef<HTMLDivElement | null>(null);
const [overflow, setOverflow] = useState(false);
const [menuOpen, setMenuOpen] = useState(false);
const closeMenu = useCallback(() => setMenuOpen(false), [setMenuOpen]);
const moreRef = useRef<HTMLButtonElement>(null);
const [drop, setDrop] = useState<number | null>(null);
const [dragging, setDragging] = useState<string | null>(null);
const register = useContext(TabStripRegistry);
const latest = useRef({ items, activeId, onClose, onTogglePin, protectPinned });
useLayoutEffect(() => {
latest.current = { items, activeId, onClose, onTogglePin, protectPinned };
});
useEffect(
() =>
register?.({
closeSelected: () => {
const { items, activeId, onClose, protectPinned } = latest.current;
const item = items.find((it) => it.id === activeId);
if (!item || !onClose || !canCloseTab(item, protectPinned)) return false;
onClose(item.id);
return true;
},
togglePinSelected: () => {
const { items, activeId, onTogglePin } = latest.current;
if (!onTogglePin || !items.some((it) => it.id === activeId)) return false;
onTogglePin(activeId!);
return true;
},
}),
[register],
);
const stripRef = useRef<HTMLDivElement>(null);
// Re-read on every drag event: items and handlers change while the strip stays registered.
const dropState = useRef({ items, dnd, vertical });
useLayoutEffect(() => {
dropState.current = { items, dnd, vertical };
});
// Set when the drag starts, before the strip re-renders for the first `over`.
const draggingRef = useRef<string | null>(null);
const dndType = dnd?.type;
useEffect(() => {
const el = stripRef.current;
if (!el || !dndType) return;
const indexAt = (x: number, y: number) => {
const { items, vertical } = dropState.current;
// A tab of this strip is placed among the others as they are laid out now, around its slot.
const others = items.filter((it) => it.id !== draggingRef.current);
const rects = others.map((it) => {
const r = tabRefs.current.get(it.id)?.parentElement?.getBoundingClientRect();
const box = { left: r?.left ?? 0, top: r?.top ?? 0, width: r?.width ?? 0, height: r?.height ?? 0 };
return vertical ? { left: box.top, top: box.left, width: box.height, height: box.width } : box;
});
const next = others[vertical ? dropIndex(y, x, rects) : dropIndex(x, y, rects)];
return next ? items.indexOf(next) : items.length;
};
return registerDropTarget(el, {
accepts: (type, data) => type === dropState.current.dnd?.type || !!dropState.current.dnd?.accepts?.(data),
over: (_, x, y) => setDrop(indexAt(x, y)),
leave: () => setDrop(null),
drop: (data, x, y) => {
setDrop(null);
const current = dropState.current.dnd;
const at = indexAt(x, y);
if (data.type === current?.type) current.onDrop(data.payload, at);
else current?.onExternalDrop?.(data, at);
},
});
}, [dndType]);
// Tab slots wholly in view as last observed, which needs no layout read: switching to one of
// them doesn't measure the strip (a forced layout of the window, mid-switch).
const inView = useRef(new Set<Element>());
// Bring a tab's whole slot (label + close button) into view. Narrowing the strip clips
// the active tab's close button (#1740), and clicking the already-active tab doesn't
// change `activeId`, so the strip must also reveal on clicks and resizes.
const revealTab = useCallback(
(id: string | null, always = false) => {
const scroller = scrollRef.current;
const tab = id ? tabRefs.current.get(id)?.parentElement : null;
if (!scroller || !tab || (!always && inView.current.has(tab))) return;
(vertical ? revealVertically : revealHorizontally)(scroller, tab);
},
[vertical],
);
const tabIds = items.map((it) => it.id).join("\n");
useEffect(() => {
const root = scrollRef.current;
if (!root || typeof IntersectionObserver === "undefined") return;
const seen = inView.current;
const io = new IntersectionObserver(
(entries) => {
for (const e of entries) {
if (e.intersectionRatio >= 1) seen.add(e.target);
else seen.delete(e.target);
}
},
{ root, threshold: 1 },
);
for (const tab of tabRefs.current.values()) if (tab.parentElement) io.observe(tab.parentElement);
return () => {
io.disconnect();
seen.clear();
};
}, [tabIds]);
const observedTabs = layout === "fit" ? tabIds : null;
useLayoutEffect(() => {
const el = scrollRef.current;
if (!el) return;
// A vertical strip shows its scrollbar instead of the overflow dropdown.
const measure = () => {
const overflowing = !vertical && el.scrollWidth > el.clientWidth + 1;
setOverflow(overflowing);
if (!overflowing && hiddenTabsOnly) closeMenu();
// A resize (e.g. the editor area narrowing) must scroll the active tab back
// into view instead of leaving its close button clipped until a tab switch.
revealTab(latest.current.activeId, true);
};
measure();
if (typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(measure);
ro.observe(el);
// A renamed tab can move or resize the selected slot without resizing the strip.
if (observedTabs) for (const tab of el.children) ro.observe(tab);
return () => ro.disconnect();
}, [items.length, observedTabs, revealTab, vertical, hiddenTabsOnly, closeMenu]);
useEffect(() => {
// The whole tab (label + close button) into view, without scrolling any outer container.
revealTab(activeId);
}, [activeId, revealTab]);
const focusTab = (index: number) => {
const item = items[(index + items.length) % items.length];
if (!item) return;
onSelect(item.id);
tabRefs.current.get(item.id)?.focus();
};
const onKeyDown = (e: KeyboardEvent, index: number, item: TabItem) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;
switch (e.key) {
case vertical ? "ArrowDown" : "ArrowRight":
focusTab(index + 1);
break;
case vertical ? "ArrowUp" : "ArrowLeft":
focusTab(index - 1);
break;
case "Home":
focusTab(0);
break;
case "End":
focusTab(items.length - 1);
break;
case "Delete":
case "Backspace":
if (onClose && canCloseTab(item, protectPinned)) onClose(item.id);
else return;
break;
case "Tab":
if (e.shiftKey || !focusContent?.()) return;
break;
default:
return;
}
e.preventDefault();
};
const menuItems: MenuItem[] = items.map((t) => ({
id: t.id,
label: t.verbatim
? (t.text ?? (typeof t.label === "string" ? t.label : t.id))
: given(t.text ?? (typeof t.label === "string" ? t.label : t.id)),
verbatim: true,
icon: t.icon,
checked: t.id === activeId ? true : undefined,
run: () => onSelect(t.id),
}));
// IDEA: a tab dragged within its strip leaves an empty slot the other tabs make room for;
// a tab dragged in from another strip shows an insertion line instead.
const order =
dragging !== null && drop !== null
? previewOrder(
items.map((it) => it.id),
dragging,
drop,
)
: null;
const marker = dragging === null ? drop : null;
const stripClass = clsx(
styles.strip,
styles[variant],
vertical ? styles.vertical : layout !== "scroll" && styles[layout],
closePosition === "left" && styles.closeLeft,
className,
);
return (
<div
className={stripClass}
ref={stripRef}
onDoubleClick={
onBlankDoubleClick
? (e) => {
// Only the strip's own background counts: tabs, buttons and trailing content handle their own clicks.
if (e.target === e.currentTarget || e.target === scrollRef.current) onBlankDoubleClick();
}
: undefined
}
>
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
<div
ref={scrollRef}
role="tablist"
aria-label={given(aria["aria-label"])}
aria-orientation={vertical ? "vertical" : undefined}
className={styles.scroller}
onWheel={(e) => {
const el = scrollRef.current;
if (el && !vertical && Math.abs(e.deltaY) > Math.abs(e.deltaX)) el.scrollLeft += e.deltaY;
}}
>
{items.map((item, index) => {
const selected = item.id === activeId;
const pinned = !!onTogglePin && !!item.pinned;
// Whether a tab can be closed at all (gestures and the button). A hidden
// close button is visual only: middle click, Shift+click and Delete still work.
const closable = !!onClose && canCloseTab(item, protectPinned);
const showClose = closable && !pinned && item.showCloseButton !== false;
const pinModified = pinned && variant === "editor" && item.modified;
return (
<div
key={item.id}
className={clsx(
styles.tab,
selected && styles.selected,
(showClose || pinned) && styles.closable,
dragging === item.id && styles.dragging,
marker === index && styles.dropBefore,
marker === items.length && index === items.length - 1 && styles.dropAfter,
item.tint && styles.tinted,
)}
style={
{
"--tab-tint": item.tint,
"--tab-tint-strength": item.tintStrength,
order: order?.get(item.id),
} as CSSProperties
}
onPointerDown={
dnd
? (e) => {
if ((closeOnShiftClick && e.shiftKey) || (e.target as Element).closest("[data-tab-close]"))
return;
startPointerDrag(
e,
e.currentTarget,
{ type: dnd.type, payload: dnd.payload(item.id) },
{
// The ghost keeps the strip's layout rules (close slot, insets).
ghostContext: stripClass,
onStart: () => {
draggingRef.current = item.id;
setDragging(item.id);
},
onEnd: (dragged, drop) => {
draggingRef.current = null;
setDragging(null);
if (!dragged || !drop || drop.accepted) return;
const outside = dnd.onDropOutside;
if (!outside) return;
const el = document.documentElement;
const r = el.getBoundingClientRect();
// The ghost (fixed, translated from the tab) never
// covers the release point, so a miss outside the
// viewport means the pointer left the window.
const rect =
r.width || r.height
? r
: { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight };
if (isOutsideWindow(rect, drop.x, drop.y)) outside(dnd.payload(item.id), drop.x, drop.y);
},
},
);
}
: undefined
}
onMouseDown={(e) => {
if (e.button !== 1 || !closable) return;
e.preventDefault();
middlePressedTab.current = e.currentTarget;
}}
onMouseLeave={(e) => {
if (middlePressedTab.current === e.currentTarget) middlePressedTab.current = null;
}}
onMouseUp={(e) => {
if (e.button !== 1 || middlePressedTab.current !== e.currentTarget) return;
middlePressedTab.current = null;
if (!closable) return;
// WebKitGTK pastes the primary selection on release. Cancel it before closing the tab moves focus.
e.preventDefault();
onClose!(item.id);
}}
onContextMenu={onContextMenu ? (e) => onContextMenu(item.id, e) : undefined}
>
<button
ref={(el) => {
if (el) tabRefs.current.set(item.id, el);
else tabRefs.current.delete(item.id);
}}
type="button"
role="tab"
id={panelIdPrefix ? `${panelIdPrefix}-tab-${item.id}` : undefined}
aria-controls={panelIdPrefix ? `${panelIdPrefix}-panel-${item.id}` : undefined}
aria-selected={selected}
aria-label={pinned && variant === "editor" && item.text ? `${item.text} ${tx("Pinned")}` : undefined}
tabIndex={selected || (!activeId && index === 0) ? 0 : -1}
className={clsx(styles.tabButton, item.dimmed && styles.dimmed)}
style={item.color ? { color: item.color } : undefined}
onMouseDown={keepFocusOnClick ? (e) => e.preventDefault() : undefined}
onClick={(e) => {
// Shift+click is mouse-only: a keyboard Enter with Shift held still selects.
if (closeOnShiftClick && e.shiftKey && e.detail > 0 && closable) {
e.preventDefault();
onClose!(item.id);
return;
}
onSelect(item.id);
// Revealing on every click: re-selecting the active tab doesn't change
// `activeId`, so the reveal effect wouldn't re-run (#1740).
revealTab(item.id);
}}
onDoubleClick={onDoubleClick ? () => onDoubleClick(item.id) : undefined}
onKeyDown={(e) => onKeyDown(e, index, item)}
{...tooltipAttrs(given(item.tooltip), undefined, true)}
>
{item.icon && <Icon name={item.icon} size={14} className={styles.tabIcon} />}
<span className={clsx(styles.tabLabel, item.italic && styles.italic, item.error && styles.error)}>
{typeof item.label === "string" && !item.verbatim ? <Given>{item.label}</Given> : item.label}
</span>
{item.trailing}
{item.modified && !showClose && !pinModified && (
<span className={styles.modified} aria-label={tx("Modified")} />
)}
</button>
{pinned && (
<span className={styles.closeSlot} data-tab-close>
<IconButton
icon="pin"
title="Unpin Tab"
size="small"
iconSize={14}
tabIndex={-1}
className={styles.unpin}
onClick={(e) => {
e.stopPropagation();
onTogglePin!(item.id);
}}
/>
{pinModified && <span className={styles.pinModified} aria-label={tx("Modified")} />}
</span>
)}
{showClose && (
<span className={styles.closeSlot} data-tab-close>
{item.modified && <span className={styles.modified} aria-label={tx("Modified")} />}
<IconButton
icon="close"
title="Close Tab"
size="small"
iconSize={11}
tabIndex={-1}
className={styles.close}
onClick={(e) => {
e.stopPropagation();
if (e.altKey && onCloseOthers) onCloseOthers(item.id);
else onClose!(item.id);
}}
/>
</span>
)}
</div>
);
})}
</div>
{overflow && (
<>
<IconButton
ref={moreRef}
icon="chevron-down"
title="Show Hidden Tabs"
size="small"
iconSize={10}
className={styles.more}
aria-haspopup={hiddenTabsOnly ? "grid" : "menu"}
aria-expanded={menuOpen}
onClick={() => setMenuOpen((v) => !v)}
/>
{hiddenTabsOnly ? (
menuOpen && (
<HiddenTabsPopup
anchor={moreRef}
scroller={scrollRef}
buttons={tabRefs}
items={items}
closePosition={closePosition}
onSelect={onSelect}
onCloseTab={onClose}
onCloseOthers={onCloseOthers}
onTogglePin={onTogglePin}
onDismiss={closeMenu}
/>
)
) : (
<Menu
open={menuOpen}
onClose={closeMenu}
anchor={moreRef}
items={menuItems}
placement="bottom-end"
aria-label="Tabs"
/>
)}
</>
)}
{!vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
</div>
);
}
function canCloseTab(item: TabItem, protectPinned: boolean): boolean {
return item.closable !== false && !(protectPinned && item.pinned);
}
/** Scrolls `scroller` horizontally just enough to show all of `child`. */
export function revealHorizontally(scroller: HTMLElement, child: HTMLElement) {
const s = scroller.getBoundingClientRect();
const c = child.getBoundingClientRect();
if (c.left < s.left) scroller.scrollLeft -= s.left - c.left;
else if (c.right > s.right) scroller.scrollLeft += Math.min(c.right - s.right, c.left - s.left);
}
/** Scrolls `scroller` vertically just enough to show all of `child`. */
export function revealVertically(scroller: HTMLElement, child: HTMLElement) {
const s = scroller.getBoundingClientRect();
const c = child.getBoundingClientRect();
if (c.top < s.top) scroller.scrollTop -= s.top - c.top;
else if (c.bottom > s.bottom) scroller.scrollTop += Math.min(c.bottom - s.bottom, c.top - s.top);
}