Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): support grid docking for plugin panels

david9c05ebccd1cc
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index 5a716e7812..24c75dbed6 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -6,9 +6,14 @@ import { ghostPanelKind, type GhostManifest, type InstalledGhost } from '../../s
import { minimizeGhostPanel, reconcileGhostPanelBubbles } from '../lib/ghostPanelBubbleState';
import { toast } from '../lib/toast';
import { usePanelMaximize } from '../layout/panelMaximize';
+import { usePaneFill } from '../layout/panePlacement';
import { usePanelWidth } from '../layout/paneWidths';
import { PanelChrome } from '../panels/PanelChrome';
-import { registerPanelKind, unregisterPanelKind, type PanelComponentProps } from '../panels/registry';
+import {
+ registerPanelKind,
+ unregisterPanelKind,
+ type PanelComponentProps,
+} from '../panels/registry';
import { extractIpcError } from '../utils/ipcError';
import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';
import { ghostInstallErrorKey } from './installErrorKey';
@@ -49,10 +54,9 @@ const PANEL_ENTER_ARMED_AT = Date.now() + 1500;
const PANEL_EXIT_MS = 180;
/** 意识面板宿主:标准头(PanelChrome)+ 沙箱自绘面板体(崩溃时错误接管)。 */
-function GhostPanel({
- manifest,
-}: PanelComponentProps & { manifest: GhostManifest }): ReactNode {
+function GhostPanel({ manifest }: PanelComponentProps & { manifest: GhostManifest }): ReactNode {
const kind = ghostPanelKind(manifest.id);
+ const fillContainer = usePaneFill();
// 宽度由引擎下发(fraction × 可用宽,缝把手可拖);兜底用清单 minWidth。
const width = usePanelWidth(kind) ?? manifest.panel?.minWidth ?? 300;
// 撑满态(引擎视图态):固定宽让位给 flex-1,树上的 fraction 账本不动。
@@ -114,21 +118,23 @@ function GhostPanel({
className={
isMaximized
? 'flex h-full min-w-0 flex-1'
- : `h-full shrink-0 overflow-hidden${enter ? ' ghost-panel-enter' : ''}${
- closing ? ' ghost-panel-exit' : ''
- }`
+ : fillContainer
+ ? 'flex h-full min-h-0 min-w-0 flex-1 overflow-hidden'
+ : `h-full shrink-0 overflow-hidden${enter ? ' ghost-panel-enter' : ''}${
+ closing ? ' ghost-panel-exit' : ''
+ }`
}
- style={isMaximized ? undefined : { width }}
+ style={isMaximized || fillContainer ? undefined : { width }}
>
<section
data-panel-drag-root={kind}
// 侧边分割线由布局引擎统一绘制(LayoutRoot layout-divider),面板不自画。
className={
- isMaximized
+ isMaximized || fillContainer
? 'flex h-full w-full min-w-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
: 'flex h-full shrink-0 flex-col overflow-hidden bg-[var(--panel-bg)]'
}
- style={isMaximized ? undefined : { width }}
+ style={isMaximized || fillContainer ? undefined : { width }}
>
<PanelChrome
title={manifest.panel?.title ?? manifest.name}
diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
index be53a559ae..7d6e8b5376 100644
--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx
+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
@@ -8,16 +8,14 @@ import {
type PaneNode,
} from '../../shared/layoutTree';
import { installGhostDevTools } from '../cindy-brain/ghostDevTools';
-import {
- ensureGhostPanelsRegistered,
- useGhostPanelsSync,
-} from '../cindy-brain/ghostPanels';
+import { ensureGhostPanelsRegistered, useGhostPanelsSync } from '../cindy-brain/ghostPanels';
import { isGhostPanelKindMinimized, useGhostPanelBubbleState } from '../lib/ghostPanelBubbleState';
import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';
import { registerBuiltinPanels } from '../panels/builtinPanels';
import { getPanelKind } from '../panels/registry';
import { installLayoutDevTools } from './layoutDevTools';
import { PanelMaximizeContext, type PanelMaximizeState } from './panelMaximize';
+import { PaneFillProvider } from './panePlacement';
import { PaneWidthProvider, useContentAvailableWidth } from './paneWidths';
/**
@@ -74,11 +72,15 @@ function isPanelKindVisible(kind: string): boolean {
}
/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */
-function PanelHost({ node }: { node: PaneNode }): ReactNode {
+function PanelHost({ node, fill = false }: { node: PaneNode; fill?: boolean }): ReactNode {
const def = getPanelKind(node.panelKind);
if (!def || !isPanelKindVisible(node.panelKind)) return null;
const Component = def.Component;
- return <Component paneId={node.id} />;
+ return (
+ <PaneFillProvider value={fill}>
+ <Component paneId={node.id} />
+ </PaneFillProvider>
+ );
}
interface SplitChildEntry {
@@ -100,6 +102,12 @@ interface ActiveSplitLedger {
scale: number;
}
+/** split 只有至少一个后代 pane 在场时才占布局空间。 */
+function isLayoutNodeVisible(node: LayoutNode): boolean {
+ if (node.type === 'pane') return isPanelKindVisible(node.panelKind);
+ return node.children.some((child) => isLayoutNodeVisible(child.node));
+}
+
/**
* 在场份额账本:过滤出可见子项并把份额在它们之间归一化(见文件头「在场份额」)。
* 隐藏子项的 fraction 不参与分配、也不被改写。
@@ -107,7 +115,7 @@ interface ActiveSplitLedger {
function activeSplitLedger(children: { fraction: number; node: LayoutNode }[]): ActiveSplitLedger {
const visible = children
.map((c, treeIndex) => ({ treeIndex, fraction: c.fraction, node: c.node }))
- .filter((e) => e.node.type !== 'pane' || isPanelKindVisible(e.node.panelKind));
+ .filter((e) => isLayoutNodeVisible(e.node));
const scale = visible.reduce((sum, e) => sum + e.fraction, 0);
return {
scale,
@@ -120,14 +128,20 @@ function activeSplitLedger(children: { fraction: number; node: LayoutNode }[]):
}
/** 过滤出可见子项(未注册/已抽离 kind 的 pane 不可见),保留树内原始下标供 fraction 操作寻址。 */
-function visibleSplitChildren(children: { fraction: number; node: LayoutNode }[]): SplitChildEntry[] {
+function visibleSplitChildren(
+ children: { fraction: number; node: LayoutNode }[],
+): SplitChildEntry[] {
return activeSplitLedger(children).entries;
}
/** 面板的最小像素宽:chat 硬下限 400,其余只有防拖丢兜底(见 NON_CHAT_FLOOR_PX)。 */
function paneMinPx(node: LayoutNode): number {
if (node.type === 'pane' && node.panelKind === 'chat-main') return CHAT_MIN_PX;
- return NON_CHAT_FLOOR_PX;
+ if (node.type === 'pane') return NON_CHAT_FLOOR_PX;
+ const childMins = node.children.map((child) => paneMinPx(child.node));
+ return node.direction === 'row'
+ ? childMins.reduce((sum, value) => sum + value, 0)
+ : Math.max(NON_CHAT_FLOOR_PX, ...childMins);
}
/**
@@ -150,7 +164,9 @@ export function normalizeSubMinFractions(
): Layout | null {
if (layout.content.type !== 'split' || layout.content.direction !== 'row') return null;
const children = layout.content.children;
- const chatIndex = children.findIndex((c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main');
+ const chatIndex = children.findIndex(
+ (c) => c.node.type === 'pane' && c.node.panelKind === 'chat-main',
+ );
if (chatIndex < 0) return null;
// 在场份额的比例尺(share × scale = 树份额)。此处不能复用 activeSplitLedger:
// 自愈是纯函数,可见性判定由入参 isRegistered 提供(测试注入)。
@@ -161,10 +177,14 @@ export function normalizeSubMinFractions(
let neededTotal = 0; // 在场份额口径的缺口总额
const bumps = new Map<number, number>(); // treeIndex → 目标在场份额
+ const nodeIsRegistered = (node: LayoutNode): boolean =>
+ node.type === 'pane'
+ ? isRegistered(node.panelKind)
+ : node.children.some((child) => nodeIsRegistered(child.node));
children.forEach((child, index) => {
const node = child.node;
- if (node.type !== 'pane' || node.panelKind === 'chat-main') return;
- if (!isRegistered(node.panelKind)) return; // 隐藏面板不渲染,不参与自愈
+ if (node.type === 'pane' && node.panelKind === 'chat-main') return;
+ if (!nodeIsRegistered(node)) return; // 隐藏面板/空 grid 不渲染,不参与自愈
const minShare = paneMinPx(node) / avail;
const share = child.fraction / scale;
if (share >= minShare) return;
@@ -189,22 +209,32 @@ export function normalizeSubMinFractions(
* 可用宽。chat-main 不进表(弹性 flex-1 吸收剩余);上限给中间留出 chat 的最小宽。
* live 覆盖里存的同样是在场份额(拖动与渲染同一口径)。
*/
-function computePanelWidths(
+interface RootWidthState {
+ panelWidths: Record<string, number>;
+ splitWidths: Record<string, number>;
+}
+
+function computeRootWidths(
layout: Layout,
live: Record<string, number> | null,
avail: number,
-): Record<string, number> {
- const out: Record<string, number> = {};
- if (layout.content.type !== 'split' || layout.content.direction !== 'row') return out;
+): RootWidthState {
+ const panelWidths: Record<string, number> = {};
+ const splitWidths: Record<string, number> = {};
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
+ return { panelWidths, splitWidths };
+ }
for (const entry of visibleSplitChildren(layout.content.children)) {
const node = entry.node;
- if (node.type !== 'pane' || node.panelKind === 'chat-main') continue;
+ if (node.type === 'pane' && node.panelKind === 'chat-main') continue;
const share = live?.[node.id] ?? entry.share;
const min = paneMinPx(node);
const max = Math.max(min, avail - CHAT_MIN_PX);
- out[node.panelKind] = Math.min(max, Math.max(min, Math.round(share * avail)));
+ const width = Math.min(max, Math.max(min, Math.round(share * avail)));
+ if (node.type === 'pane') panelWidths[node.panelKind] = width;
+ else splitWidths[node.id] = width;
}
- return out;
+ return { panelWidths, splitWidths };
}
/** 嵌套 split 用的静态分割线(嵌套布局今天不存在;交互化随真实需求补)。 */
@@ -219,17 +249,94 @@ function StaticDivider({ direction, id }: { direction: 'row' | 'column'; id: str
);
}
-/** 递归节点渲染:pane → PanelHost;嵌套 split → flex 容器(静态分割线)。 */
-function NodeView({ node }: { node: LayoutNode }): ReactNode {
- if (node.type === 'pane') return <PanelHost node={node} />;
- const visible = visibleSplitChildren(node.children);
+function containsPanelKind(node: LayoutNode, kind: string): boolean {
+ if (node.type === 'pane') return node.panelKind === kind;
+ return node.children.some((child) => containsPanelKind(child.node, kind));
+}
+
+interface NodeViewProps {
+ node: LayoutNode;
+ fillPane?: boolean;
+ liveFractions: Record<string, number> | null;
+ maximizedKind: string | null;
+ onLive: (live: Record<string, number> | null) => void;
+ onCommitted: (layout: Layout) => void;
+}
+
+/** 递归节点渲染:pane → PanelHost;column split → 插件 grid + 可拖横缝。 */
+function NodeView({
+ node,
+ fillPane = false,
+ liveFractions,
+ maximizedKind,
+ onLive,
+ onCommitted,
+}: NodeViewProps): ReactNode {
+ const splitRef = useRef<HTMLDivElement>(null);
+ if (node.type === 'pane') return <PanelHost node={node} fill={fillPane} />;
+ const ledger = activeSplitLedger(node.children);
+ const visible = ledger.entries;
const items: ReactNode[] = [];
visible.forEach((entry, i) => {
- if (i > 0) items.push(<StaticDivider key={`divider-${entry.node.id}`} direction={node.direction} id={entry.node.id} />);
- items.push(<NodeView key={entry.node.id} node={entry.node} />);
+ const entryHasMaximized =
+ maximizedKind !== null && containsPanelKind(entry.node, maximizedKind);
+ if (i > 0 && maximizedKind === null) {
+ const previous = visible[i - 1];
+ items.push(
+ node.direction === 'column' ? (
+ <ColumnDivider
+ key={`divider-${entry.node.id}`}
+ splitId={node.id}
+ top={previous}
+ bottom={entry}
+ containerRef={splitRef}
+ shareScale={ledger.scale}
+ onLive={onLive}
+ onCommitted={onCommitted}
+ />
+ ) : (
+ <StaticDivider
+ key={`divider-${entry.node.id}`}
+ direction={node.direction}
+ id={entry.node.id}
+ />
+ ),
+ );
+ }
+ const share = liveFractions?.[entry.node.id] ?? entry.share;
+ const hiddenByMaximize = maximizedKind !== null && !entryHasMaximized;
+ items.push(
+ <div
+ key={entry.node.id}
+ data-layout-node-id={entry.node.id}
+ className={`flex min-h-0 min-w-0 overflow-hidden ${
+ node.direction === 'column' ? 'w-full flex-col' : 'h-full flex-row'
+ } ${entryHasMaximized ? 'flex-1' : 'flex-none'}`}
+ style={
+ hiddenByMaximize
+ ? node.direction === 'column'
+ ? { height: 0 }
+ : { width: 0 }
+ : entryHasMaximized
+ ? undefined
+ : { flexBasis: `${share * 100}%` }
+ }
+ >
+ <NodeView
+ node={entry.node}
+ fillPane
+ liveFractions={liveFractions}
+ maximizedKind={maximizedKind}
+ onLive={onLive}
+ onCommitted={onCommitted}
+ />
+ </div>,
+ );
});
return (
<div
+ ref={splitRef}
+ data-layout-node-id={node.id}
className={`flex min-h-0 min-w-0 flex-1 ${node.direction === 'row' ? 'flex-row' : 'flex-col'}`}
>
{items}
@@ -262,12 +369,13 @@ interface RootDividerProps extends RootDividerPropsExtra {
onCommitted: (layout: Layout) => void;
}
-/** 起拖时实测某面板的元素宽;量不到 / 收成 0 宽返回 null(调用方回落账面)。 */
+/** 起拖时实测某布局节点的宽;split 量自己的 grid 列壳,pane 量标准拖拽根。 */
function measuredPanePx(node: LayoutNode): number | null {
- if (node.type !== 'pane') return null;
- const width = document
- .querySelector(`[data-panel-drag-root="${node.panelKind}"]`)
- ?.getBoundingClientRect().width;
+ const selector =
+ node.type === 'pane'
+ ? `[data-panel-drag-root="${node.panelKind}"]`
+ : `[data-layout-node-id="${node.id}"]`;
+ const width = document.querySelector(selector)?.getBoundingClientRect().width;
return typeof width === 'number' && width > 0 ? width : null;
}
@@ -330,8 +438,7 @@ function RootDivider({
// 实测可信直接用;量不到才回退账面/兜底,并保留 min 下限(与历史一致,不扰动)。
const basisPx = measured ?? Math.min(ledgerPx, fallbackPx ?? ledgerPx);
const pxRoom = basisPx - minPx;
- const floorRoom =
- shareScale > 0 ? (entry.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0;
+ const floorRoom = shareScale > 0 ? (entry.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0;
return Math.max(0, Math.min(pxRoom / avail, floorRoom));
};
@@ -406,6 +513,129 @@ function RootDivider({
);
}
+const GRID_PANE_MIN_HEIGHT_PX = 120;
+
+interface ColumnDividerProps {
+ splitId: string;
+ top: SplitChildEntry;
+ bottom: SplitChildEntry;
+ containerRef: React.RefObject<HTMLDivElement | null>;
+ shareScale: number;
+ onLive: (live: Record<string, number> | null) => void;
+ onCommitted: (layout: Layout) => void;
+}
+
+/** 插件 grid 的横向分割线:拖动调高度,双击均分相邻两格。 */
+function ColumnDivider({
+ splitId,
+ top,
+ bottom,
+ containerRef,
+ shareScale,
+ onLive,
+ onCommitted,
+}: ColumnDividerProps): ReactNode {
+ const [hover, setHover] = useState(false);
+ const draggingRef = useRef(false);
+
+ const commit = (amountToTop: number) => {
+ const treeAmount = amountToTop * shareScale;
+ if (treeAmount === 0) return;
+ try {
+ const current = window.electronAPI.layout.getStateSync().layout;
+ const op =
+ treeAmount > 0
+ ? transferSplitFraction(current, splitId, bottom.treeIndex, top.treeIndex, treeAmount)
+ : transferSplitFraction(current, splitId, top.treeIndex, bottom.treeIndex, -treeAmount);
+ if (!op.applied) return;
+ onCommitted(op.layout);
+ void window.electronAPI.layout.set(op.layout).catch(() => undefined);
+ } catch {
+ // IPC 不可用时放弃本次持久化,广播/树值保持原状。
+ }
+ };
+
+ const onPointerDown = (event: React.PointerEvent) => {
+ if (event.button !== 0 || draggingRef.current) return;
+ const available = containerRef.current?.getBoundingClientRect().height ?? 0;
+ if (!(available > 0)) return;
+ event.preventDefault();
+ draggingRef.current = true;
+ const startY = event.clientY;
+ const startTop = top.share;
+ const startBottom = bottom.share;
+ const topRoom = Math.max(
+ 0,
+ Math.min(
+ startTop - GRID_PANE_MIN_HEIGHT_PX / available,
+ shareScale > 0 ? (top.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0,
+ ),
+ );
+ const bottomRoom = Math.max(
+ 0,
+ Math.min(
+ startBottom - GRID_PANE_MIN_HEIGHT_PX / available,
+ shareScale > 0 ? (bottom.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0,
+ ),
+ );
+ let lastDelta = 0;
+
+ document.body.classList.add('resizing-pane');
+ const previousUserSelect = document.body.style.userSelect;
+ const previousCursor = document.documentElement.style.cursor;
+ document.body.style.userSelect = 'none';
+ document.documentElement.style.cursor = 'row-resize';
+
+ const onMove = (moveEvent: PointerEvent) => {
+ const delta = Math.min(
+ bottomRoom,
+ Math.max(-topRoom, (moveEvent.clientY - startY) / available),
+ );
+ lastDelta = delta;
+ onLive({ [top.node.id]: startTop + delta, [bottom.node.id]: startBottom - delta });
+ };
+ const finish = (commitChange: boolean) => {
+ draggingRef.current = false;
+ document.body.classList.remove('resizing-pane');
+ document.body.style.userSelect = previousUserSelect;
+ document.documentElement.style.cursor = previousCursor;
+ document.removeEventListener('pointermove', onMove);
+ document.removeEventListener('pointerup', onUp);
+ document.removeEventListener('pointercancel', onCancel);
+ if (commitChange && lastDelta !== 0) commit(lastDelta);
+ onLive(null);
+ };
+ const onUp = () => finish(true);
+ const onCancel = () => finish(false);
+ document.addEventListener('pointermove', onMove);
+ document.addEventListener('pointerup', onUp);
+ document.addEventListener('pointercancel', onCancel);
+ };
+
+ const onDoubleClick = () => {
+ const total = top.share + bottom.share;
+ commit(total / 2 - top.share);
+ };
+
+ return (
+ <div
+ aria-hidden
+ data-testid="layout-divider"
+ className="layout-divider-h relative"
+ style={hover ? { background: 'hsl(var(--sidebar-action-icon))' } : undefined}
+ >
+ <div
+ className="absolute inset-x-0 top-[-3px] z-10 h-[7px] cursor-row-resize"
+ style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}
+ onPointerEnter={() => setHover(true)}
+ onPointerLeave={() => setHover(false)}
+ onPointerDown={onPointerDown}
+ onDoubleClick={onDoubleClick}
+ />
+ </div>
+ );
+}
+
interface LayoutRootProps {
/**
* 内容区被全屏路由接管中(如设置页):只渲染 chat-main(接管方的宿主),
@@ -435,11 +665,10 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
const ghostBubbleState = useGhostPanelBubbleState();
// 首帧同步读取(sendSync):布局在第一帧就位,不出现默认布局闪现。
- const [layout, setLayout] = useState<Layout>(() => window.electronAPI.layout.getStateSync().layout);
- useEffect(
- () => window.electronAPI.layout.onChanged(({ layout: next }) => setLayout(next)),
- [],
+ const [layout, setLayout] = useState<Layout>(
+ () => window.electronAPI.layout.getStateSync().layout,
);
+ useEffect(() => window.electronAPI.layout.onChanged(({ layout: next }) => setLayout(next)), []);
// 撑满态(panelMaximize.tsx):会话级视图态,树账本不动。同 kind 再点还原。
const [maximizedKind, setMaximizedKind] = useState<string | null>(null);
@@ -456,17 +685,21 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
const [liveFractions, setLiveFractions] = useState<Record<string, number> | null>(null);
const availCtx = useContentAvailableWidth();
const avail = availCtx ?? AVAILABLE_WIDTH_FALLBACK;
- // eslint 会说 ghostWindowsState 没被直接读——它是 computePanelWidths 里
+ // eslint 会说 ghostWindowsState 没被直接读——它是 computeRootWidths 里
// isPanelKindVisible 的隐式数据源(模块级镜像),必须进 deps 才能感知抽离变化。
- const widths = useMemo(
- () => computePanelWidths(layout, liveFractions, avail),
+ const rootWidths = useMemo(
+ () => computeRootWidths(layout, liveFractions, avail),
[layout, liveFractions, avail, ghostWindowsState, ghostBubbleState],
);
// chat 实际渲染宽 ≈ 可用宽 − 各在场非 chat 面板宽度之和(拖缝余量的兜底估值,
// 见 RootDividerPropsExtra;起拖优先实测元素矩形)。
const chatRenderedPx = Math.max(
CHAT_MIN_PX,
- avail - Object.values(widths).reduce((sum, w) => sum + w, 0),
+ avail -
+ [...Object.values(rootWidths.panelWidths), ...Object.values(rootWidths.splitWidths)].reduce(
+ (sum, width) => sum + width,
+ 0,
+ ),
);
// 布局自愈:份额吃不饱最小宽 → 抬到位、chat 捐差额并写回树(画面与账本一致,
@@ -482,20 +715,32 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
void window.electronAPI.layout.set(fixed).catch(() => undefined);
}, 250);
return () => clearTimeout(timer);
- }, [availCtx, ghostBubbleState, ghostSyncVersion, ghostWindowsState, layout, liveFractions, suppressNonChatPanels]);
+ }, [
+ availCtx,
+ ghostBubbleState,
+ ghostSyncVersion,
+ ghostWindowsState,
+ layout,
+ liveFractions,
+ suppressNonChatPanels,
+ ]);
// 撑满目标失效自动还原:面板被卸下/停用(kind 注销)、抽离进独立窗口或
// pane 离开树时清态,免得下次回来以陈年撑满态惊回。接管态(设置页)只是
// 暂不渲染,不清 —— 退出接管原样恢复。
useEffect(() => {
if (maximizedKind === null || suppressNonChatPanels) return;
- const c = layout.content;
const present =
- c.type === 'split' &&
- c.children.some((ch) => ch.node.type === 'pane' && ch.node.panelKind === maximizedKind) &&
- isPanelKindVisible(maximizedKind);
+ containsPanelKind(layout.content, maximizedKind) && isPanelKindVisible(maximizedKind);
if (!present) setMaximizedKind(null);
- }, [layout, ghostBubbleState, ghostSyncVersion, ghostWindowsState, maximizedKind, suppressNonChatPanels]);
+ }, [
+ layout,
+ ghostBubbleState,
+ ghostSyncVersion,
+ ghostWindowsState,
+ maximizedKind,
+ suppressNonChatPanels,
+ ]);
const content = layout.content;
let body: ReactNode;
@@ -514,21 +759,30 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
const maximizedEntry =
maximizedKind === null
? undefined
- : visible.find(
- (e) =>
- e.node.type === 'pane' &&
- e.node.panelKind === maximizedKind &&
- e.node.panelKind !== 'chat-main',
- );
+ : visible.find((entry) => containsPanelKind(entry.node, maximizedKind));
if (maximizedEntry) {
body = (
<>
{visible.map((entry) =>
entry === maximizedEntry ? (
- <NodeView key={entry.node.id} node={entry.node} />
+ <div key={entry.node.id} className="flex min-h-0 min-w-0 flex-1 overflow-hidden">
+ <NodeView
+ node={entry.node}
+ liveFractions={liveFractions}
+ maximizedKind={maximizedKind}
+ onLive={setLiveFractions}
+ onCommitted={setLayout}
+ />
+ </div>
) : (
<div key={entry.node.id} aria-hidden className="flex w-0 flex-none overflow-hidden">
- <NodeView node={entry.node} />
+ <NodeView
+ node={entry.node}
+ liveFractions={liveFractions}
+ maximizedKind={maximizedKind}
+ onLive={setLiveFractions}
+ onCommitted={setLayout}
+ />
</div>
),
)}
@@ -536,7 +790,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
);
return (
<PanelMaximizeContext.Provider value={maximizeCtx}>
- <PaneWidthProvider value={widths}>{body}</PaneWidthProvider>
+ <PaneWidthProvider value={rootWidths.panelWidths}>{body}</PaneWidthProvider>
</PanelMaximizeContext.Provider>
);
}
@@ -544,8 +798,7 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
visible.forEach((entry, i) => {
if (i > 0) {
const prev = visible[i - 1];
- // 仅两侧都是 pane 的根级缝才可拖(嵌套 split 邻居的缝静态;今天不存在)。
- if (content.direction === 'row' && prev.node.type === 'pane' && entry.node.type === 'pane') {
+ if (content.direction === 'row') {
items.push(
<RootDivider
key={`divider-${entry.node.id}`}
@@ -561,19 +814,60 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
);
} else {
items.push(
- <StaticDivider key={`divider-${entry.node.id}`} direction={content.direction} id={entry.node.id} />,
+ <StaticDivider
+ key={`divider-${entry.node.id}`}
+ direction={content.direction}
+ id={entry.node.id}
+ />,
);
}
}
- items.push(<NodeView key={entry.node.id} node={entry.node} />);
+ if (entry.node.type === 'split' && content.direction === 'row') {
+ items.push(
+ <div
+ key={entry.node.id}
+ data-layout-root-child-id={entry.node.id}
+ className="flex h-full min-h-0 min-w-0 flex-none overflow-hidden"
+ style={{ width: rootWidths.splitWidths[entry.node.id] }}
+ >
+ <NodeView
+ node={entry.node}
+ fillPane
+ liveFractions={liveFractions}
+ maximizedKind={null}
+ onLive={setLiveFractions}
+ onCommitted={setLayout}
+ />
+ </div>,
+ );
+ } else {
+ items.push(
+ <NodeView
+ key={entry.node.id}
+ node={entry.node}
+ liveFractions={liveFractions}
+ maximizedKind={null}
+ onLive={setLiveFractions}
+ onCommitted={setLayout}
+ />,
+ );
+ }
});
body = <>{items}</>;
} else {
- body = <NodeView node={content} />;
+ body = (
+ <NodeView
+ node={content}
+ liveFractions={liveFractions}
+ maximizedKind={maximizedKind}
+ onLive={setLiveFractions}
+ onCommitted={setLayout}
+ />
+ );
}
return (
<PanelMaximizeContext.Provider value={maximizeCtx}>
- <PaneWidthProvider value={widths}>{body}</PaneWidthProvider>
+ <PaneWidthProvider value={rootWidths.panelWidths}>{body}</PaneWidthProvider>
</PanelMaximizeContext.Provider>
);
}
diff --git a/apps/desktop/src/renderer/layout/PanelDragController.tsx b/apps/desktop/src/renderer/layout/PanelDragController.tsx
index e89c8f5800..f28db8c955 100644
--- a/apps/desktop/src/renderer/layout/PanelDragController.tsx
+++ b/apps/desktop/src/renderer/layout/PanelDragController.tsx
@@ -1,5 +1,5 @@
/**
- * PanelDragController —— 「直接拖面板换位」正式交互(布局树 B3 转正;前身是
+ * PanelDragController —— 「直接拖面板换位 / grid 停靠」正式交互(布局树 B3 转正;前身是
* dev-only 原型 PanelDragPrototype,Lizi 体感两轮后拍板转正、不做编辑模式)。
*
* 手势(所有顶级面板通用,未来意识面板经标准头 §6.0 天然继承):
@@ -9,11 +9,10 @@
* 已知边界:网页(webview)/独立进程区域宿主收不到按压事件,长按在那里
* 天然无效(平台机制)——标准头手势是这类面板的主入口。
*
- * 交互语义(drop-zone 式):**拖动过程不换位**;指针拖进**对面那块面板的真实
- * 矩形**(共享边内缩 12px 防贴边抖动)时,该面板区域亮起「松手会落到这里」的
- * 半透明高亮罩 —— 高亮就是会被交换的区域本身的尺寸,不是半屏;退出即熄灭。
- * **松手在高亮亮着时才写树交换**(layout.set 即持久化,LayoutRoot 收广播重排),
- * Esc / 松手在原侧 = 取消,什么都不发生。
+ * 交互语义(drop-zone 式):**拖动过程不改树**。插件拖到另一个插件的上/下边缘
+ * 形成纵向 grid,拖到任一根级区域的左/右边缘回到横排,中心保持交换;内置
+ * chat/right-tabs 只参加根级交换,不进入插件 column。高亮罩严格显示最终占位的
+ * 半区或整块区域,松手才一次性 layout.set 持久化;Esc / 无高亮松手 = 取消。
*
* 性能口径(按 Lizi "卡手"反馈定型):pointermove 热路径**零 React 渲染、零
* 布局读取**——边界几何在起拖时量一次缓存(拖动期间不换位,界面静止,没有
@@ -32,7 +31,12 @@ import { useEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import { swapRootSplitChildrenByKind } from '../../shared/layoutTree';
+import {
+ moveGhostPaneToRootByKind,
+ stackGhostPaneByKind,
+ swapPanesByKind,
+ type LayoutNode,
+} from '../../shared/layoutTree';
import { toast } from '@/lib/toast';
/** 长按窗体:按住该时长(ms)且位移小于容差才"浮起"。 */
@@ -106,7 +110,6 @@ export function isDroppableRect(width: number, height: number): boolean {
return width >= MIN_DROP_TARGET_SIZE_PX && height >= MIN_DROP_TARGET_SIZE_PX;
}
-
interface PanelDragControllerProps {
/** MainLayout 的 row 容器(全宽 flex 行),用于算内容区右边界与纵向范围。 */
rowRef: React.RefObject<HTMLDivElement | null>;
@@ -123,11 +126,111 @@ interface ZoneRect {
height: number;
}
-/** 单个可落靶面板:高亮框(它的真实矩形)+ 触发区间。起拖时一次性量好。 */
+export type PanelDropIntent =
+ 'swap' | 'stack-before' | 'stack-after' | 'root-before' | 'root-after';
+
+interface RectLike extends ZoneRect {
+ right: number;
+ bottom: number;
+}
+
+const GRID_EDGE_RATIO = 0.28;
+
+function pointInRect(x: number, y: number, rect: RectLike): boolean {
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
+}
+
+/**
+ * 二维停靠意图:插件之间上/下形成 grid,左/右回到根横排,中心交换槽位。
+ * 内置面板保持原有根级交换,不允许被塞进插件纵向列。
+ */
+export function computePanelDropIntent(input: {
+ pointerX: number;
+ pointerY: number;
+ paneRect: RectLike;
+ rootRect: RectLike;
+ sourceKind: string;
+ targetKind: string;
+ sourceRootIndex: number;
+ targetRootIndex: number;
+ sourceIsRootPane: boolean;
+ targetIsRootPane: boolean;
+}): PanelDropIntent | null {
+ const { pointerX, pointerY, paneRect, sourceKind, targetKind } = input;
+ if (!pointInRect(pointerX, pointerY, paneRect)) return null;
+ const sourceGhost = sourceKind.startsWith('ghost:');
+ const targetGhost = targetKind.startsWith('ghost:');
+ if (!sourceGhost) {
+ return input.sourceIsRootPane &&
+ input.targetIsRootPane &&
+ input.sourceRootIndex !== input.targetRootIndex
+ ? 'swap'
+ : null;
+ }
+
+ const nx = paneRect.width > 0 ? (pointerX - paneRect.left) / paneRect.width : 0.5;
+ const ny = paneRect.height > 0 ? (pointerY - paneRect.top) / paneRect.height : 0.5;
+ const edgeCandidates: Array<{ distance: number; intent: PanelDropIntent }> = [
+ { distance: nx, intent: 'root-before' },
+ { distance: 1 - nx, intent: 'root-after' },
+ ];
+ if (targetGhost) {
+ edgeCandidates.push(
+ { distance: ny, intent: 'stack-before' },
+ { distance: 1 - ny, intent: 'stack-after' },
+ );
+ }
+ const nearest = edgeCandidates.sort((a, b) => a.distance - b.distance)[0];
+ if (nearest && nearest.distance <= GRID_EDGE_RATIO) return nearest.intent;
+
+ // 嵌套插件只能和插件交换,避免把 chat/right-tabs 换进 ghost-only 的 column。
+ if (
+ targetGhost ||
+ (input.sourceIsRootPane &&
+ input.targetIsRootPane &&
+ input.sourceRootIndex !== input.targetRootIndex)
+ ) {
+ return 'swap';
+ }
+ // 同一 root 区域的中心没有新的布局含义。
+ return null;
+}
+
+function insetRect(rect: RectLike): RectLike {
+ const left = rect.left + DROP_ZONE_INSET_PX;
+ const top = rect.top + DROP_ZONE_INSET_PX;
+ const width = Math.max(0, rect.width - DROP_ZONE_INSET_PX * 2);
+ const height = Math.max(0, rect.height - DROP_ZONE_INSET_PX * 2);
+ return { left, top, width, height, right: left + width, bottom: top + height };
+}
+
+export function computePanelDropZone(
+ intent: PanelDropIntent,
+ paneRect: RectLike,
+ rootRect: RectLike,
+): ZoneRect {
+ const base = insetRect(intent === 'root-before' || intent === 'root-after' ? rootRect : paneRect);
+ switch (intent) {
+ case 'stack-before':
+ return { ...base, height: base.height / 2 };
+ case 'stack-after':
+ return { ...base, top: base.top + base.height / 2, height: base.height / 2 };
+ case 'root-before':
+ return { ...base, width: base.width / 2 };
+ case 'root-after':
+ return { ...base, left: base.left + base.width / 2, width: base.width / 2 };
+ case 'swap':
+ return base;
+ }
+}
+
+/** 单个可落靶面板:pane 与其根级区域几何均在起拖时缓存。 */
interface DropTarget {
kind: string;
- zone: ZoneRect;
- trigger: TriggerRange;
+ paneRect: RectLike;
+ rootRect: RectLike;
+ rootIndex: number;
+ isRootPane: boolean;
}
/** 起拖时一次性缓存的几何:全部可落靶面板(N 面板,拖到谁身上就和谁换位)。 */
@@ -138,6 +241,7 @@ interface DragGeometry {
/** 低频渲染状态:只在拖动开始/结束与落靶目标变化时更新,不随指针移动更新。 */
interface DragRenderState {
targetKind: string | null;
+ zone: ZoneRect | null;
}
export function PanelDragController({
@@ -166,37 +270,62 @@ export function PanelDragController({
/** 进入拖动态:量一次几何 + 挂全局监听 + webview 穿透 + 禁选中。 */
const activateDrag = (sourceKind: string, startX: number, startY: number) => {
- // 可落靶面板 = root 分割里除源之外的每一个 pane(N 面板通用,拖到谁
- // 身上就和谁换位);高亮/提交区域是各自**当下的真实矩形**(Lizi 定案:
- // 高亮必须是"会被交换的那块区域"的尺寸,不是半屏)。
- // 几何一次性缓存:拖动期间不换位、界面静止,没有需要每帧重量的理由。
+ // 几何一次性缓存:pane 矩形决定上下/中心落点,根级区域矩形决定左右停靠。
+ // 拖动期间树不变,热路径无需再次读取布局。
const targets: DropTarget[] = [];
+ let sourceRootIndex = -1;
+ let sourceIsRootPane = false;
try {
const layout = window.electronAPI.layout.getStateSync().layout;
- if (layout.content.type !== 'split') return;
- const kinds = layout.content.children.map((c) =>
- c.node.type === 'pane' ? c.node.panelKind : null,
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') return;
+ const paneKinds = (node: LayoutNode): string[] =>
+ node.type === 'pane'
+ ? [node.panelKind]
+ : node.children.flatMap((child) => paneKinds(child.node));
+ sourceRootIndex = layout.content.children.findIndex((child) =>
+ paneKinds(child.node).includes(sourceKind),
);
- const sourceIndex = kinds.indexOf(sourceKind);
- if (sourceIndex < 0) return;
- kinds.forEach((kind, index) => {
- if (!kind || index === sourceIndex) return;
- const el = document.querySelector(`[data-panel-drag-root="${kind}"]`);
- if (!el) return; // 未注册(隐藏)的 kind 没有 DOM,自然不可落靶
- const rect = el.getBoundingClientRect();
- // 折叠(w-0)/隐藏的面板没有身体,不算落点;全过滤光则下方 targets 为空,
- // 根本不进入拖动态(按下如常点击,不浮起一张无处可落的拖影)。
- if (!isDroppableRect(rect.width, rect.height)) return;
- targets.push({
- kind,
- zone: {
- left: rect.left + DROP_ZONE_INSET_PX,
- top: rect.top + DROP_ZONE_INSET_PX,
- width: Math.max(0, rect.width - DROP_ZONE_INSET_PX * 2),
- height: Math.max(0, rect.height - DROP_ZONE_INSET_PX * 2),
- },
- // 入界余量只缩"朝源面板那侧"的共享方向:源在目标左侧则缩目标左缘。
- trigger: computeTriggerRange(rect.left, rect.right, sourceIndex < index),
+ if (sourceRootIndex < 0) return;
+ sourceIsRootPane = layout.content.children[sourceRootIndex].node.type === 'pane';
+
+ layout.content.children.forEach((rootChild, rootIndex) => {
+ const kinds = paneKinds(rootChild.node);
+ const rootElement =
+ rootChild.node.type === 'split'
+ ? document.querySelector(`[data-layout-root-child-id="${rootChild.node.id}"]`)
+ : document.querySelector(`[data-panel-drag-root="${rootChild.node.panelKind}"]`);
+ const rootDomRect = rootElement?.getBoundingClientRect();
+ if (!rootDomRect || !isDroppableRect(rootDomRect.width, rootDomRect.height)) return;
+ const rootRect: RectLike = {
+ left: rootDomRect.left,
+ top: rootDomRect.top,
+ width: rootDomRect.width,
+ height: rootDomRect.height,
+ right: rootDomRect.right,
+ bottom: rootDomRect.bottom,
+ };
+ kinds.forEach((kind) => {
+ if (kind === sourceKind) return;
+ const el = document.querySelector(`[data-panel-drag-root="${kind}"]`);
+ if (!el) return; // 未注册(隐藏)的 kind 没有 DOM,自然不可落靶
+ const rect = el.getBoundingClientRect();
+ // 折叠(w-0)/隐藏的面板没有身体,不算落点;全过滤光则下方 targets 为空,
+ // 根本不进入拖动态(按下如常点击,不浮起一张无处可落的拖影)。
+ if (!isDroppableRect(rect.width, rect.height)) return;
+ targets.push({
+ kind,
+ paneRect: {
+ left: rect.left,
+ top: rect.top,
+ width: rect.width,
+ height: rect.height,
+ right: rect.right,
+ bottom: rect.bottom,
+ },
+ rootRect,
+ rootIndex,
+ isRootPane: rootChild.node.type === 'pane',
+ });
});
});
} catch {
@@ -207,8 +336,9 @@ export function PanelDragController({
dragActiveRef.current = true;
let targetKindNow: string | null = null;
+ let targetIntentNow: PanelDropIntent | null = null;
pointRef.current = { x: startX, y: startY };
- setDrag({ targetKind: null });
+ setDrag({ targetKind: null, zone: null });
document.body.classList.add('resizing-pane');
const prevUserSelect = document.body.style.userSelect;
const prevBodyPointerEvents = document.body.style.pointerEvents;
@@ -223,16 +353,42 @@ export function PanelDragController({
// 长按期间 mousedown 默认行为可能已拉出文字选区,浮起时清掉。
window.getSelection()?.removeAllRanges();
- /** 每帧:直改拖影 transform;只有落靶目标变化才 setState。 */
+ /** 每帧:直改拖影 transform;只有落靶目标/方向变化才 setState。 */
const onMove = (e: PointerEvent) => {
moveGhost(e.clientX, e.clientY);
const geo = geometryRef.current;
if (!geo) return;
- const hit = geo.targets.find((t) => isPointerInTargetZone(e.clientX, t.trigger));
- const nextKind = hit ? hit.kind : null;
- if (nextKind !== targetKindNow) {
+ let nextTarget: DropTarget | null = null;
+ let nextIntent: PanelDropIntent | null = null;
+ for (const target of geo.targets) {
+ const intent = computePanelDropIntent({
+ pointerX: e.clientX,
+ pointerY: e.clientY,
+ paneRect: target.paneRect,
+ rootRect: target.rootRect,
+ sourceKind,
+ targetKind: target.kind,
+ sourceRootIndex,
+ targetRootIndex: target.rootIndex,
+ sourceIsRootPane,
+ targetIsRootPane: target.isRootPane,
+ });
+ if (!intent) continue;
+ nextTarget = target;
+ nextIntent = intent;
+ break;
+ }
+ const nextKind = nextTarget?.kind ?? null;
+ if (nextKind !== targetKindNow || nextIntent !== targetIntentNow) {
targetKindNow = nextKind;
- setDrag({ targetKind: nextKind });
+ targetIntentNow = nextIntent;
+ setDrag({
+ targetKind: nextKind,
+ zone:
+ nextTarget && nextIntent
+ ? computePanelDropZone(nextIntent, nextTarget.paneRect, nextTarget.rootRect)
+ : null,
+ });
}
};
@@ -249,11 +405,25 @@ export function PanelDragController({
document.removeEventListener('pointercancel', onCancel);
window.removeEventListener('keydown', onKey, true);
cleanupRef.current = null;
- if (opts.commit && targetKindNow) {
- // 松手在高亮上 → 此刻才真正与落靶面板换位并持久化。
+ if (opts.commit && targetKindNow && targetIntentNow) {
try {
const layout = window.electronAPI.layout.getStateSync().layout;
- const op = swapRootSplitChildrenByKind(layout, sourceKind, targetKindNow);
+ const op =
+ targetIntentNow === 'stack-before' || targetIntentNow === 'stack-after'
+ ? stackGhostPaneByKind(
+ layout,
+ sourceKind,
+ targetKindNow,
+ targetIntentNow === 'stack-before' ? 'before' : 'after',
+ )
+ : targetIntentNow === 'root-before' || targetIntentNow === 'root-after'
+ ? moveGhostPaneToRootByKind(
+ layout,
+ sourceKind,
+ targetKindNow,
+ targetIntentNow === 'root-before' ? 'before' : 'after',
+ )
+ : swapPanesByKind(layout, sourceKind, targetKindNow);
if (op.applied) {
void window.electronAPI.layout
.set(op.layout)
@@ -265,7 +435,7 @@ export function PanelDragController({
.catch(() => toast.error(t('settings.appearance.layout.saveFailed')));
}
} catch {
- // 同步 IPC 异常 —— 放弃本次交换并明确告诉用户没有保存。
+ // 同步 IPC 异常 —— 放弃本次布局变换并明确告诉用户没有保存。
toast.error(t('settings.appearance.layout.saveFailed'));
}
}
@@ -278,7 +448,10 @@ export function PanelDragController({
};
window.addEventListener('click', swallow, { capture: true, once: true });
window.setTimeout(
- () => window.removeEventListener('click', swallow, { capture: true } as EventListenerOptions),
+ () =>
+ window.removeEventListener('click', swallow, {
+ capture: true,
+ } as EventListenerOptions),
100,
);
}
@@ -357,9 +530,7 @@ export function PanelDragController({
}, [enabled, rowRef, sidebarBlockRef, t]);
if (!drag) return null;
- const zone = drag.targetKind
- ? geometryRef.current?.targets.find((t) => t.kind === drag.targetKind)?.zone ?? null
- : null;
+ const zone = drag.zone;
// 视觉(全走主题 token,规则 16;无文案免 i18n):
// 1. 落点高亮:半透明淡蓝罩层(VSCode 拖 tab 落点同款质感)——透出下方内容,
// 取色基于 focus-ring 语义蓝低透明度混合,light / dark / 扩展主题都自然;
diff --git a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
index 8a74964ad6..c556efba03 100644
--- a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
+++ b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
@@ -1,13 +1,17 @@
// @vitest-environment jsdom
import { cleanup, render, screen } from '@testing-library/react';
import { act } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createDefaultLayout, type Layout } from '../../../shared/layoutTree';
-import { BuiltinPanelBridgeProvider, type BuiltinPanelBridge } from '../../panels/BuiltinPanelBridge';
+import {
+ BuiltinPanelBridgeProvider,
+ type BuiltinPanelBridge,
+} from '../../panels/BuiltinPanelBridge';
import { __resetBuiltinPanelsForTest } from '../../panels/builtinPanels';
-import { __resetPanelRegistryForTest } from '../../panels/registry';
+import { __resetPanelRegistryForTest, registerPanelKind } from '../../panels/registry';
import { LayoutRoot } from '../LayoutRoot';
+import { usePaneFill } from '../panePlacement';
/** stub electronAPI.layout:同步返回给定树 + 可手动触发 onChanged。 */
let currentLayout: Layout;
@@ -93,8 +97,9 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
it('未注册 panelKind(未安装意识残留)整个 pane 隐藏,不留孤儿分割线', () => {
const withGhost = createDefaultLayout();
- (withGhost.content as { children: { node: { panelKind: string } }[] }).children[1].node.panelKind =
- 'ghost:not-installed';
+ (
+ withGhost.content as { children: { node: { panelKind: string } }[] }
+ ).children[1].node.panelKind = 'ghost:not-installed';
currentLayout = withGhost;
renderLayoutRoot();
expect(rowChildTestIds()).toEqual(['p-chat']);
@@ -120,4 +125,54 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
unmount();
expect(changedListeners).toHaveLength(0);
});
+
+ it('根级 column split 渲染为插件 grid,两个 pane 填满各自格并带横向分割线', () => {
+ const GridPane = ({ name }: { name: string }) => (
+ <div data-testid={`grid-${name}`} data-fill={String(usePaneFill())} />
+ );
+ registerPanelKind({
+ kind: 'ghost:alpha',
+ Component: () => <GridPane name="alpha" />,
+ collapseMemory: 'global',
+ });
+ registerPanelKind({
+ kind: 'ghost:beta',
+ Component: () => <GridPane name="beta" />,
+ collapseMemory: 'global',
+ });
+ currentLayout = {
+ ...createDefaultLayout(),
+ content: {
+ type: 'split',
+ id: 'root',
+ direction: 'row',
+ children: [
+ {
+ fraction: 0.35,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
+ {
+ fraction: 0.35,
+ node: {
+ type: 'split',
+ id: 'grid-alpha',
+ direction: 'column',
+ children: [
+ { fraction: 0.5, node: { type: 'pane', id: 'alpha', panelKind: 'ghost:alpha' } },
+ { fraction: 0.5, node: { type: 'pane', id: 'beta', panelKind: 'ghost:beta' } },
+ ],
+ },
+ },
+ { fraction: 0.3, node: { type: 'pane', id: 'right', panelKind: 'right-tabs' } },
+ ],
+ },
+ };
+
+ renderLayoutRoot();
+
+ expect(screen.getByTestId('grid-alpha').getAttribute('data-fill')).toBe('true');
+ expect(screen.getByTestId('grid-beta').getAttribute('data-fill')).toBe('true');
+ expect(document.querySelector('[data-layout-root-child-id="grid-alpha"]')).not.toBeNull();
+ expect(screen.getAllByTestId('layout-divider')).toHaveLength(3);
+ });
});
diff --git a/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts b/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
index 5e5e221b18..8d92254e01 100644
--- a/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
+++ b/apps/desktop/src/renderer/layout/__tests__/panelDragController.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { computeTriggerRange, isDroppableRect, isPointerInTargetZone } from '../PanelDragController';
+import {
+ computePanelDropIntent,
+ computePanelDropZone,
+ computeTriggerRange,
+ isDroppableRect,
+ isPointerInTargetZone,
+} from '../PanelDragController';
/**
* 拖面板原型的落点判定单测 —— 高亮/提交共用同一区间(所见即所得)。
@@ -57,3 +63,87 @@ describe('isDroppableRect', () => {
expect(isDroppableRect(20, 800)).toBe(false); // 低于最小身体尺寸
});
});
+
+describe('插件面板二维停靠落点', () => {
+ const paneRect = {
+ left: 100,
+ top: 100,
+ width: 400,
+ height: 600,
+ right: 500,
+ bottom: 700,
+ };
+ const rootRect = paneRect;
+ const base = {
+ paneRect,
+ rootRect,
+ sourceKind: 'ghost:alpha',
+ targetKind: 'ghost:beta',
+ sourceRootIndex: 0,
+ targetRootIndex: 1,
+ sourceIsRootPane: true,
+ targetIsRootPane: true,
+ };
+
+ it('插件拖到目标上/下边缘 → 形成纵向 grid', () => {
+ expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 110 })).toBe('stack-before');
+ expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 690 })).toBe('stack-after');
+ });
+
+ it('插件拖到目标左/右边缘 → 回到根横排', () => {
+ expect(computePanelDropIntent({ ...base, pointerX: 105, pointerY: 400 })).toBe('root-before');
+ expect(computePanelDropIntent({ ...base, pointerX: 495, pointerY: 400 })).toBe('root-after');
+ });
+
+ it('插件拖到目标中心 → 交换槽位', () => {
+ expect(computePanelDropIntent({ ...base, pointerX: 300, pointerY: 400 })).toBe('swap');
+ });
+
+ it('内置面板只保留根级交换,不进入插件 column', () => {
+ expect(
+ computePanelDropIntent({
+ ...base,
+ pointerX: 300,
+ pointerY: 400,
+ sourceKind: 'chat-main',
+ targetKind: 'right-tabs',
+ }),
+ ).toBe('swap');
+ expect(
+ computePanelDropIntent({
+ ...base,
+ pointerX: 300,
+ pointerY: 400,
+ sourceKind: 'chat-main',
+ targetIsRootPane: false,
+ }),
+ ).toBeNull();
+ });
+
+ it('纵向列里的插件可从内置区域左右边缘抽回横排,但中心不交换', () => {
+ const nestedSource = {
+ ...base,
+ sourceIsRootPane: false,
+ targetKind: 'chat-main',
+ };
+ expect(computePanelDropIntent({ ...nestedSource, pointerX: 105, pointerY: 400 })).toBe(
+ 'root-before',
+ );
+ expect(computePanelDropIntent({ ...nestedSource, pointerX: 300, pointerY: 400 })).toBeNull();
+ });
+
+ it('高亮区域与停靠方向一致:上下/左右各占目标一半', () => {
+ expect(computePanelDropZone('stack-before', paneRect, rootRect)).toMatchObject({
+ left: 106,
+ top: 106,
+ width: 388,
+ height: 294,
+ });
+ expect(computePanelDropZone('root-after', paneRect, rootRect)).toMatchObject({
+ left: 300,
+ top: 106,
+ width: 194,
+ height: 588,
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/layout/panePlacement.tsx b/apps/desktop/src/renderer/layout/panePlacement.tsx
new file mode 100644
index 0000000000..1eb0640ee0
--- /dev/null
+++ b/apps/desktop/src/renderer/layout/panePlacement.tsx
@@ -0,0 +1,15 @@
+import { createContext, useContext } from 'react';
+
+/**
+ * 布局树给 pane 的容器适配信号。
+ *
+ * 根级横排沿用既有像素宽度通道;进入插件 grid 的纵向列后,面板必须填满父格,
+ * 不能继续拿 manifest 的固定宽度,否则会在列内留下空白或溢出。
+ */
+const PaneFillContext = createContext(false);
+
+export const PaneFillProvider = PaneFillContext.Provider;
+
+export function usePaneFill(): boolean {
+ return useContext(PaneFillContext);
+}
diff --git a/apps/desktop/src/shared/__tests__/layoutTree.test.ts b/apps/desktop/src/shared/__tests__/layoutTree.test.ts
index 70b3cf3ee7..ebd9ffbe64 100644
--- a/apps/desktop/src/shared/__tests__/layoutTree.test.ts
+++ b/apps/desktop/src/shared/__tests__/layoutTree.test.ts
@@ -10,7 +10,10 @@ import {
findPaneById,
findSplitChildByPanelKind,
insertRootSplitPane,
+ moveGhostPaneToRootByKind,
removeRootSplitPaneByKind,
+ stackGhostPaneByKind,
+ swapPanesByKind,
swapRootSplitChildrenByKind,
transferSplitFraction,
setPaneCollapsed,
@@ -140,8 +143,10 @@ describe('validateLayout · 结构性不变量', () => {
it('chat-main 标记 collapsed 被拒(主区不可折叠)', () => {
const layout = makeLayout((l) => {
- const chat = (l.content as { children: { node: LayoutNode }[] }).children[0]
- .node as Extract<LayoutNode, { type: 'pane' }>;
+ const chat = (l.content as { children: { node: LayoutNode }[] }).children[0].node as Extract<
+ LayoutNode,
+ { type: 'pane' }
+ >;
chat.collapsed = true;
});
expect(validateLayout(layout).ok).toBe(false);
@@ -201,7 +206,14 @@ describe('validateLayout · 结构性不变量', () => {
it('v1 float 非空被拒', () => {
const layout = makeLayout((l) => {
- (l.float as unknown[]).push({ id: 'f', panelKind: 'right-tabs', x: 0, y: 0, width: 1, height: 1 });
+ (l.float as unknown[]).push({
+ id: 'f',
+ panelKind: 'right-tabs',
+ x: 0,
+ y: 0,
+ width: 1,
+ height: 1,
+ });
});
expect(validateLayout(layout).ok).toBe(false);
});
@@ -315,7 +327,9 @@ describe('setSplitChildFraction', () => {
expect(children[0].fraction).toBeCloseTo(0.6);
expect(children[1].fraction).toBeCloseTo(0.4);
// 原树保持默认占比(0.5/0.5,B1b-1 对齐右栏既有 50/50 默认)。
- expect((layout.content as { children: { fraction: number }[] }).children[0].fraction).toBeCloseTo(0.5);
+ expect(
+ (layout.content as { children: { fraction: number }[] }).children[0].fraction,
+ ).toBeCloseTo(0.5);
});
it('split 不存在 / index 越界 / fraction 非法均被拒且返回原引用', () => {
@@ -340,8 +354,14 @@ describe('insertRootSplitPane / removeRootSplitPaneByKind(加装/卸载)', () =>
{ index: 1, fraction: 0.2 },
);
expect(r.applied).toBe(true);
- const children = (r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }).children;
- expect(children.map((c) => c.node.panelKind)).toEqual(['chat-main', 'ghost:hello', 'right-tabs']);
+ const children = (
+ r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }
+ ).children;
+ expect(children.map((c) => c.node.panelKind)).toEqual([
+ 'chat-main',
+ 'ghost:hello',
+ 'right-tabs',
+ ]);
expect(children.reduce((a, c) => a + c.fraction, 0)).toBeCloseTo(1);
expect(children[1].fraction).toBeCloseTo(0.2);
expect(validateLayout(r.layout)).toEqual({ ok: true });
@@ -351,9 +371,15 @@ describe('insertRootSplitPane / removeRootSplitPaneByKind(加装/卸载)', () =>
it('index 越界夹取到末尾;fraction 夹取进 [0.05, 0.8]', () => {
const layout = createDefaultLayout();
- const r = insertRootSplitPane(layout, { id: 'x', panelKind: 'ghost:x' }, { index: 99, fraction: 5 });
+ const r = insertRootSplitPane(
+ layout,
+ { id: 'x', panelKind: 'ghost:x' },
+ { index: 99, fraction: 5 },
+ );
expect(r.applied).toBe(true);
- const children = (r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }).children;
+ const children = (
+ r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }
+ ).children;
expect(children[2].node.panelKind).toBe('ghost:x');
expect(children[2].fraction).toBeLessThanOrEqual(0.8);
});
@@ -367,10 +393,16 @@ describe('insertRootSplitPane / removeRootSplitPaneByKind(加装/卸载)', () =>
it('卸载:移除目标并归一份额;round-trip 加装→卸载回到两块', () => {
const layout = createDefaultLayout();
- const added = insertRootSplitPane(layout, { id: 'demo-hello', panelKind: 'ghost:hello' }, { index: 1 });
+ const added = insertRootSplitPane(
+ layout,
+ { id: 'demo-hello', panelKind: 'ghost:hello' },
+ { index: 1 },
+ );
const removed = removeRootSplitPaneByKind(added.layout, 'ghost:hello');
expect(removed.applied).toBe(true);
- const children = (removed.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }).children;
+ const children = (
+ removed.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }
+ ).children;
expect(children.map((c) => c.node.panelKind)).toEqual(['chat-main', 'right-tabs']);
expect(children.reduce((a, c) => a + c.fraction, 0)).toBeCloseTo(1);
});
@@ -384,7 +416,11 @@ describe('insertRootSplitPane / removeRootSplitPaneByKind(加装/卸载)', () =>
it('卸载 chat-main 被出口校验拒绝(即使块数足够)', () => {
const layout = createDefaultLayout();
- const added = insertRootSplitPane(layout, { id: 'demo-hello', panelKind: 'ghost:hello' }, { index: 1 });
+ const added = insertRootSplitPane(
+ layout,
+ { id: 'demo-hello', panelKind: 'ghost:hello' },
+ { index: 1 },
+ );
const r = removeRootSplitPaneByKind(added.layout, 'chat-main');
expect(r.applied).toBe(false);
});
@@ -400,8 +436,14 @@ describe('swapRootSplitChildrenByKind(N 面板换位)', () => {
);
const r = swapRootSplitChildrenByKind(added.layout, 'chat-main', 'right-tabs');
expect(r.applied).toBe(true);
- const children = (r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }).children;
- expect(children.map((c) => c.node.panelKind)).toEqual(['right-tabs', 'ghost:hello', 'chat-main']);
+ const children = (
+ r.layout.content as { children: { fraction: number; node: { panelKind: string } }[] }
+ ).children;
+ expect(children.map((c) => c.node.panelKind)).toEqual([
+ 'right-tabs',
+ 'ghost:hello',
+ 'chat-main',
+ ]);
// fraction 跟着面板走:hello 仍是 0.2。
expect(children[1].fraction).toBeCloseTo(0.2);
expect(validateLayout(r.layout)).toEqual({ ok: true });
@@ -414,6 +456,133 @@ describe('swapRootSplitChildrenByKind(N 面板换位)', () => {
});
});
+function layoutWithTwoGhostPanes(): Layout {
+ const alpha = insertRootSplitPane(
+ createDefaultLayout(),
+ { id: 'ghost-alpha', panelKind: 'ghost:alpha' },
+ { index: 0, fraction: 0.2 },
+ );
+ const beta = insertRootSplitPane(
+ alpha.layout,
+ { id: 'ghost-beta', panelKind: 'ghost:beta' },
+ { index: 1, fraction: 0.25 },
+ );
+ expect(alpha.applied).toBe(true);
+ expect(beta.applied).toBe(true);
+ return beta.layout;
+}
+
+describe('插件面板 grid 停靠', () => {
+ it('把两个根级插件上下合并为 column,外层宽度继承双方份额之和', () => {
+ const layout = layoutWithTwoGhostPanes();
+ const before = (layout.content as SplitNode).children;
+ const alphaWidth = before[0].fraction;
+ const betaWidth = before[1].fraction;
+
+ const result = stackGhostPaneByKind(layout, 'ghost:alpha', 'ghost:beta', 'before');
+
+ expect(result.applied).toBe(true);
+ const root = result.layout.content as SplitNode;
+ expect(root.direction).toBe('row');
+ expect(root.children).toHaveLength(3);
+ expect(root.children[0].fraction).toBeCloseTo(alphaWidth + betaWidth);
+ expect(root.children[0].node).toMatchObject({ type: 'split', direction: 'column' });
+ const column = root.children[0].node as SplitNode;
+ expect(
+ column.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
+ ).toEqual(['ghost:alpha', 'ghost:beta']);
+ expect(column.children.map((child) => child.fraction)).toEqual([0.5, 0.5]);
+ expect(validateLayout(result.layout)).toEqual({ ok: true });
+ expect(layout.content).not.toEqual(result.layout.content);
+ });
+
+ it('同一纵向列内上下拖动只调整顺序,保留每块高度份额', () => {
+ const stacked = stackGhostPaneByKind(
+ layoutWithTwoGhostPanes(),
+ 'ghost:alpha',
+ 'ghost:beta',
+ 'before',
+ );
+ const column = (stacked.layout.content as SplitNode).children[0].node as SplitNode;
+ column.children[0].fraction = 0.35;
+ column.children[1].fraction = 0.65;
+
+ const reordered = stackGhostPaneByKind(stacked.layout, 'ghost:alpha', 'ghost:beta', 'after');
+
+ expect(reordered.applied).toBe(true);
+ const nextColumn = (reordered.layout.content as SplitNode).children[0].node as SplitNode;
+ expect(
+ nextColumn.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
+ ).toEqual(['ghost:beta', 'ghost:alpha']);
+ expect(nextColumn.children.map((child) => child.fraction)).toEqual([0.65, 0.35]);
+ });
+
+ it('从两块等分 column 抽回根横排时,恢复为两份相同列宽并折叠单子节点 split', () => {
+ const stacked = stackGhostPaneByKind(
+ layoutWithTwoGhostPanes(),
+ 'ghost:alpha',
+ 'ghost:beta',
+ 'before',
+ );
+
+ const result = moveGhostPaneToRootByKind(stacked.layout, 'ghost:alpha', 'chat-main', 'before');
+
+ expect(result.applied).toBe(true);
+ const root = result.layout.content as SplitNode;
+ expect(
+ root.children.map((child) => child.node.type === 'pane' && child.node.panelKind),
+ ).toEqual(['ghost:beta', 'ghost:alpha', 'chat-main', 'right-tabs']);
+ expect(root.children[0].fraction).toBeCloseTo(root.children[1].fraction);
+ expect(validateLayout(result.layout)).toEqual({ ok: true });
+ });
+
+ it('中心交换支持纵向列中的插件槽位,且不会改变槽位高度', () => {
+ const withGamma = insertRootSplitPane(
+ layoutWithTwoGhostPanes(),
+ { id: 'ghost-gamma', panelKind: 'ghost:gamma' },
+ { index: 2, fraction: 0.1 },
+ );
+ const stacked = stackGhostPaneByKind(withGamma.layout, 'ghost:alpha', 'ghost:beta', 'before');
+ const rootBefore = stacked.layout.content as SplitNode;
+ const columnBefore = rootBefore.children[0].node as SplitNode;
+ columnBefore.children[0].fraction = 0.4;
+ columnBefore.children[1].fraction = 0.6;
+
+ const result = swapPanesByKind(stacked.layout, 'ghost:alpha', 'ghost:gamma');
+
+ expect(result.applied).toBe(true);
+ const root = result.layout.content as SplitNode;
+ const column = root.children[0].node as SplitNode;
+ expect(column.children[0].node).toMatchObject({ panelKind: 'ghost:gamma' });
+ expect(column.children.map((child) => child.fraction)).toEqual([0.4, 0.6]);
+ expect(walkPanes(result.layout).map((pane) => pane.panelKind)).toContain('ghost:alpha');
+ expect(validateLayout(result.layout)).toEqual({ ok: true });
+ });
+
+ it('数据层拒绝把 chat/right-tabs 交换进插件纵向列', () => {
+ const stacked = stackGhostPaneByKind(
+ layoutWithTwoGhostPanes(),
+ 'ghost:alpha',
+ 'ghost:beta',
+ 'before',
+ );
+
+ expect(swapPanesByKind(stacked.layout, 'chat-main', 'ghost:alpha').applied).toBe(false);
+ expect(countPanelKind(stacked.layout, 'chat-main')).toBe(1);
+ expect(validateLayout(stacked.layout)).toEqual({ ok: true });
+ });
+
+ it('上下停靠拒绝内置面板或缺失目标,保持 chat-main 不变量', () => {
+ const layout = layoutWithTwoGhostPanes();
+ expect(stackGhostPaneByKind(layout, 'chat-main', 'ghost:alpha', 'before').applied).toBe(false);
+ expect(stackGhostPaneByKind(layout, 'ghost:alpha', 'ghost:missing', 'after').applied).toBe(
+ false,
+ );
+ expect(validateLayout(layout)).toEqual({ ok: true });
+ expect(countPanelKind(layout, 'chat-main')).toBe(1);
+ });
+});
+
describe('transferSplitFraction(缝把手拖宽提交)', () => {
it('只动缝两侧邻居:from 减 to 增,第三方不受影响,总和保持 1', () => {
const layout = createDefaultLayout();
@@ -422,10 +591,14 @@ describe('transferSplitFraction(缝把手拖宽提交)', () => {
{ id: 'demo-hello', panelKind: 'ghost:hello' },
{ index: 1, fraction: 0.2 },
);
- const before = (added.layout.content as { children: { fraction: number }[] }).children.map((c) => c.fraction);
+ const before = (added.layout.content as { children: { fraction: number }[] }).children.map(
+ (c) => c.fraction,
+ );
const r = transferSplitFraction(added.layout, 'root', 1, 2, 0.1);
expect(r.applied).toBe(true);
- const after = (r.layout.content as { children: { fraction: number }[] }).children.map((c) => c.fraction);
+ const after = (r.layout.content as { children: { fraction: number }[] }).children.map(
+ (c) => c.fraction,
+ );
expect(after[0]).toBeCloseTo(before[0]); // chat 不动
expect(after[1]).toBeCloseTo(before[1] - 0.1);
expect(after[2]).toBeCloseTo(before[2] + 0.1);
@@ -484,7 +657,10 @@ describe('findSplitChildByPanelKind', () => {
id: 'root',
direction: 'row',
children: [
- { fraction: 0.5, node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 } },
+ {
+ fraction: 0.5,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
{
fraction: 0.5,
node: {
diff --git a/apps/desktop/src/shared/layoutTree.ts b/apps/desktop/src/shared/layoutTree.ts
index 6832823d64..5bffe8460d 100644
--- a/apps/desktop/src/shared/layoutTree.ts
+++ b/apps/desktop/src/shared/layoutTree.ts
@@ -127,7 +127,10 @@ export function createDefaultLayout(): Layout {
id: 'root',
direction: 'row',
children: [
- { fraction: 0.5, node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 } },
+ {
+ fraction: 0.5,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
{ fraction: 0.5, node: { type: 'pane', id: 'right', panelKind: 'right-tabs' } },
],
},
@@ -280,7 +283,10 @@ function validateNodeShape(
if (node.collapsed !== undefined && typeof node.collapsed !== 'boolean') {
return { ok: false, reason: 'collapsed must be boolean' };
}
- if (node.minWidth !== undefined && !(Number.isFinite(node.minWidth) && (node.minWidth as number) > 0)) {
+ if (
+ node.minWidth !== undefined &&
+ !(Number.isFinite(node.minWidth) && (node.minWidth as number) > 0)
+ ) {
return { ok: false, reason: 'minWidth must be a positive finite number' };
}
panes.push(node as unknown as PaneNode);
@@ -335,8 +341,10 @@ export function validateLayout(input: Layout): ValidateResult {
}
const sidebar = input.sidebar as unknown;
- if (!isRecord(sidebar) || sidebar.type !== 'pane') return { ok: false, reason: 'sidebar must be a pane' };
- if (sidebar.panelKind !== 'session-list') return { ok: false, reason: 'sidebar must be session-list' };
+ if (!isRecord(sidebar) || sidebar.type !== 'pane')
+ return { ok: false, reason: 'sidebar must be a pane' };
+ if (sidebar.panelKind !== 'session-list')
+ return { ok: false, reason: 'sidebar must be session-list' };
if (sidebar.edge !== 'left') return { ok: false, reason: "sidebar edge must be 'left' in v1" };
if (!isValidId(sidebar.id)) return { ok: false, reason: 'sidebar id invalid' };
@@ -347,9 +355,13 @@ export function validateLayout(input: Layout): ValidateResult {
const chatMains = contentPanes.filter((p) => p.panelKind === 'chat-main');
if (chatMains.length !== 1) {
- return { ok: false, reason: `content must contain exactly one chat-main (got ${chatMains.length})` };
+ return {
+ ok: false,
+ reason: `content must contain exactly one chat-main (got ${chatMains.length})`,
+ };
}
- if (chatMains[0].collapsed === true) return { ok: false, reason: 'chat-main must not be collapsed' };
+ if (chatMains[0].collapsed === true)
+ return { ok: false, reason: 'chat-main must not be collapsed' };
if (contentPanes.some((p) => p.panelKind === 'session-list')) {
return { ok: false, reason: 'session-list must stay outside the content tree' };
}
@@ -393,7 +405,11 @@ function finishOp(original: Layout, mutated: Layout, reason: string): LayoutOpRe
* 设置某个 pane 的折叠态。chat-main 不可折叠(由出口校验兜底拒绝)。
* 注意:能否折叠(是否贴边)是渲染层的位置判定,本函数只负责状态写入的合法性。
*/
-export function setPaneCollapsed(layout: Layout, paneId: string, collapsed: boolean): LayoutOpResult {
+export function setPaneCollapsed(
+ layout: Layout,
+ paneId: string,
+ collapsed: boolean,
+): LayoutOpResult {
if (!findPaneById(layout, paneId)) {
return { layout, applied: false, reason: `pane not found: ${paneId}` };
}
@@ -434,7 +450,10 @@ export function setSplitChildFraction(
const remainder = 1 - fraction;
for (let i = 0; i < siblings.length; i++) {
if (i === childIndex) continue;
- siblings[i].fraction = siblingSum > 0 ? (siblings[i].fraction / siblingSum) * remainder : remainder / (siblings.length - 1);
+ siblings[i].fraction =
+ siblingSum > 0
+ ? (siblings[i].fraction / siblingSum) * remainder
+ : remainder / (siblings.length - 1);
}
normalizeSplitFractions(split);
return finishOp(layout, next, 'setSplitChildFraction rejected');
@@ -505,11 +524,14 @@ export function swapRootSplitChildrenByKind(
}
const indexOf = (kind: PanelKind) =>
layout.content.type === 'split'
- ? layout.content.children.findIndex((c) => c.node.type === 'pane' && c.node.panelKind === kind)
+ ? layout.content.children.findIndex(
+ (c) => c.node.type === 'pane' && c.node.panelKind === kind,
+ )
: -1;
const a = indexOf(kindA);
const b = indexOf(kindB);
- if (a < 0 || b < 0) return { layout, applied: false, reason: `pane kind not found: ${a < 0 ? kindA : kindB}` };
+ if (a < 0 || b < 0)
+ return { layout, applied: false, reason: `pane kind not found: ${a < 0 ? kindA : kindB}` };
if (a === b) return { layout, applied: false, reason: 'cannot swap a pane with itself' };
const next = structuredClone(layout);
const split = next.content as SplitNode;
@@ -517,6 +539,327 @@ export function swapRootSplitChildrenByKind(
return finishOp(layout, next, 'swapRootSplitChildrenByKind rejected');
}
+/** 插件面板二维停靠只使用一层纵向分组,避免把主界面演化成任意深度的自由网格。 */
+interface RootGhostPaneLocation {
+ rootIndex: number;
+ columnIndex: number | null;
+}
+
+function isGhostPanelKind(kind: PanelKind): boolean {
+ return kind.startsWith('ghost:');
+}
+
+function findRootGhostPaneLocation(layout: Layout, kind: PanelKind): RootGhostPaneLocation | null {
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') return null;
+ for (let rootIndex = 0; rootIndex < layout.content.children.length; rootIndex++) {
+ const node = layout.content.children[rootIndex].node;
+ if (node.type === 'pane' && node.panelKind === kind) {
+ return { rootIndex, columnIndex: null };
+ }
+ if (node.type !== 'split' || node.direction !== 'column') continue;
+ const columnIndex = node.children.findIndex(
+ (child) => child.node.type === 'pane' && child.node.panelKind === kind,
+ );
+ if (columnIndex >= 0) return { rootIndex, columnIndex };
+ }
+ return null;
+}
+
+function rootChildIndexContainingKind(layout: Layout, kind: PanelKind): number {
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') return -1;
+ const contains = (node: LayoutNode): boolean => {
+ if (node.type === 'pane') return node.panelKind === kind;
+ return node.children.some((child) => contains(child.node));
+ };
+ return layout.content.children.findIndex((child) => contains(child.node));
+}
+
+function collectLayoutNodeIds(node: LayoutNode, ids: Set<string>): void {
+ ids.add(node.id);
+ if (node.type === 'split') {
+ for (const child of node.children) collectLayoutNodeIds(child.node, ids);
+ }
+}
+
+function nextGridSplitId(layout: Layout, targetId: string): string {
+ const ids = new Set<string>([layout.sidebar.id]);
+ collectLayoutNodeIds(layout.content, ids);
+ const base = `grid-${targetId}`.slice(0, 120);
+ if (!ids.has(base)) return base;
+ for (let suffix = 2; suffix < 10_000; suffix++) {
+ const candidate = `${base.slice(0, 127 - String(suffix).length)}-${suffix}`;
+ if (!ids.has(candidate)) return candidate;
+ }
+ return `grid-${targetId.slice(0, 110)}-fallback`;
+}
+
+function removeGhostPaneFromColumn(
+ root: SplitNode,
+ location: RootGhostPaneLocation,
+): PaneNode | null {
+ if (location.columnIndex === null) return null;
+ const rootChild = root.children[location.rootIndex];
+ if (!rootChild || rootChild.node.type !== 'split' || rootChild.node.direction !== 'column') {
+ return null;
+ }
+ const [removed] = rootChild.node.children.splice(location.columnIndex, 1);
+ if (!removed || removed.node.type !== 'pane') return null;
+ if (rootChild.node.children.length === 1) {
+ rootChild.node = rootChild.node.children[0].node;
+ } else {
+ normalizeSplitFractions(rootChild.node);
+ }
+ return removed.node;
+}
+
+/**
+ * 把一个插件面板停靠到另一个插件面板的上方/下方。
+ *
+ * 根布局始终保持横向;纵向 grid 只存在于根 child 的一层 column split 中,且只包含
+ * `ghost:*` pane。两个根级插件合并时,目标列继承双方宽度份额之和,画面不会突然变窄。
+ */
+export function stackGhostPaneByKind(
+ layout: Layout,
+ sourceKind: PanelKind,
+ targetKind: PanelKind,
+ placement: 'before' | 'after',
+): LayoutOpResult {
+ if (!isGhostPanelKind(sourceKind) || !isGhostPanelKind(targetKind)) {
+ return { layout, applied: false, reason: 'vertical grid only supports ghost panels' };
+ }
+ if (sourceKind === targetKind) {
+ return { layout, applied: false, reason: 'cannot stack a pane with itself' };
+ }
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
+ return { layout, applied: false, reason: 'content root must be a row split' };
+ }
+ const source = findRootGhostPaneLocation(layout, sourceKind);
+ const target = findRootGhostPaneLocation(layout, targetKind);
+ if (!source || !target) {
+ return {
+ layout,
+ applied: false,
+ reason: `ghost pane not found: ${!source ? sourceKind : targetKind}`,
+ };
+ }
+
+ const next = structuredClone(layout);
+ const root = next.content as SplitNode;
+
+ // 同一列内只做顺序调整,份额随面板走。
+ if (
+ source.rootIndex === target.rootIndex &&
+ source.columnIndex !== null &&
+ target.columnIndex !== null
+ ) {
+ const column = root.children[source.rootIndex].node;
+ if (column.type !== 'split' || column.direction !== 'column') return { layout, applied: false };
+ const [sourceChild] = column.children.splice(source.columnIndex, 1);
+ const targetIndex = column.children.findIndex(
+ (child) => child.node.type === 'pane' && child.node.panelKind === targetKind,
+ );
+ if (!sourceChild || targetIndex < 0) return { layout, applied: false };
+ column.children.splice(placement === 'before' ? targetIndex : targetIndex + 1, 0, sourceChild);
+ return finishOp(layout, next, 'stackGhostPaneByKind reorder rejected');
+ }
+
+ let sourceNode: PaneNode | null = null;
+ let transferredRootFraction = 0;
+ if (source.columnIndex === null) {
+ const [sourceRootChild] = root.children.splice(source.rootIndex, 1);
+ if (!sourceRootChild || sourceRootChild.node.type !== 'pane') return { layout, applied: false };
+ sourceNode = sourceRootChild.node;
+ transferredRootFraction = sourceRootChild.fraction;
+ } else {
+ sourceNode = removeGhostPaneFromColumn(root, source);
+ }
+ if (!sourceNode) return { layout, applied: false, reason: `ghost pane not found: ${sourceKind}` };
+
+ // source 移除后目标 rootIndex 可能左移,重新寻址。
+ const targetAfterRemoval = findRootGhostPaneLocation(next, targetKind);
+ if (!targetAfterRemoval)
+ return { layout, applied: false, reason: `ghost pane not found: ${targetKind}` };
+ const targetRootChild = root.children[targetAfterRemoval.rootIndex];
+ targetRootChild.fraction += transferredRootFraction;
+
+ if (targetAfterRemoval.columnIndex === null) {
+ if (targetRootChild.node.type !== 'pane') return { layout, applied: false };
+ const targetNode = targetRootChild.node;
+ targetRootChild.node = {
+ type: 'split',
+ id: nextGridSplitId(next, targetNode.id),
+ direction: 'column',
+ children:
+ placement === 'before'
+ ? [
+ { fraction: 0.5, node: sourceNode },
+ { fraction: 0.5, node: targetNode },
+ ]
+ : [
+ { fraction: 0.5, node: targetNode },
+ { fraction: 0.5, node: sourceNode },
+ ],
+ };
+ } else {
+ const column = targetRootChild.node;
+ if (column.type !== 'split' || column.direction !== 'column') return { layout, applied: false };
+ const targetIndex = targetAfterRemoval.columnIndex;
+ const targetChild = column.children[targetIndex];
+ const half = targetChild.fraction / 2;
+ targetChild.fraction = half;
+ column.children.splice(placement === 'before' ? targetIndex : targetIndex + 1, 0, {
+ fraction: half,
+ node: sourceNode,
+ });
+ normalizeSplitFractions(column);
+ }
+
+ normalizeSplitFractions(root);
+ return finishOp(layout, next, 'stackGhostPaneByKind rejected');
+}
+
+/**
+ * 把插件面板从纵向列中抽出(或移动现有根 pane),停到某个根级区域左/右侧。
+ * 从 column 抽出时按它在列中的高度份额拆分外层列宽;两块 50/50 的列可因此恢复为
+ * 合并前近似相同的两列宽度。
+ */
+export function moveGhostPaneToRootByKind(
+ layout: Layout,
+ sourceKind: PanelKind,
+ targetKind: PanelKind,
+ placement: 'before' | 'after',
+): LayoutOpResult {
+ if (!isGhostPanelKind(sourceKind)) {
+ return { layout, applied: false, reason: 'only ghost panels can leave a grid column' };
+ }
+ if (sourceKind === targetKind) {
+ return { layout, applied: false, reason: 'cannot move a pane relative to itself' };
+ }
+ if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
+ return { layout, applied: false, reason: 'content root must be a row split' };
+ }
+ const source = findRootGhostPaneLocation(layout, sourceKind);
+ if (!source) return { layout, applied: false, reason: `ghost pane not found: ${sourceKind}` };
+ if (rootChildIndexContainingKind(layout, targetKind) < 0) {
+ return { layout, applied: false, reason: `target pane not found: ${targetKind}` };
+ }
+
+ const next = structuredClone(layout);
+ const root = next.content as SplitNode;
+ let sourceRootChild: { fraction: number; node: LayoutNode } | null = null;
+
+ if (source.columnIndex === null) {
+ [sourceRootChild] = root.children.splice(source.rootIndex, 1);
+ } else {
+ const rootChild = root.children[source.rootIndex];
+ if (rootChild.node.type !== 'split' || rootChild.node.direction !== 'column') {
+ return { layout, applied: false };
+ }
+ const sourceColumnChild = rootChild.node.children[source.columnIndex];
+ if (!sourceColumnChild || sourceColumnChild.node.type !== 'pane')
+ return { layout, applied: false };
+ const ideal = rootChild.fraction * sourceColumnChild.fraction;
+ const maxTransfer = rootChild.fraction - MIN_SPLIT_CHILD_FRACTION;
+ if (maxTransfer < MIN_SPLIT_CHILD_FRACTION) {
+ return { layout, applied: false, reason: 'grid column is too narrow to split' };
+ }
+ const extractedFraction = Math.min(maxTransfer, Math.max(MIN_SPLIT_CHILD_FRACTION, ideal));
+ const sourceNode = removeGhostPaneFromColumn(root, source);
+ if (!sourceNode) return { layout, applied: false };
+ rootChild.fraction -= extractedFraction;
+ sourceRootChild = { fraction: extractedFraction, node: sourceNode };
+ }
+ if (!sourceRootChild) return { layout, applied: false };
+
+ const targetRootIndex = rootChildIndexContainingKind(next, targetKind);
+ if (targetRootIndex < 0)
+ return { layout, applied: false, reason: `target pane not found: ${targetKind}` };
+ root.children.splice(
+ placement === 'before' ? targetRootIndex : targetRootIndex + 1,
+ 0,
+ sourceRootChild,
+ );
+ normalizeSplitFractions(root);
+ return finishOp(layout, next, 'moveGhostPaneToRootByKind rejected');
+}
+
+function findPanePath(node: LayoutNode, kind: PanelKind, path: number[] = []): number[] | null {
+ if (node.type === 'pane') return node.panelKind === kind ? path : null;
+ for (let index = 0; index < node.children.length; index++) {
+ const found = findPanePath(node.children[index].node, kind, [...path, index]);
+ if (found) return found;
+ }
+ return null;
+}
+
+function nodeAtPath(root: LayoutNode, path: number[]): LayoutNode | null {
+ let node = root;
+ for (const index of path) {
+ if (node.type !== 'split' || !node.children[index]) return null;
+ node = node.children[index].node;
+ }
+ return node;
+}
+
+function setNodeAtPath(root: LayoutNode, path: number[], value: LayoutNode): LayoutNode | null {
+ if (path.length === 0) return value;
+ let node = root;
+ for (let depth = 0; depth < path.length - 1; depth++) {
+ if (node.type !== 'split' || !node.children[path[depth]]) return null;
+ node = node.children[path[depth]].node;
+ }
+ const index = path[path.length - 1];
+ if (node.type !== 'split' || !node.children[index]) return null;
+ node.children[index].node = value;
+ return root;
+}
+
+/** 交换任意两个 pane 的停靠槽位;份额属于槽位,不随面板移动。 */
+export function swapPanesByKind(
+ layout: Layout,
+ kindA: PanelKind,
+ kindB: PanelKind,
+): LayoutOpResult {
+ if (kindA === kindB) return { layout, applied: false, reason: 'cannot swap a pane with itself' };
+ const rootA = rootChildIndexContainingKind(layout, kindA);
+ const rootB = rootChildIndexContainingKind(layout, kindB);
+ const aIsRootPane =
+ layout.content.type === 'split' &&
+ rootA >= 0 &&
+ layout.content.children[rootA].node.type === 'pane';
+ const bIsRootPane =
+ layout.content.type === 'split' &&
+ rootB >= 0 &&
+ layout.content.children[rootB].node.type === 'pane';
+ if ((!aIsRootPane || !bIsRootPane) && (!isGhostPanelKind(kindA) || !isGhostPanelKind(kindB))) {
+ return {
+ layout,
+ applied: false,
+ reason: 'built-in panes cannot enter a ghost grid column',
+ };
+ }
+ const pathA = findPanePath(layout.content, kindA);
+ const pathB = findPanePath(layout.content, kindB);
+ if (!pathA || !pathB) {
+ return { layout, applied: false, reason: `pane kind not found: ${!pathA ? kindA : kindB}` };
+ }
+ const next = structuredClone(layout);
+ const nodeA = nodeAtPath(next.content, pathA);
+ const nodeB = nodeAtPath(next.content, pathB);
+ if (!nodeA || !nodeB || nodeA.type !== 'pane' || nodeB.type !== 'pane') {
+ return { layout, applied: false };
+ }
+ const cloneA = structuredClone(nodeA);
+ const cloneB = structuredClone(nodeB);
+ const withA = setNodeAtPath(next.content, pathA, cloneB);
+ if (!withA) return { layout, applied: false };
+ next.content = withA;
+ const withB = setNodeAtPath(next.content, pathB, cloneA);
+ if (!withB) return { layout, applied: false };
+ next.content = withB;
+ return finishOp(layout, next, 'swapPanesByKind rejected');
+}
+
/**
* 在分割内把 amount 份额从 fromIndex child 转移给 toIndex child(引擎分割线
* 拖宽的提交操作 —— 只动缝两侧的邻居,其余 children 份额不受影响;与
@@ -541,8 +884,10 @@ export function transferSplitFraction(
const split = findSplitById(next.content, splitId);
if (!split) return { layout, applied: false, reason: `split not found: ${splitId}` };
if (
- fromIndex < 0 || fromIndex >= split.children.length ||
- toIndex < 0 || toIndex >= split.children.length
+ fromIndex < 0 ||
+ fromIndex >= split.children.length ||
+ toIndex < 0 ||
+ toIndex >= split.children.length
) {
return { layout, applied: false, reason: 'child index out of range' };
}