feat(desktop): 支持无限分屏边缘拖放

This commit is contained in:
xiaomakuaiz committed 2026-08-24 00:06:06 +08:00
1 parent b0809e1a23
commit aaf50c0653
11 files changed
+895 -257

No files matched your search

+17 -9
View File
@@ -48,7 +48,7 @@
「没啥用」:拆分/关闭本身就是布局手段);「新建」主钮的家在任务列顶行。**新建即新格**(2026-08-18
用户定案「创建任务也是一个 panel」):列侧一切新建入口(列顶主钮/组头
「+」/组头右键)有空格先用空格,没有就把焦点格向右拆一格**专供创建**
(spawned 标记,取消即收回不留尾巴),满 6 格退化占焦点格;格内入口
(spawned 标记,取消即收回不留尾巴),不设格数上限;格内入口
(提示卡/装载卡)仍就地创建。**窗顶 chrome 行(列顶行/
列收起顶条/设置页头)一律 h-10(40px)+ mac 4px 底衬**——先按 mac 原生灯(垂直中心 ≈18)定过 h-9
同心,用户复看「有点太小」加到 40;「行心 20 差 2px 无感」是错判,灯是
@@ -237,13 +237,22 @@
(grid 底色透缝)、无衬无卡衣;**焦点格 = 细头标题 primary 下划线**
(data-split-focus 迁至下划线,常驻透明底防抖),落点 secondary 虚环
保留;**单格融合已反转退役**——格恒平铺、细头恒在,右侧顶条仅列收起
时存在)+ **布局树递归渲染**(features/split/tree.ts,tmux 同构;
用户终案「随便他搞」,固定档位模型退役):叶=格(上限 6)、内部节点=
切分,每格细头可「向右/向下拆分」「关闭(兄弟上位,最后一格置灰)」,
**按住格头标题拖拽换位**(HTML5 dnd 私有 MIME,落点 secondary 虚环);
时存在)+ **布局树迭代扁平渲染**(features/split/tree.ts,tmux 同构;树投影
为 grid 下同级 pane/handle,深树不进入 JS/React/DOM 递归栈;用户终案
「随便他搞」,固定档位模型退役):叶=格(不设数量
上限)、内部节点=切分,每格细头可「向右/向下拆分」「关闭(兄弟上位,
最后一格置灰)」,**按住格头标题拖拽**(HTML5 dnd 私有 MIME):落在
Panel 中心交换位置;落在整个格区上边缘/右边缘则把该 Panel 搬到根级
对应边缘并收拢原位置。任务列拖行同用这两个根边缘落点新增 Panel,中心
仍定点替换;中心落点用 secondary 虚环、根边缘用对应边带高亮;
每条分隔线恰是一个树节点,拖它只动两侧子树(固定档位时代"一条线牵动
别的格"的三轮拉扯就此消解),8px 透明把手骑 1px 分隔线,0.2–0.8 夹取,
双击平分;trackPointer 收尾纪律同 FilesDrawer(mouseup 与卸载兜底双路
别的格"的三轮拉扯就此消解),8px 透明把手骑 1px 分隔线,树比例只守
ε–(1−ε) 以容纳任意格数,手动拖动则按所属区域为两侧各留至少 48px;
实际不足 48px 可用尺寸的深层子树仅保留焦点路径、不物化其余
pane/handle,画布尺寸变化后重算;同屏 pane/handle 各有 512 DOM 物化
预算(只限视图实例、不限制树中格数,焦点路径优先),避免 4K 画布上的
合法深树仍扩成数万 DOM。双击平分;trackPointer 收尾纪律同
FilesDrawer(mouseup 与卸载兜底双路
收回 body 全局样式)。格 = 细头(**h-12 主头**——右侧无顶条后它就是每格
的视图头,2026-08-19 用户「再大一点」;白底 + 拖窗面;状态点 12px 定宽
槽/标题 14px(焦点下划线**绝对定位悬挂**,盒 block+w-fit——truncate 的
@@ -261,8 +270,7 @@
格操作,confirm 两击走 openMenu 现成机制,端口预览取快照、开菜单触发
拉取下次可见(动态分节只归整页头);插槽 ref 回调必须恒等,每渲染换新函数会 detach/attach 打状态
直至 Maximum update depth,实测钉死);拆右/拆下/独占/更换四个分窗操作
收进 ⋯ 菜单(openMenu,2026-08-18「不是常见的操作」;满 6 拆分项置灰
带因);**关闭钮可关才渲染**(独格整颗不出,置灰版 2026-08-19「去掉
收进 ⋯ 菜单(openMenu,2026-08-18「不是常见的操作」);**关闭钮可关才渲染**(独格整颗不出,置灰版 2026-08-19「去掉
吧」)。簇 hover 显隐(invisible 常驻占位),更换/独占态强制可见——
**无**归档/删除,行政回任务列;空格也有细头,否则关不掉)+ ChatView
pane 变体(无 52px 头/文件抽屉入口(细头代之);**大纲左缘浮轨格内
@@ -129,6 +129,23 @@ const fakeDT = () => {
};
};
/** jsdom 未实现 DragEvent,fireEvent.dragOver 不会带上指针坐标。 */
const fireDragAt = (
target: Element,
type: "dragover" | "drop",
dataTransfer: ReturnType<typeof fakeDT>,
clientX: number,
clientY: number,
) => {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, {
dataTransfer: { value: dataTransfer },
clientX: { value: clientX },
clientY: { value: clientY },
});
fireEvent(target, event);
};
describe("分屏视图(树形布局)", () => {
it("首启缺省单格(2026-08-20 定案:新用户不见空栏;存过树不受影响)", () => {
stubShell();
@@ -136,6 +153,52 @@ describe("分屏视图(树形布局)", () => {
expect(screen.getAllByRole("region")).toHaveLength(1);
});
it("恢复时压密超大叶槽号并丢弃离树长尾,装载不再扩巨型数组", async () => {
stubShell();
localStorage.setItem("mc.splitTree", JSON.stringify({ leaf: Number.MAX_SAFE_INTEGER }));
localStorage.setItem("mc.splitSlots", JSON.stringify(Array.from({ length: 500 }, (_, i) => `c:orphan-${i}`)));
render(<Harness />);
expect(screen.getByRole("region", { name: "第 1 格" })).toBeTruthy();
await waitFor(() => expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null")).toEqual({ leaf: 0 }));
expect(JSON.parse(localStorage.getItem("mc.splitSlots") ?? "null")).toEqual([]);
});
it("20,001 叶深存档启动时只物化像素可见子树", () => {
stubShell();
const parts: string[] = [];
for (let slot = 0; slot < 20_000; slot++) {
parts.push(`{"dir":"col","ratio":0.5,"a":{"leaf":${slot}},"b":`);
}
localStorage.setItem("mc.splitTree", parts.join("") + '{"leaf":20000}' + "}".repeat(20_000));
const { container } = render(<Harness />);
expect(container.querySelectorAll("section[aria-label$='格']").length).toBeLessThan(32);
expect(container.querySelectorAll("[data-split-handle]").length).toBeLessThan(32);
});
it("4K 画布中的 20,001 叶平衡存档仍受全局物化预算约束", () => {
stubShell();
let level = Array.from({ length: 20_001 }, (_, slot) => `{"leaf":${slot}}`);
let depth = 0;
while (level.length > 1) {
const next: string[] = [];
for (let index = 0; index < level.length; index += 2) {
const a = level[index]!;
const b = level[index + 1];
next.push(b ? `{"dir":"${depth % 2 === 0 ? "col" : "row"}","ratio":0.5,"a":${a},"b":${b}}` : a);
}
level = next;
depth += 1;
}
localStorage.setItem("mc.splitTree", level[0]!);
const width = vi.spyOn(window, "innerWidth", "get").mockReturnValue(3840);
const height = vi.spyOn(window, "innerHeight", "get").mockReturnValue(2160);
const { container } = render(<Harness />);
width.mockRestore();
height.mockRestore();
expect(container.querySelectorAll("section[aria-label$='格']").length).toBeLessThanOrEqual(512);
expect(container.querySelectorAll("[data-split-handle]").length).toBeLessThanOrEqual(512);
});
it("存档双格:槽 0 挂会话,槽 1 装载卡——tab、项目分组、临时会话段、已入格判重排除", async () => {
stubShell();
localStorage.setItem("mc.workbenchListHidden", "1"); // 钉在装载卡路径(任务列默认展开时空格是提示卡)
@@ -185,7 +248,7 @@ describe("分屏视图(树形布局)", () => {
expect(within(loader).getAllByText("A 跑着")).toHaveLength(1);
});
it("右分屏:长出第三格(新格取最小空槽号、装载卡形态、树落盘);满 6 格置灰", async () => {
it("右分屏:新格取最小空槽号、树落盘且可继续拆出第七格", async () => {
stubShell();
localStorage.setItem("mc.splitTree", JSON.stringify({ dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } }));
render(<Harness />);
@@ -197,17 +260,19 @@ describe("分屏视图(树形布局)", () => {
expect(screen.getByRole("region", { name: "第 3 格" })).toBeTruthy();
const saved = JSON.parse(localStorage.getItem("mc.splitTree") ?? "null");
expect(saved).not.toBeNull();
// 连拆到 6 格
// 连拆到 6 格后菜单仍可继续拆分
for (let i = 0; i < 3; i++) {
await userEvent.click(screen.getAllByRole("button", { name: "格操作" })[0]!);
await userEvent.click(within(document.body.lastElementChild as HTMLElement).getByText("下分屏"));
}
expect(screen.getAllByRole("region")).toHaveLength(6);
// 满 6:菜单里两个拆分项置灰
await userEvent.click(screen.getAllByRole("button", { name: "格操作" })[0]!);
const capMenu = document.body.lastElementChild as HTMLElement;
expect((within(capMenu).getByText("右分屏").closest("button") as HTMLButtonElement).disabled).toBe(true);
expect((within(capMenu).getByText("下分屏").closest("button") as HTMLButtonElement).disabled).toBe(true);
const menu = document.body.lastElementChild as HTMLElement;
const splitRight = within(menu).getByText("右分屏").closest("button") as HTMLButtonElement;
expect(splitRight.disabled).toBe(false);
await userEvent.click(splitRight);
expect(screen.getAllByRole("region")).toHaveLength(7);
expect(screen.getByRole("region", { name: "第 7 格" })).toBeTruthy();
});
it("工作台 inactive 时不响应聚焦、侧栏和分屏快捷键", async () => {
@@ -251,7 +316,7 @@ describe("分屏视图(树形布局)", () => {
expect(aside.style.width).toBe("232px");
});
it("工作台快捷键只操作焦点格:聚焦、侧栏、两向分屏与六格上限", async () => {
it("工作台快捷键只操作焦点格,且可连续拆分超过六格", async () => {
stubShell();
localStorage.setItem("mc.splitSlots", JSON.stringify(["s1", null, null, null, null, null]));
render(<Harness />);
@@ -272,7 +337,7 @@ describe("分屏视图(树形布局)", () => {
expect(screen.getByRole("region", { name: "第 3 格" }).querySelector("[data-split-focus]")).not.toBeNull();
for (let i = 0; i < 4; i++) fireEvent.keyDown(window, { key: "\\", code: "Backslash", ctrlKey: true });
expect(screen.getAllByRole("region")).toHaveLength(6);
expect(screen.getAllByRole("region")).toHaveLength(7);
});
it("Ctrl+N 沿用当前任务类型;侧栏帮助入口展示快捷键并由 Esc 关闭", async () => {
@@ -416,6 +481,11 @@ describe("分屏视图(树形布局)", () => {
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").a.ratio).toBeCloseTo(0.75);
fireEvent.doubleClick(container.querySelector('[data-split-handle="a"]')!);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").a.ratio).toBe(0.5);
const resetHandle = container.querySelector<HTMLElement>('[data-split-handle="a"]')!;
fireEvent.mouseDown(resetHandle, { clientY: 400 });
fireEvent.mouseMove(window, { clientY: 0 });
fireEvent.mouseUp(window);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").a.ratio).toBeCloseTo(48 / 800);
});
it("三格双击贯通线:按辖下格数分成 2:1,并递归均分左侧两格", () => {
@@ -436,7 +506,7 @@ describe("分屏视图(树形布局)", () => {
expect(saved.a.ratio).toBe(0.5);
});
it("六格 1:5 均分后键盘沿边界方向不反跳", () => {
it("七格 1:6 均分可落盘并继续用键盘调整", () => {
stubShell();
localStorage.setItem(
"mc.splitTree",
@@ -456,7 +526,12 @@ describe("分屏视图(树形布局)", () => {
dir: "col",
ratio: 0.5,
a: { leaf: 3 },
b: { dir: "col", ratio: 0.5, a: { leaf: 4 }, b: { leaf: 5 } },
b: {
dir: "col",
ratio: 0.5,
a: { leaf: 4 },
b: { dir: "col", ratio: 0.5, a: { leaf: 5 }, b: { leaf: 6 } },
},
},
},
},
@@ -465,11 +540,11 @@ describe("分屏视图(树形布局)", () => {
const { container } = render(<Harness />);
const root = container.querySelector<HTMLElement>('[data-split-handle="root"]')!;
fireEvent.doubleClick(root);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 6);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 7);
fireEvent.keyDown(root, { key: "ArrowLeft" });
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 6);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 7 - 0.05);
fireEvent.keyDown(root, { key: "ArrowRight" });
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 6 + 0.05);
expect(JSON.parse(localStorage.getItem("mc.splitTree") ?? "null").ratio).toBeCloseTo(1 / 7);
});
it("按住格头标题拖到另一格 = 交换位置(内容跟格走,落点有高亮)", () => {
@@ -495,6 +570,63 @@ describe("分屏视图(树形布局)", () => {
expect(screen.getByRole("region", { name: "第 2 格" }).querySelector("[data-split-focus]")).toBeNull();
});
it("任务拖到整个主视图上边缘 = 新建根级顶部格;原格不被替换", () => {
stubShell();
localStorage.setItem("mc.splitTree", JSON.stringify({ dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } }));
localStorage.setItem("mc.splitSlots", JSON.stringify(["s1", null]));
const { container } = render(<Harness />);
const grid = container.querySelector<HTMLElement>("[data-split-grid]")!;
vi.spyOn(grid, "getBoundingClientRect").mockReturnValue({
left: 0, top: 0, width: 1000, height: 800, right: 1000, bottom: 800, x: 0, y: 0, toJSON: () => ({}),
});
const first = screen.getByRole("region", { name: "第 1 格" });
const row = within(screen.getByRole("complementary", { name: "选择任务" })).getByText("跑着的任务").closest("button")!;
const dt = fakeDT();
fireEvent.dragStart(row, { dataTransfer: dt });
fireDragAt(first, "dragover", dt, 500, 12);
expect(grid.querySelector('[data-split-root-drop="top"]')).not.toBeNull();
expect(first.querySelector("[data-split-drop]")).toBeNull();
fireDragAt(first, "drop", dt, 500, 12);
const panes = screen.getAllByRole("region");
expect(panes).toHaveLength(3);
expect(panes[0]!.getAttribute("aria-label")).toBe("第 3 格");
expect(within(panes[0]!).getByTitle(/跑着的任务/)).toBeTruthy();
expect(within(screen.getByRole("region", { name: "第 1 格" })).getByTitle(/已入格的任务/)).toBeTruthy();
});
it("Panel 拖到整个主视图右边缘 = 搬到根级右侧并收拢原位置", () => {
stubShell();
localStorage.setItem(
"mc.splitTree",
JSON.stringify({
dir: "row",
ratio: 0.5,
a: { dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } },
b: { leaf: 2 },
}),
);
localStorage.setItem("mc.splitSlots", JSON.stringify(["s1", "s2", "s3"]));
const { container } = render(<Harness />);
const grid = container.querySelector<HTMLElement>("[data-split-grid]")!;
vi.spyOn(grid, "getBoundingClientRect").mockReturnValue({
left: 0, top: 0, width: 1000, height: 800, right: 1000, bottom: 800, x: 0, y: 0, toJSON: () => ({}),
});
const first = screen.getByRole("region", { name: "第 1 格" });
const target = screen.getByRole("region", { name: "第 3 格" });
const dt = fakeDT();
fireEvent.dragStart(within(first).getByTitle(/已入格的任务/), { dataTransfer: dt });
fireDragAt(target, "dragover", dt, 988, 400);
expect(grid.querySelector('[data-split-root-drop="right"]')).not.toBeNull();
fireDragAt(target, "drop", dt, 988, 400);
const panes = screen.getAllByRole("region");
expect(panes).toHaveLength(3);
expect(panes.map((pane) => pane.getAttribute("aria-label"))).toEqual(["第 2 格", "第 3 格", "第 1 格"]);
expect(within(panes[2]!).getByTitle(/已入格的任务/)).toBeTruthy();
expect(JSON.parse(localStorage.getItem("mc.splitSlots") ?? "[]")).toEqual(["s1", "s2", "s3"]);
});
it("布局模板钮退役(2026-08-18 用户定案「没啥用」——拆分/关闭本身就是布局手段):头部无布局组", () => {
stubShell();
localStorage.setItem("mc.splitTree", JSON.stringify({ dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } }));
@@ -509,12 +641,14 @@ describe("分屏视图(树形布局)", () => {
expect(within(screen.getByRole("region", { name: "第 1 格" })).getByRole("button", { name: "格操作" })).toBeTruthy();
});
it("格细头「会话文件」开全局文件抽屉(2026-08-16 报障「看文件的功能咋没了」)", async () => {
it("第七格的动态细头插槽可用:「会话文件」打开文件抽屉", async () => {
stubShell();
localStorage.setItem("mc.splitTree", JSON.stringify({ dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } }));
localStorage.setItem("mc.splitSlots", JSON.stringify(["s1", null, null, null, null, null]));
localStorage.setItem("mc.splitTree", JSON.stringify({ leaf: 6 }));
localStorage.setItem("mc.splitSlots", JSON.stringify([null, null, null, null, null, null, "s1"]));
render(<Harness />);
await userEvent.click(within(screen.getByRole("region", { name: "第 1 格" })).getByRole("button", { name: "会话文件" }));
await userEvent.click(
await within(screen.getByRole("region", { name: "第 7 格" })).findByRole("button", { name: "会话文件" }),
);
// FilesDrawer 挂上(文件/改动两页签);关掉即收
expect(await screen.findByRole("tab", { name: /文件/ })).toBeTruthy();
});
@@ -622,7 +756,7 @@ describe("分屏视图(树形布局)", () => {
await waitFor(() => expect(JSON.parse(localStorage.getItem("mc.splitSlots") ?? "[]")[2]).toBe("created"));
});
it("六格全满时新建表单覆盖焦点格,不会把打开前已有会话误判成外部装载", async () => {
it("六格全满时新建表单拆出第七格,不覆盖已有会话", async () => {
stubShell();
const sixTree = {
dir: "col",
@@ -637,8 +771,9 @@ describe("分屏视图(树形布局)", () => {
await userEvent.click(
within(screen.getByRole("complementary", { name: "选择任务" })).getByRole("button", { name: "新建任务" }),
);
expect(screen.getAllByRole("region")).toHaveLength(6);
expect(within(screen.getByRole("region", { name: "第 1 格" })).getByRole("heading", { name: "新建任务" })).toBeTruthy();
expect(screen.getAllByRole("region")).toHaveLength(7);
expect(within(screen.getByRole("region", { name: "第 7 格" })).getByRole("heading", { name: "新建任务" })).toBeTruthy();
expect(within(screen.getByRole("region", { name: "第 1 格" })).getByTitle(/^满格 0/)).toBeTruthy();
});
it("工作台 inactive 时 window 级原生文件拖放不投递到后台 pane", async () => {
+346 -101
View File
@@ -3,8 +3,8 @@
// 标题 + 布局下拉 + 设置)+ 可折叠任务列(三 tab:本地项目/本地会话/
// 云端任务——导航全部在此,行政事务随之迁入:行右键 改名/归档/删除、
// 已归档折叠小节、待办组、云端列表整体复用 CloudTaskList)+ 布局树格区。
// 布局 = 用户拆的二叉树(tree.ts,tmux/iTerm 同构):每格可向右/向下拆分
// (上限 SPLIT_MAX_PANES)、可关闭(兄弟上位)、按住格头标题拖拽换位;
// 布局 = 用户拆的二叉树(tree.ts,tmux/iTerm 同构):每格可向右/向下拆分、
// 可关闭(兄弟上位)、按住格头标题拖拽换位;
// 每条分隔线恰是一个树节点,拖它只动两侧子树。1/2横/2纵/4 为快捷模板。
// 每格 = 细头 + ChatView/CloudTaskView 的 pane 变体(全交互;槽位条目经
// slots.ts 的 "c:" 记号分流本地/云端);空槽:任务列展开时 = 轻提示卡,
@@ -31,7 +31,7 @@ import {
IconWorld,
IconX,
} from "@tabler/icons-react";
import { Fragment, useEffect, useEffectEvent, useMemo, useRef, useState, type DragEvent as ReactDragEvent, type MouseEvent as ReactMouseEvent } from "react";
import { Fragment, useEffect, useEffectEvent, useRef, useState, type DragEvent as ReactDragEvent, type MouseEvent as ReactMouseEvent } from "react";
import { createPortal } from "react-dom";
import { ChatView } from "@/features/chat/ChatView";
@@ -51,7 +51,40 @@ import { TODO_GROUP_KEY, TodoSection, type TodoWiring } from "@/features/todo/To
const SIDE_MIN = 184;
const SIDE_MAX = 420;
const SIDE_DEFAULT = 232; // = --spacing-side
const ROOT_DROP_EDGE_SIZE = 48;
const MIN_DRAG_PANE_SIZE = 48;
const MIN_MATERIALIZED_PANE_SIZE = 48;
const MAX_MATERIALIZED_PANES = 512;
const MAX_MATERIALIZED_HANDLES = 512;
const FALLBACK_GRID_WIDTH = 1024;
const FALLBACK_GRID_HEIGHT = 768;
const CHATS_GROUP_KEY = "\0chats";
interface SplitRect {
x: number;
y: number;
width: number;
height: number;
}
interface SplitRenderPath {
parent: SplitRenderPath | null;
side: "a" | "b";
depth: number;
}
const splitPathString = (path: SplitRenderPath | null): string => {
if (!path) return "";
const chars = new Array<string>(path.depth);
let current: SplitRenderPath | null = path;
while (current) {
chars[current.depth - 1] = current.side;
current = current.parent;
}
return chars.join("");
};
const pct = (value: number) => `${value * 100}%`;
import { useI18n, type MessageKey } from "@/lib/i18n";
import type { CloudProject, CloudTask, CloudTaskDetail } from "@/lib/ipc/cloudtasks";
import type { SessionKind, SessionMeta } from "@/lib/ipc/sessions";
@@ -60,10 +93,10 @@ import { groupSessions, projectKey, readArchivedProjects, readCollapsedGroups, r
import { Brand } from "@/features/titlebar/TitleBar";
import { useUpdate } from "@/features/update/useUpdate";
import { isMacShell, openExternal } from "@/lib/ipc/host";
import { readFold, SPLIT_MAX_PANES, writeFold } from "@/lib/util/prefs";
import { readFold, writeFold } from "@/lib/util/prefs";
import { renameIsNoop } from "@/lib/util/rename";
import { cloudSlotId, cloudTaskIdOf, firstEmptyIn, isCloudSlotId, LOAD_MIME, SWAP_MIME } from "./slots";
import { leaves, paneCount, SPLIT_MAX_RATIO, SPLIT_MIN_RATIO, type SplitDir, type SplitNode } from "./tree";
import { leaves, paneCount, SPLIT_MAX_RATIO, SPLIT_MIN_RATIO, type SplitDir, type SplitNode, type SplitRootEdge } from "./tree";
import type { SplitStateApi } from "./useSplitState";
/** 快捷模板(「布局」下拉):套形状不套比例;当前同形的项 menu-active。 */
@@ -170,7 +203,29 @@ export function SplitView({
todoId?: string;
} | null>(null);
const [dropSlot, setDropSlot] = useState<number | null>(null);
const [dropEdge, setDropEdge] = useState<SplitRootEdge | null>(null);
const [shortcutsOpen, setShortcutsOpen] = useState(false);
const gridRef = useRef<HTMLDivElement>(null);
const [gridSize, setGridSize] = useState(() => ({
width: typeof window === "undefined" ? FALLBACK_GRID_WIDTH : window.innerWidth || FALLBACK_GRID_WIDTH,
height: typeof window === "undefined" ? FALLBACK_GRID_HEIGHT : window.innerHeight || FALLBACK_GRID_HEIGHT,
}));
useEffect(() => {
const grid = gridRef.current;
if (!grid) return;
const update = () => {
const rect = grid.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
setGridSize((prev) =>
prev.width === rect.width && prev.height === rect.height ? prev : { width: rect.width, height: rect.height },
);
};
update();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(update);
observer.observe(grid);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (!active) setShortcutsOpen(false);
}, [active]);
@@ -215,22 +270,28 @@ export function SplitView({
// 换新函数的话 React 会 detach(null)→attach(el) 反复打状态,直接
// Maximum update depth(实测)
const [paneExtras, setPaneExtras] = useState<Record<number, HTMLElement | null>>({});
const paneExtrasRef = useMemo(
() =>
Array.from({ length: SPLIT_MAX_PANES }, (_, i) => (el: HTMLElement | null) => {
setPaneExtras((prev) => (prev[i] === el ? prev : { ...prev, [i]: el }));
}),
[],
);
const paneExtraRefs = useRef(new Map<number, (el: HTMLElement | null) => void>());
const paneExtraRefFor = (slot: number) => {
const existing = paneExtraRefs.current.get(slot);
if (existing) return existing;
const created = (el: HTMLElement | null) => {
setPaneExtras((prev) => (prev[slot] === el ? prev : { ...prev, [slot]: el }));
};
paneExtraRefs.current.set(slot, created);
return created;
};
// 视图菜单项注册表(开 ⋯ 时现取;注册函数按槽恒等,注销置 null)
const viewMenus = useRef<Record<number, (() => MenuItem[]) | null>>({});
const paneMenuReg = useMemo(
() =>
Array.from({ length: SPLIT_MAX_PANES }, (_, i) => (fn: (() => MenuItem[]) | null) => {
viewMenus.current[i] = fn;
}),
[],
);
const paneMenuRegs = useRef(new Map<number, (fn: (() => MenuItem[]) | null) => void>());
const paneMenuRegFor = (slot: number) => {
const existing = paneMenuRegs.current.get(slot);
if (existing) return existing;
const created = (fn: (() => MenuItem[]) | null) => {
viewMenus.current[slot] = fn;
};
paneMenuRegs.current.set(slot, created);
return created;
};
// 任务列开合(默认展开;键语义取反,见 prefs.FoldKey 注)
const [listOpen, setListOpen] = useState(() => !readFold("mc.workbenchListHidden"));
const toggleList = () => {
@@ -243,7 +304,6 @@ export function SplitView({
const placed = new Set(split.slots.filter(Boolean) as string[]);
const zoomedSlot = split.zoomed;
const total = paneCount(split.tree);
const canSplit = total < SPLIT_MAX_PANES;
const canClose = total > 1;
const visible = zoomedSlot !== null ? 1 : total;
const visibleLeaves = zoomedSlot !== null ? [zoomedSlot] : leaves(split.tree);
@@ -267,9 +327,8 @@ export function SplitView({
};
/** 「新建即新格」(2026-08-18 用户定案「创建任务也是一个 panel」):列侧
* 一切新建入口走此——有空格先用空格(它就是现成的新格),没有就把焦点
* 格向右拆一格**专供创建**(spawned,取消即收回,不留空格尾巴);满
* 6 格退化为旧行为(占焦点格,取消回原会话)。格内入口(提示卡/装载
* 卡)仍就地创建,不走这条。 */
* 格向右拆一格**专供创建**(spawned,取消即收回,不留空格尾巴)。格内
* 入口(提示卡/装载卡)仍就地创建,不走这条。 */
const openCreateInNewPane = (kind: SessionKind | "cloud", extras?: CreateExtras) => {
if (split.zoomed !== null) split.toggleZoom(split.zoomed); // 独占态先回程
const all = leaves(split.tree);
@@ -278,13 +337,11 @@ export function SplitView({
openCreate(kind, empty, extras);
return;
}
if (all.length < SPLIT_MAX_PANES) {
const spawned = split.splitPane(split.focused, "col");
if (spawned !== null) {
setSwapSlot(null);
setCreatingSlot({ slot: spawned, kind, entryAtOpen: null, ...extras, spawned: true });
return;
}
const spawned = split.splitPane(split.focused, "col");
if (spawned !== null) {
setSwapSlot(null);
setCreatingSlot({ slot: spawned, kind, entryAtOpen: null, ...extras, spawned: true });
return;
}
openCreate(kind, undefined, extras);
};
@@ -358,19 +415,32 @@ export function SplitView({
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", finish);
};
// 与树存档/双击均分共用边界;六格 1:5 时需要允许到 1/6。
const clamp = (v: number) => Math.min(SPLIT_MAX_RATIO, Math.max(SPLIT_MIN_RATIO, v));
const startHandleDrag = (path: string, dir: SplitDir) => (e: ReactMouseEvent) => {
// 树值本身不设与格数绑定的固定下限;真实拖动按当前所属区域至少留出
// 48px,避免 Number.EPSILON 在浏览器布局中被量化成 0px。
const clampVisible = (v: number, pixels: number) => {
if (pixels <= 0) return clamp(v); // jsdom/首拍尚无布局度量
const min = Math.min(0.5, MIN_DRAG_PANE_SIZE / pixels);
return Math.min(1 - min, Math.max(min, v));
};
const startHandleDrag = (path: () => string, dir: SplitDir, area: SplitRect) => (e: ReactMouseEvent) => {
e.preventDefault();
// 分隔线的坐标系就是它所属切分容器(把手的父节点),树再深也各算各的
const rect = (e.currentTarget as HTMLElement).parentElement?.getBoundingClientRect();
if (!rect) return;
const grid = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-split-grid]");
if (!grid) return;
const gridRect = grid.getBoundingClientRect();
const rect = {
left: gridRect.left + area.x * gridRect.width,
top: gridRect.top + area.y * gridRect.height,
width: area.width * gridRect.width,
height: area.height * gridRect.height,
};
const resolvedPath = path();
trackPointer(dir === "col" ? "col-resize" : "row-resize", (ev) => {
const frac =
dir === "col"
? (ev.clientX - rect.left) / Math.max(1, rect.width)
: (ev.clientY - rect.top) / Math.max(1, rect.height);
split.setNodeRatio(path, clamp(frac));
split.setNodeRatio(resolvedPath, clampVisible(frac, dir === "col" ? rect.width : rect.height));
});
};
@@ -385,6 +455,51 @@ export function SplitView({
// ==== 格上拖拽落点(两条通道):格头换位(SWAP)与任务列拖行装载(LOAD)。
// 私有 MIME 判定,ChatView pane 自己收文件拖放,互不打扰 ====
const rootDropEdgeOf = (e: ReactDragEvent<HTMLElement>): SplitRootEdge | null => {
const rect = e.currentTarget.getBoundingClientRect();
const top = e.clientY - rect.top;
const right = rect.right - e.clientX;
const inX = e.clientX >= rect.left && e.clientX <= rect.right;
const inY = e.clientY >= rect.top && e.clientY <= rect.bottom;
const hitsTop = inX && top >= 0 && top <= ROOT_DROP_EDGE_SIZE;
const hitsRight = inY && right >= 0 && right <= ROOT_DROP_EDGE_SIZE;
if (hitsTop && hitsRight) return top <= right ? "top" : "right";
if (hitsTop) return "top";
if (hitsRight) return "right";
return null;
};
const hasSplitDrag = (e: ReactDragEvent) => {
const types = [...e.dataTransfer.types];
return types.includes(SWAP_MIME) || types.includes(LOAD_MIME);
};
const onGridDragOverCapture = (e: ReactDragEvent<HTMLDivElement>) => {
if (!hasSplitDrag(e)) return;
const edge = rootDropEdgeOf(e);
setDropEdge(edge);
if (!edge) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "move";
setDropSlot(null);
};
const onGridDropCapture = (e: ReactDragEvent<HTMLDivElement>) => {
if (!hasSplitDrag(e)) return;
const edge = rootDropEdgeOf(e);
if (!edge) return;
e.preventDefault();
e.stopPropagation();
setDropEdge(null);
setDropSlot(null);
const swapRaw = e.dataTransfer.getData(SWAP_MIME);
if (swapRaw !== "") {
const src = Number(swapRaw);
if (Number.isSafeInteger(src) && leaves(split.tree).includes(src)) split.movePaneToRoot(src, edge);
return;
}
const loadRaw = e.dataTransfer.getData(LOAD_MIME);
if (loadRaw !== "") pick(split.addRootPane(edge), loadRaw);
};
const onPaneDragOver = (slot: number) => (e: ReactDragEvent) => {
const types = [...e.dataTransfer.types];
if (!types.includes(SWAP_MIME) && !types.includes(LOAD_MIME)) return;
@@ -476,7 +591,7 @@ export function SplitView({
focused={focused && visible > 1}
attention={attention}
onRename={admin && meta ? (title) => admin.onRename(meta, title) : undefined}
extrasRef={paneExtrasRef[slot]}
extrasRef={entry ? paneExtraRefFor(slot) : undefined}
viewMenu={() => [
// 本地格行政项(与云端格 终止/删除 对称;旧详情页 ⋯ 三件套
// 缺的两件,2026-08-20 审计补齐):同走 admin 接线,错误外显
@@ -500,7 +615,6 @@ export function SplitView({
]}
zoomed={zoomedSlot === slot}
swapping={swapSlot === slot}
canSplit={canSplit}
canClose={canClose}
onSplit={(dir) => {
setSwapSlot(null);
@@ -579,7 +693,7 @@ export function SplitView({
variant="pane"
task={cloudTask}
headerSlot={paneExtras[slot] ?? null}
menuRegister={paneMenuReg[slot]}
menuRegister={paneMenuRegFor(slot)}
hotkeysActive={active && focused}
nativeDropEnabled={active && focused}
focusRequest={active && focused ? focusRequest : 0}
@@ -612,65 +726,176 @@ export function SplitView({
);
};
/** 递归渲染布局树:切分节点 = 两个按比例伸展的子容器 + 骑在 1px 分隔线
* 上的把手(8px 透明热区,双击按辖下叶数递归均分面积)。平铺分栏(2026-08-19 用户
* mockup 终案):浮卡的 12px 缝在多格时每格白吃 ~30px 宽,回 1px 细线。 */
const renderNode = (node: SplitNode, path: string) => {
if ("leaf" in node) return renderPane(node.leaf);
const vertical = node.dir === "col";
/** 把布局树迭代投影成同级 pane/handle,避免深树继续形成深 Fiber/DOM。 */
const renderLayout = (root: SplitNode) => {
type Branch = Extract<SplitNode, { dir: SplitDir }>;
const pending: { node: SplitNode; path: SplitRenderPath | null; area: SplitRect }[] = [
{ node: root, path: null, area: { x: 0, y: 0, width: 1, height: 1 } },
];
const panes: { slot: number; area: SplitRect }[] = [];
const handles: { node: Branch; path: SplitRenderPath | null; area: SplitRect; id: number }[] = [];
const viewportWidth = gridSize.width || FALLBACK_GRID_WIDTH;
const viewportHeight = gridSize.height || FALLBACK_GRID_HEIGHT;
const materialized = (area: SplitRect) =>
area.width * viewportWidth >= MIN_MATERIALIZED_PANE_SIZE &&
area.height * viewportHeight >= MIN_MATERIALIZED_PANE_SIZE;
// 像素虚拟化仍要保留焦点叶及其祖先:格数超过画布容量时,当前格
// 不能因面积不足而连操作入口一起消失。
const focusedNodes = new Set<SplitNode>();
const parents = new Map<SplitNode, SplitNode | null>([[root, null]]);
const leafOrder = new Map<number, number>();
const branchOrder = new Map<SplitNode, number>();
const search: SplitNode[] = [root];
let focusedNode: SplitNode | null = null;
let visitOrder = 0;
while (search.length > 0) {
const node = search.pop()!;
if ("leaf" in node) {
leafOrder.set(node.leaf, visitOrder++);
if (node.leaf === split.focused) focusedNode = node;
continue;
}
branchOrder.set(node, visitOrder++);
parents.set(node.a, node);
parents.set(node.b, node);
search.push(node.b, node.a);
}
while (focusedNode) {
focusedNodes.add(focusedNode);
focusedNode = parents.get(focusedNode) ?? null;
}
while (pending.length > 0) {
const item = pending.pop()!;
if ("leaf" in item.node) {
if (panes.length < MAX_MATERIALIZED_PANES || item.node.leaf === split.focused) {
panes.push({ slot: item.node.leaf, area: item.area });
}
continue;
}
const node = item.node;
const depth = (item.path?.depth ?? 0) + 1;
const aPath: SplitRenderPath = { parent: item.path, side: "a", depth };
const bPath: SplitRenderPath = { parent: item.path, side: "b", depth };
const aArea: SplitRect = { ...item.area };
const bArea: SplitRect = { ...item.area };
if (node.dir === "col") {
aArea.width *= node.ratio;
bArea.x += aArea.width;
bArea.width *= 1 - node.ratio;
} else {
aArea.height *= node.ratio;
bArea.y += aArea.height;
bArea.height *= 1 - node.ratio;
}
// 不物化实际不足一个可用 pane 尺寸的子树:它既不能完整交互,继续挂完整
// PaneHeader/ChatView 只会让恶意深树产生数十万 DOM。ResizeObserver
// 会在画布变大后重算;正常拖动另有 48px 下限,不会制造这种子树。
const onFocusedPath = focusedNodes.has(node);
// 焦点路径每层连同直接兄弟一起保留,保证连续拆分后新格和被拆格都
// 仍有可操作入口;兄弟若还是巨大子树,其更深后代仍受像素阈值约束。
const aVisible = materialized(aArea) || onFocusedPath || focusedNodes.has(node.a);
const bVisible = materialized(bArea) || onFocusedPath || focusedNodes.has(node.b);
if (((aVisible && bVisible) || onFocusedPath) && handles.length < MAX_MATERIALIZED_HANDLES) {
handles.push({ node, path: item.path, area: item.area, id: handles.length });
}
// 栈后进先出:焦点子树后压、优先遍历,确保全局物化预算先留给当前格。
if (focusedNodes.has(node.b)) {
if (aVisible) pending.push({ node: node.a, path: aPath, area: aArea });
if (bVisible) pending.push({ node: node.b, path: bPath, area: bArea });
} else {
if (bVisible) pending.push({ node: node.b, path: bPath, area: bArea });
if (aVisible) pending.push({ node: node.a, path: aPath, area: aArea });
}
}
// 焦点优先只影响谁获得物化预算,不能改变 DOM/辅助技术的树内视觉顺序。
panes.sort((a, b) => (leafOrder.get(a.slot) ?? 0) - (leafOrder.get(b.slot) ?? 0));
handles.sort((a, b) => (branchOrder.get(a.node) ?? 0) - (branchOrder.get(b.node) ?? 0));
return (
<div className={`relative flex min-h-0 min-w-0 flex-1 gap-px ${vertical ? "" : "flex-col"}`}>
<div className="flex min-h-0 min-w-0" style={{ flex: `${node.ratio} 1 0%` }}>
{renderNode(node.a, `${path}a`)}
</div>
<div className="flex min-h-0 min-w-0" style={{ flex: `${1 - node.ratio} 1 0%` }}>
{renderNode(node.b, `${path}b`)}
</div>
<div
data-split-handle={path === "" ? "root" : path}
role="separator"
aria-orientation={vertical ? "vertical" : "horizontal"}
aria-label={t("split.resize")}
aria-valuemin={Math.round(SPLIT_MIN_RATIO * 100)}
aria-valuemax={Math.round(SPLIT_MAX_RATIO * 100)}
aria-valuenow={Math.round(node.ratio * 100)}
tabIndex={0}
title={t("split.resizeHint")}
className={`absolute z-30 focus-visible:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 focus-visible:ring-inset ${
vertical ? "inset-y-0 w-2 -translate-x-1/2 cursor-col-resize" : "inset-x-0 h-2 -translate-y-1/2 cursor-row-resize"
}`}
style={vertical ? { left: `${node.ratio * 100}%` } : { top: `${node.ratio * 100}%` }}
onMouseDown={startHandleDrag(path, node.dir)}
onKeyDown={(e) => {
const delta =
vertical && e.key === "ArrowLeft"
? -0.05
: vertical && e.key === "ArrowRight"
? 0.05
: !vertical && e.key === "ArrowUp"
<>
{panes.map(({ slot, area }) => (
<div
key={`pane-${slot}`}
className="absolute flex min-h-0 min-w-0"
style={{
left: pct(area.x),
top: pct(area.y),
width: pct(area.width),
height: pct(area.height),
minWidth: MIN_MATERIALIZED_PANE_SIZE,
minHeight: MIN_MATERIALIZED_PANE_SIZE,
}}
>
{renderPane(slot)}
</div>
))}
{handles.map(({ node, path, area, id }) => {
const vertical = node.dir === "col";
const resolvePath = () => splitPathString(path);
const pathAttr = !path ? "root" : path.depth <= 64 ? splitPathString(path) : `deep-${id}`;
const boundary = vertical
? area.x + area.width * node.ratio
: area.y + area.height * node.ratio;
return (
<div
key={`handle-${id}`}
data-split-handle={pathAttr}
role="separator"
aria-orientation={vertical ? "vertical" : "horizontal"}
aria-label={t("split.resize")}
aria-valuemin={Math.round(SPLIT_MIN_RATIO * 100)}
aria-valuemax={Math.round(SPLIT_MAX_RATIO * 100)}
aria-valuenow={Math.round(node.ratio * 100)}
tabIndex={0}
title={t("split.resizeHint")}
className={`absolute z-30 focus-visible:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 focus-visible:ring-inset ${
vertical ? "w-2 -translate-x-1/2 cursor-col-resize" : "h-2 -translate-y-1/2 cursor-row-resize"
}`}
style={
vertical
? { left: pct(boundary), top: pct(area.y), height: pct(area.height) }
: { left: pct(area.x), top: pct(boundary), width: pct(area.width) }
}
onMouseDown={startHandleDrag(resolvePath, node.dir, area)}
onKeyDown={(e) => {
const delta =
vertical && e.key === "ArrowLeft"
? -0.05
: !vertical && e.key === "ArrowDown"
: vertical && e.key === "ArrowRight"
? 0.05
: 0;
if (delta === 0) return;
e.preventDefault();
e.stopPropagation();
split.setNodeRatio(path, clamp(node.ratio + delta));
}}
onDoubleClick={() => split.equalizeNode(path)}
>
{/* 画布本体在背景启用时必须透明,否则 pane 的半透明表面会与
画布叠成两层;真正的 1px 分隔面只画在把手中心。 */}
<span
aria-hidden
className={`mc-workbench-surface-300 pointer-events-none absolute ${
vertical
? "inset-y-0 left-1/2 w-px -translate-x-1/2"
: "inset-x-0 top-1/2 h-px -translate-y-1/2"
}`}
/>
</div>
</div>
: !vertical && e.key === "ArrowUp"
? -0.05
: !vertical && e.key === "ArrowDown"
? 0.05
: 0;
if (delta === 0) return;
e.preventDefault();
e.stopPropagation();
const grid = e.currentTarget.closest<HTMLElement>("[data-split-grid]");
const gridRect = grid?.getBoundingClientRect();
const pixels = gridRect
? vertical
? area.width * gridRect.width
: area.height * gridRect.height
: 0;
split.setNodeRatio(resolvePath(), clampVisible(node.ratio + delta, pixels));
}}
onDoubleClick={() => split.equalizeNode(resolvePath())}
>
<span
aria-hidden
className={`mc-workbench-surface-300 pointer-events-none absolute ${
vertical
? "inset-y-0 left-1/2 w-px -translate-x-1/2"
: "inset-x-0 top-1/2 h-px -translate-y-1/2"
}`}
/>
</div>
);
})}
</>
);
};
@@ -817,8 +1042,30 @@ export function SplitView({
{/* 平铺画布:bg 只为透出 1px 分隔线;无衬(2026-08-19 mockup 终案,
浮卡的 12px 衬退役)。拖窗面 = 细头空白区(PaneHeader 自带拖拽
属性)+ 列顶行 */}
<div data-split-grid="" data-tauri-drag-region="" className="mc-workbench-surface-300 flex min-h-0 min-w-0 flex-1">
{zoomedSlot !== null ? renderPane(zoomedSlot) : renderNode(split.tree, "")}
<div
ref={gridRef}
data-split-grid=""
data-tauri-drag-region=""
className="mc-workbench-surface-300 relative flex min-h-0 min-w-0 flex-1"
onDragOverCapture={onGridDragOverCapture}
onDropCapture={onGridDropCapture}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
setDropEdge(null);
setDropSlot(null);
}
}}
>
{zoomedSlot !== null ? renderPane(zoomedSlot) : renderLayout(split.tree)}
{dropEdge && (
<div
aria-hidden
data-split-root-drop={dropEdge}
className={`pointer-events-none absolute z-40 bg-secondary/15 ring-2 ring-secondary/70 ring-inset ${
dropEdge === "top" ? "inset-x-0 top-0 h-12" : "inset-y-0 end-0 w-12"
}`}
/>
)}
</div>
</div>
</main>
@@ -1560,7 +1807,6 @@ function PaneHeader({
viewMenu,
zoomed,
swapping,
canSplit,
canClose,
onSplit,
onZoom,
@@ -1587,7 +1833,6 @@ function PaneHeader({
viewMenu?: () => MenuItem[];
zoomed: boolean;
swapping: boolean;
canSplit: boolean;
canClose: boolean;
onSplit: (dir: SplitDir) => void;
onZoom: () => void;
@@ -1701,8 +1946,8 @@ function PaneHeader({
[
...(meta && onRename ? [{ label: t("sidebar.row.rename"), run: () => setRenaming(true) }] : []),
...(meta ? [{ label: swapping ? t("split.swapCancel") : t("split.swap"), run: onSwap }] : []),
{ label: t("split.splitRight"), disabledReason: canSplit ? undefined : t("split.splitCap"), run: () => onSplit("col") },
{ label: t("split.splitDown"), disabledReason: canSplit ? undefined : t("split.splitCap"), run: () => onSplit("row") },
{ label: t("split.splitRight"), run: () => onSplit("col") },
{ label: t("split.splitDown"), run: () => onSplit("row") },
{ label: zoomed ? t("split.unzoom") : t("split.zoom"), run: onZoom },
...(viewMenu?.() ?? []),
],
@@ -3,7 +3,7 @@
// 回环要 jsdom 的 localStorage。
import { afterEach, describe, expect, it } from "vitest";
import { readSplitSlots } from "@/lib/util/prefs";
import { readSplitSlots, writeSplitSlots } from "@/lib/util/prefs";
import { assign, cloudSlotId, eject, ejectCloud, emptySlots, firstEmptyIn, prune, seed } from "./slots";
afterEach(() => localStorage.clear());
@@ -26,7 +26,7 @@ describe("分屏槽位纯逻辑", () => {
const localOnly = assign(emptySlots(), 0, "local-a");
expect(ejectCloud(localOnly)).toBe(localOnly);
const mixed = assign(assign(localOnly, 1, cloudSlotId("cloud-a")), 2, "local-b");
expect(ejectCloud(mixed)).toEqual(["local-a", null, "local-b", null, null, null]);
expect(ejectCloud(mixed)).toEqual(["local-a", null, "local-b"]);
});
it("prune 按全表剪掉被删会话;无变化保引用(不触发白重渲/白落盘)", () => {
@@ -44,6 +44,14 @@ describe("分屏槽位纯逻辑", () => {
expect(firstEmptyIn(emptySlots(), [3])).toBe(3);
});
it("assign/seed 会为高位槽按需扩容", () => {
const assigned = assign(emptySlots(), 7, "high");
expect(assigned).toHaveLength(8);
expect(assigned.slice(0, 7)).toEqual(Array.from({ length: 7 }, () => null));
expect(assigned[7]).toBe("high");
expect(seed(emptySlots(), "a", 6)[6]).toBe("a");
});
it("seed 只在全空时把当前会话播进指定首叶;有存档原样恢复,无当前会话不动", () => {
expect(seed(emptySlots(), "a", 2)[2]).toBe("a");
const kept = assign(emptySlots(), 1, "b");
@@ -54,10 +62,21 @@ describe("分屏槽位纯逻辑", () => {
});
describe("分屏 prefs 槽位档(mc.splitSlots)", () => {
it("坏档逐位兜底:非串/空串按空槽,恒定长 6(SPLIT_MAX_PANES);超长截断", () => {
localStorage.setItem("mc.splitSlots", JSON.stringify(["a", 3, "", "b", null, "c", "越界"]));
expect(readSplitSlots()).toEqual(["a", null, null, "b", null, "c"]);
it("完整读取时坏档逐位兜底且不截断有效高位槽", () => {
localStorage.setItem("mc.splitSlots", JSON.stringify(["a", 3, "", "b", null, "c", "第七格"]));
expect(readSplitSlots()).toEqual(["a", null, null, "b", null, "c", "第七格"]);
localStorage.setItem("mc.splitSlots", "not-json");
expect(readSplitSlots()).toEqual([null, null, null, null, null, null]);
expect(readSplitSlots()).toEqual([]);
});
it("按树叶读取时只恢复引用槽并压成稠密数组", () => {
localStorage.setItem("mc.splitSlots", JSON.stringify(["a", "离树", null, "d", "尾巴"]));
expect(readSplitSlots([0, 3, Number.MAX_SAFE_INTEGER])).toEqual(["a", "d", null]);
});
it("写回保留全部动态槽位", () => {
const slots = assign(emptySlots(), 8, "第九格");
writeSplitSlots(slots);
expect(readSplitSlots()).toEqual(slots);
});
});
+7 -7
View File
@@ -1,10 +1,8 @@
// 分屏槽位纯逻辑:定长 SPLIT_MAX_PANES 的 (sid | null)[]。哪些槽位可见由
// 布局树(tree.ts)的叶集决定——树上不在场的槽位留档不清空,换回带它的
// 模板即恢复;设计定案见
// 分屏槽位纯逻辑:按需增长的 (sid | null)[]。哪些槽位可见由布局树
// (tree.ts)的叶集决定;启动恢复会把树叶与槽位一并压密,运行期关闭格
// 则显式清掉内容。设计定案见
// docs/superpowers/specs/2026-08-16-desktop-split-view-design.md。
// 判定与变换全是纯函数,useSplitState 只做接线,产品语义单测钉在这里。
import { SPLIT_MAX_PANES } from "@/lib/util/prefs";
export type Slots = readonly (string | null)[];
/** 槽位条目 = 「带记号的 id」:本地任务/会话 = 裸 sid;云端任务 =
@@ -16,14 +14,16 @@ export const cloudSlotId = (taskId: string): string => CLOUD_PREFIX + taskId;
export const isCloudSlotId = (v: string): boolean => v.startsWith(CLOUD_PREFIX);
export const cloudTaskIdOf = (v: string): string => v.slice(CLOUD_PREFIX.length);
export const emptySlots = (): Slots => Array.from({ length: SPLIT_MAX_PANES }, () => null);
export const emptySlots = (): Slots => [];
/** 装载(move 语义):**同一会话禁止双格并存**——session_close 无引用
* 计数,先卸载的那个实例会把另一格的实时流掐断(壳侧 session.rs 把
* opened 置 false 是按会话不是按订阅方)。装载前先把该会话从其他槽摘掉,
* 判重收口在此单点,调用方不必各自防。 */
export function assign(slots: Slots, index: number, id: string): Slots {
return slots.map((s, i) => (i === index ? id : s === id ? null : s));
if (!Number.isSafeInteger(index) || index < 0) return slots;
const length = Math.max(slots.length, index + 1);
return Array.from({ length }, (_, i) => (i === index ? id : slots[i] === id ? null : (slots[i] ?? null)));
}
export function eject(slots: Slots, index: number): Slots {
@@ -3,9 +3,12 @@ import { describe, expect, it } from "vitest";
import {
equalizeAt,
insertRootLeaf,
leaves,
moveLeafToRoot,
paneCount,
PRESETS,
remapLeaves,
removeLeaf,
sameShape,
setRatio,
@@ -23,14 +26,51 @@ describe("布局树", () => {
expect(paneCount(PRESETS["4"])).toBe(4);
});
it("validateTree:坏方向/槽位越界/重复/超深整树作废;比例保留六格均分所需边界", () => {
it("validateTree:坏方向/非法或重复槽位整树作废;高位槽和深树可恢复", () => {
expect(validateTree(PRESETS["4"])).toEqual(PRESETS["4"]);
expect(validateTree({ dir: "diag", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 1 } })).toBeNull();
expect(validateTree({ leaf: 99 })).toBeNull();
expect(validateTree({ leaf: 99 })).toEqual({ leaf: 99 });
expect(validateTree({ leaf: Number.MAX_SAFE_INTEGER + 1 })).toBeNull();
expect(validateTree({ dir: "col", ratio: 0.5, a: { leaf: 0 }, b: { leaf: 0 } })).toBeNull();
expect(validateTree(null)).toBeNull();
const clamped = validateTree({ dir: "col", ratio: 0.01, a: { leaf: 0 }, b: { leaf: 1 } });
expect(clamped && "dir" in clamped && clamped.ratio).toBeCloseTo(1 / 6);
const ratio = validateTree({ dir: "col", ratio: 0.01, a: { leaf: 0 }, b: { leaf: 1 } });
expect(ratio && "dir" in ratio && ratio.ratio).toBeCloseTo(0.01);
let deep: SplitNode = { leaf: 7 };
for (let slot = 6; slot >= 0; slot--) deep = { dir: "col", ratio: 0.5, a: { leaf: slot }, b: deep };
expect(validateTree(deep)).toEqual(deep);
const cycle: Record<string, unknown> = { dir: "col", ratio: 0.5, a: { leaf: 0 } };
cycle.b = cycle;
expect(validateTree(cycle)).toBeNull();
});
it("恢复时可把稀疏和超大叶槽压密且不改变视觉顺序", () => {
const tree: SplitNode = {
dir: "col",
ratio: 0.4,
a: { leaf: Number.MAX_SAFE_INTEGER },
b: { leaf: 7 },
};
const remapped = remapLeaves(tree, new Map([[7, 0], [Number.MAX_SAFE_INTEGER, 1]]));
expect(remapped).toEqual({ dir: "col", ratio: 0.4, a: { leaf: 1 }, b: { leaf: 0 } });
expect(leaves(remapped)).toEqual([1, 0]);
});
it("异常深存档与树操作不耗尽调用栈", () => {
let deep: SplitNode = { leaf: 20_000 };
for (let slot = 19_999; slot >= 0; slot--) deep = { dir: "col", ratio: 0.5, a: { leaf: slot }, b: deep };
const restored = validateTree(deep);
expect(restored).not.toBeNull();
expect(paneCount(restored!)).toBe(20_001);
expect(splitLeaf(restored!, 0, "row")?.newSlot).toBe(20_001);
expect(paneCount(equalizeAt(restored!, ""))).toBe(20_001);
expect(paneCount(removeLeaf(restored!, 20_000))).toBe(20_000);
expect(paneCount(insertRootLeaf(restored!, "top").tree)).toBe(20_002);
expect(paneCount(moveLeafToRoot(restored!, 10_000, "right"))).toBe(20_001);
expect(leaves(swapLeaves(restored!, 0, 20_000)).slice(0, 2)).toEqual([20_000, 1]);
expect(sameShape(restored!, restored!)).toBe(true);
});
it("setRatio 按路径寻址:只动那个节点(拖哪条线动哪条)", () => {
@@ -58,25 +98,58 @@ describe("布局树", () => {
expect(local.ratio).toBe(0.4);
expect(local.a.ratio).toBe(0.5);
let six: SplitNode = { leaf: 5 };
for (let slot = 4; slot >= 1; slot--) six = { dir: "col", ratio: 0.5, a: { leaf: slot }, b: six };
six = { dir: "col", ratio: 0.5, a: { leaf: 0 }, b: six };
const allSix = equalizeAt(six, "");
if ("leaf" in allSix) throw new Error("形状不该变");
expect(allSix.ratio).toBeCloseTo(1 / 6);
expect(validateTree(allSix)).toEqual(allSix); // 1:5 落盘重载后不能弹回 1:4
let seven: SplitNode = { leaf: 6 };
for (let slot = 5; slot >= 1; slot--) seven = { dir: "col", ratio: 0.5, a: { leaf: slot }, b: seven };
seven = { dir: "col", ratio: 0.5, a: { leaf: 0 }, b: seven };
const allSeven = equalizeAt(seven, "");
if ("leaf" in allSeven) throw new Error("形状不该变");
expect(allSeven.ratio).toBeCloseTo(1 / 7);
expect(validateTree(allSeven)).toEqual(allSeven); // 1:6 落盘重载后比例不反弹
});
it("splitLeaf:新格取最小空槽号、原格在前;满员返回 null", () => {
it("splitLeaf:新格取最小空槽号、原格在前且可持续超过六格", () => {
const res = splitLeaf(PRESETS["2col"], 0, "row");
expect(res).not.toBeNull();
expect(leaves(res!.tree)).toEqual([0, 2, 1]); // 槽 2 是最小空号,挂在 0 之下
expect(res!.newSlot).toBe(2);
// 连拆到上限(6):再拆返回 null
let tree = PRESETS["1"];
for (let i = 0; i < 5; i++) tree = splitLeaf(tree, 0, "col")!.tree;
expect(paneCount(tree)).toBe(6);
expect(splitLeaf(tree, 0, "col")).toBeNull();
for (let i = 0; i < 7; i++) tree = splitLeaf(tree, 0, "col")!.tree;
expect(paneCount(tree)).toBe(8);
expect(leaves(tree)).toContain(7);
expect(validateTree(tree)).toEqual(tree);
});
it("根边缘插入:上方/右侧包住整棵旧树且取最小空槽", () => {
const top = insertRootLeaf(PRESETS["2col"], "top");
expect(top.newSlot).toBe(2);
expect(top.tree).toEqual({ dir: "row", ratio: 0.5, a: { leaf: 2 }, b: PRESETS["2col"] });
const right = insertRootLeaf(PRESETS["2row"], "right");
expect(right.newSlot).toBe(2);
expect(right.tree).toEqual({ dir: "col", ratio: 0.5, a: PRESETS["2row"], b: { leaf: 2 } });
});
it("已有叶搬到根边缘:原位置收拢、槽只出现一次且单格不动", () => {
const right = moveLeafToRoot(PRESETS["4"], 2, "right");
expect(leaves(right)).toEqual([0, 1, 3, 2]);
expect(paneCount(right)).toBe(4);
expect(moveLeafToRoot(right, 2, "right")).toBe(right);
expect(right).toEqual({
dir: "col",
ratio: 0.5,
a: {
dir: "col",
ratio: 0.5,
a: { leaf: 0 },
b: { dir: "row", ratio: 0.5, a: { leaf: 1 }, b: { leaf: 3 } },
},
b: { leaf: 2 },
});
const top = moveLeafToRoot(PRESETS["4"], 3, "top");
expect(leaves(top)).toEqual([3, 0, 2, 1]);
expect(moveLeafToRoot({ leaf: 0 }, 0, "right")).toEqual({ leaf: 0 });
expect(moveLeafToRoot(PRESETS["2col"], 9, "top")).toBe(PRESETS["2col"]);
});
it("removeLeaf:兄弟上位(tmux 收格);最后一格不许关", () => {
+191 -76
View File
@@ -5,9 +5,8 @@
// 翻向)到这里整体消解:共享线只在用户自己把树拆成那个形状时存在。
// 档位(1/2横/2纵/4)降级为快捷模板,只是四棵预设树。
// 全部纯函数,useSplitState 只做接线;产品语义单测钉在这里。
import { SPLIT_MAX_PANES } from "@/lib/util/prefs";
export type SplitDir = "col" | "row";
export type SplitRootEdge = "top" | "right";
export type SplitNode =
| { leaf: number }
@@ -30,8 +29,9 @@ export const PRESETS = {
export type PresetKey = keyof typeof PRESETS;
const MAX_DEPTH = 5; // 6 叶的树最深 5 层;再深必是坏档/恶意档
export const SPLIT_MIN_RATIO = 1 / SPLIT_MAX_PANES; // 1:5 是六格等面积时的合法边界
// 比例边界只保证树值合法,不与格子数量绑定;交互时按当前像素区域另加
// 可见尺寸下限,渲染时也会跳过不足一个像素的子树。
export const SPLIT_MIN_RATIO = Number.EPSILON;
export const SPLIT_MAX_RATIO = 1 - SPLIT_MIN_RATIO;
const clampRatio = (v: unknown): number =>
@@ -41,117 +41,232 @@ const clampRatio = (v: unknown): number =>
/** 叶槽位序(中序 = 视觉阅读序;可见集/焦点轮转/播种都按它)。 */
export function leaves(node: SplitNode): number[] {
return "leaf" in node ? [node.leaf] : [...leaves(node.a), ...leaves(node.b)];
const result: number[] = [];
const pending = [node];
while (pending.length > 0) {
const current = pending.pop()!;
if ("leaf" in current) result.push(current.leaf);
else pending.push(current.b, current.a);
}
return result;
}
export function paneCount(node: SplitNode): number {
return leaves(node).length;
let count = 0;
const pending = [node];
while (pending.length > 0) {
const current = pending.pop()!;
if ("leaf" in current) count += 1;
else pending.push(current.a, current.b);
}
return count;
}
/** 坏档校验(localStorage 手改/旧格式):形状/方向/深度/叶数/槽位唯一且
* 在界内,任何一条不满足整树作废(部分修复会造出没人见过的布局)。 */
/** 坏档校验(localStorage 手改/旧格式):形状/方向/槽位为非负安全整数且
* 唯一,任何一条不满足整树作废(部分修复会造出没人见过的布局)。迭代
* 后序遍历避免异常深存档在应用启动时耗尽调用栈。 */
export function validateTree(raw: unknown): SplitNode | null {
const seen = new Set<number>();
const walk = (v: unknown, depth: number): SplitNode | null => {
if (depth > MAX_DEPTH || !v || typeof v !== "object") return null;
const o = v as Record<string, unknown>;
if ("leaf" in o) {
const slot = o.leaf;
if (typeof slot !== "number" || !Number.isInteger(slot) || slot < 0 || slot >= SPLIT_MAX_PANES) return null;
if (seen.has(slot)) return null;
seen.add(slot);
return { leaf: slot };
type Pending =
| { kind: "visit"; value: unknown }
| { kind: "join"; dir: SplitDir; ratio: number };
const seenSlots = new Set<number>();
const seenObjects = new WeakSet<object>();
const pending: Pending[] = [{ kind: "visit", value: raw }];
const built: SplitNode[] = [];
while (pending.length > 0) {
const item = pending.pop()!;
if (item.kind === "join") {
const b = built.pop();
const a = built.pop();
if (!a || !b) return null;
built.push({ dir: item.dir, ratio: item.ratio, a, b });
continue;
}
if (o.dir !== "col" && o.dir !== "row") return null;
const a = walk(o.a, depth + 1);
const b = walk(o.b, depth + 1);
if (!a || !b) return null;
return { dir: o.dir, ratio: clampRatio(o.ratio), a, b };
};
const tree = walk(raw, 0);
return tree && seen.size <= SPLIT_MAX_PANES ? tree : null;
const value = item.value;
if (!value || typeof value !== "object" || seenObjects.has(value)) return null;
seenObjects.add(value);
const object = value as Record<string, unknown>;
if ("leaf" in object) {
const slot = object.leaf;
if (typeof slot !== "number" || !Number.isSafeInteger(slot) || slot < 0 || seenSlots.has(slot)) return null;
seenSlots.add(slot);
built.push({ leaf: slot });
continue;
}
if (object.dir !== "col" && object.dir !== "row") return null;
pending.push(
{ kind: "join", dir: object.dir, ratio: clampRatio(object.ratio) },
{ kind: "visit", value: object.b },
{ kind: "visit", value: object.a },
);
}
return built.length === 1 ? built[0]! : null;
}
function transformTree<T>(
root: SplitNode,
leaf: (node: Extract<SplitNode, { leaf: number }>) => T,
branch: (node: Extract<SplitNode, { dir: SplitDir }>, a: T, b: T) => T,
): T {
const pending: { node: SplitNode; expanded: boolean }[] = [{ node: root, expanded: false }];
const built: T[] = [];
while (pending.length > 0) {
const item = pending.pop()!;
if ("leaf" in item.node) {
built.push(leaf(item.node));
} else if (item.expanded) {
const b = built.pop()!;
const a = built.pop()!;
built.push(branch(item.node, a, b));
} else {
pending.push({ node: item.node, expanded: true }, { node: item.node.b, expanded: false }, { node: item.node.a, expanded: false });
}
}
return built[0]!;
}
/** 恢复存档时把稀疏/超大槽号压成稠密编号;只换叶标签,不改树形、比例
* 或视觉顺序。迭代实现保证恶意深树不会重新引入调用栈风险。 */
export function remapLeaves(node: SplitNode, remap: ReadonlyMap<number, number>): SplitNode {
return transformTree<SplitNode>(
node,
(current) => ({ leaf: remap.get(current.leaf) ?? current.leaf }),
(current, a, b) => ({ ...current, a, b }),
);
}
/** 节点寻址:根 "";子路径追加 "a"/"b"。把手按路径改比例,拖谁动谁。 */
export function setRatio(node: SplitNode, path: string, ratio: number): SplitNode {
if ("leaf" in node) return node;
if (path === "") return { ...node, ratio: clampRatio(ratio) };
const head = path[0];
return head === "a"
? { ...node, a: setRatio(node.a, path.slice(1), ratio) }
: { ...node, b: setRatio(node.b, path.slice(1), ratio) };
const ancestors: { node: Extract<SplitNode, { dir: SplitDir }>; side: "a" | "b" }[] = [];
let current = node;
let offset = 0;
while (!("leaf" in current) && offset < path.length) {
const side = path[offset] === "a" ? "a" : "b";
ancestors.push({ node: current, side });
current = current[side];
offset += 1;
}
let replacement = "leaf" in current || offset < path.length ? current : { ...current, ratio: clampRatio(ratio) };
for (let i = ancestors.length - 1; i >= 0; i--) {
const { node: parent, side } = ancestors[i]!;
replacement = side === "a" ? { ...parent, a: replacement } : { ...parent, b: replacement };
}
return replacement;
}
/** 双击某条分隔线时,只在它辖下的子树按叶数递归分配面积。比如左侧
* 有上下两格、右侧一格,根比例为 2/3:1/3,左侧内部再取 1/2:1/2;
* 于是三格等面积。路径外的布局保持不动。 */
export function equalizeAt(node: SplitNode, path: string): SplitNode {
if ("leaf" in node) return node;
if (path !== "") {
const head = path[0];
return head === "a"
? { ...node, a: equalizeAt(node.a, path.slice(1)) }
: { ...node, b: equalizeAt(node.b, path.slice(1)) };
const ancestors: { node: Extract<SplitNode, { dir: SplitDir }>; side: "a" | "b" }[] = [];
let target = node;
let offset = 0;
while (!("leaf" in target) && offset < path.length) {
const side = path[offset] === "a" ? "a" : "b";
ancestors.push({ node: target, side });
target = target[side];
offset += 1;
}
const a = equalizeAt(node.a, "");
const b = equalizeAt(node.b, "");
return { ...node, ratio: clampRatio(paneCount(a) / (paneCount(a) + paneCount(b))), a, b };
if ("leaf" in target || offset < path.length) return node;
const equalized = transformTree(
target,
(leaf) => ({ node: leaf as SplitNode, count: 1 }),
(branch, a, b) => ({
node: { ...branch, ratio: clampRatio(a.count / (a.count + b.count)), a: a.node, b: b.node } as SplitNode,
count: a.count + b.count,
}),
).node;
let replacement = equalized;
for (let i = ancestors.length - 1; i >= 0; i--) {
const { node: parent, side } = ancestors[i]!;
replacement = side === "a" ? { ...parent, a: replacement } : { ...parent, b: replacement };
}
return replacement;
}
/** 拆分某叶(向右 = col / 向下 = row):新格取未被任何叶占用的最小槽号,
* 原格在前新格在后;到叶数上限返回 null(调用方置灰按钮)。 */
* 原格在前新格在后。 */
export function splitLeaf(node: SplitNode, slot: number, dir: SplitDir): { tree: SplitNode; newSlot: number } | null {
const used = new Set(leaves(node));
let newSlot = -1;
for (let i = 0; i < SPLIT_MAX_PANES; i++) {
if (!used.has(i)) {
newSlot = i;
break;
}
}
if (newSlot < 0) return null;
const walk = (n: SplitNode): SplitNode =>
"leaf" in n
? n.leaf === slot
? { dir, ratio: 0.5, a: { leaf: slot }, b: { leaf: newSlot } }
: n
: { ...n, a: walk(n.a), b: walk(n.b) };
const tree = walk(node);
let newSlot = 0;
while (used.has(newSlot)) newSlot += 1;
const tree = transformTree<SplitNode>(
node,
(leaf) => (leaf.leaf === slot ? { dir, ratio: 0.5, a: { leaf: slot }, b: { leaf: newSlot } } : leaf),
(branch, a, b) => (a === branch.a && b === branch.b ? branch : { ...branch, a, b }),
);
return tree === node ? null : { tree, newSlot };
}
/** 从整个主视图上边缘或右边缘插入新叶。 */
export function insertRootLeaf(node: SplitNode, edge: SplitRootEdge): { tree: SplitNode; newSlot: number } {
const used = new Set(leaves(node));
let newSlot = 0;
while (used.has(newSlot)) newSlot += 1;
const leaf: SplitNode = { leaf: newSlot };
return {
newSlot,
tree:
edge === "top"
? { dir: "row", ratio: 0.5, a: leaf, b: node }
: { dir: "col", ratio: 0.5, a: node, b: leaf },
};
}
/** 把已有叶搬到整个主视图边缘;原位置由兄弟子树上位,槽内容不动。 */
export function moveLeafToRoot(node: SplitNode, slot: number, edge: SplitRootEdge): SplitNode {
if ("leaf" in node || !leaves(node).includes(slot)) return node;
if (edge === "top" && node.dir === "row" && "leaf" in node.a && node.a.leaf === slot) return node;
if (edge === "right" && node.dir === "col" && "leaf" in node.b && node.b.leaf === slot) return node;
const remaining = removeLeaf(node, slot);
const leaf: SplitNode = { leaf: slot };
return edge === "top"
? { dir: "row", ratio: 0.5, a: leaf, b: remaining }
: { dir: "col", ratio: 0.5, a: remaining, b: leaf };
}
/** 关闭某叶:兄弟子树上位(tmux 收格语义);最后一叶不许关(返回原树,
* 出口是退出分屏不是关光格子)。 */
export function removeLeaf(node: SplitNode, slot: number): SplitNode {
if ("leaf" in node) return node;
const walk = (n: SplitNode): SplitNode | null => {
if ("leaf" in n) return n.leaf === slot ? null : n;
const a = walk(n.a);
const b = walk(n.b);
if (a && b) return a === n.a && b === n.b ? n : { ...n, a, b };
return a ?? b; // 一侧整体消失:兄弟上位
};
return walk(node) ?? node;
return (
transformTree<SplitNode | null>(
node,
(leaf) => (leaf.leaf === slot ? null : leaf),
(branch, a, b) => {
if (a && b) return a === branch.a && b === branch.b ? branch : { ...branch, a, b };
return a ?? b;
},
) ?? node
);
}
/** 交换两叶的槽位(拖格头换位;两叶都得在树上,否则原样返回)。 */
export function swapLeaves(node: SplitNode, x: number, y: number): SplitNode {
const present = new Set(leaves(node));
if (x === y || !present.has(x) || !present.has(y)) return node;
const walk = (n: SplitNode): SplitNode =>
"leaf" in n
? n.leaf === x
? { leaf: y }
: n.leaf === y
? { leaf: x }
: n
: { ...n, a: walk(n.a), b: walk(n.b) };
return walk(node);
return transformTree<SplitNode>(
node,
(leaf) => (leaf.leaf === x ? { leaf: y } : leaf.leaf === y ? { leaf: x } : leaf),
(branch, a, b) => (a === branch.a && b === branch.b ? branch : { ...branch, a, b }),
);
}
/** 形状等价(忽略比例):header 档位钮的按下态按它判——用户拖过比例的
* 四格仍是"四格"。 */
export function sameShape(a: SplitNode, b: SplitNode): boolean {
if ("leaf" in a || "leaf" in b) return "leaf" in a && "leaf" in b && a.leaf === b.leaf;
return a.dir === b.dir && sameShape(a.a, b.a) && sameShape(a.b, b.b);
const pending: [SplitNode, SplitNode][] = [[a, b]];
while (pending.length > 0) {
const [left, right] = pending.pop()!;
if ("leaf" in left || "leaf" in right) {
if (!("leaf" in left && "leaf" in right && left.leaf === right.leaf)) return false;
continue;
}
if (left.dir !== right.dir) return false;
pending.push([left.a, right.a], [left.b, right.b]);
}
return true;
}
@@ -9,8 +9,11 @@ import { readSplitSlots, readSplitTreeRaw, writeSplitSlots, writeSplitTree } fro
import { assign, eject, ejectCloud, firstEmptyIn, isCloudSlotId, prune, seed, type Slots } from "./slots";
import {
equalizeAt,
insertRootLeaf,
leaves,
moveLeafToRoot,
PRESETS,
remapLeaves,
removeLeaf,
setRatio,
splitLeaf,
@@ -18,6 +21,7 @@ import {
validateTree,
type SplitDir,
type SplitNode,
type SplitRootEdge,
} from "./tree";
export interface SplitStateApi {
@@ -29,14 +33,16 @@ export interface SplitStateApi {
focused: number;
/** 实际在渲染的槽(放大 > 树叶集,阅读序);通知抑制按它算可见集。 */
visibleIndices: readonly number[];
/** 套模板(树整棵替换;树上不在场的槽位留档,换回即恢复)。 */
/** 拖分隔线:按节点路径改比例(路径见 tree.setRatio)。 */
setNodeRatio: (path: string, ratio: number) => void;
/** 双击分隔线:让该节点辖下的所有格子尽量等面积,路径外不动。 */
equalizeNode: (path: string) => void;
/** 拆分某格(向右/向下):新格取最小空槽号并夺焦;到上限静默不动
* (按钮侧按 canSplit 置灰,这里只兜底)。 */
/** 拆分某格(向右/向下):新格取最小空槽号并夺焦。 */
splitPane: (slot: number, dir: SplitDir) => number | null;
/** 在整个主视图的上/右边缘创建新格。 */
addRootPane: (edge: SplitRootEdge) => number;
/** 把已有格搬到整个主视图的上/右边缘,原位置自动收拢。 */
movePaneToRoot: (slot: number, edge: SplitRootEdge) => void;
/** 关闭某格(tmux 收格:兄弟上位):槽位内容一并清档——关格是显式
* 动作,不同于换模板的"藏而不清";最后一格不许关。 */
closePane: (slot: number) => void;
@@ -57,13 +63,37 @@ export interface SplitStateApi {
place: (id: string) => void;
}
export function useSplitState(): SplitStateApi {
const [slots, setSlots] = useState<Slots>(readSplitSlots);
function readInitialSplitState(): { tree: SplitNode; slots: Slots } {
// 首启缺省**单格**(2026-08-20 用户定案:新用户开门见两栏、右栏空面板
// 冷场;多格由拆分/「新建即新格」自然长出)。存过树的老用户不受影响
const [tree, setTree] = useState<SplitNode>(() => validateTree(readSplitTreeRaw()) ?? PRESETS["1"]);
// 冷场;多格由拆分/「新建即新格」自然长出)。恢复时只取树实际引用的
// 槽,并把异常稀疏的叶槽号压密:树形/视觉顺序不变,同时避免手改的超大
// 叶号触发稠密数组扩容、离树长尾拖慢此后的每次渲染。
const restoredTree = validateTree(readSplitTreeRaw()) ?? PRESETS["1"];
const oldSlots = leaves(restoredTree).sort((a, b) => a - b);
const restoredSlots = readSplitSlots(oldSlots);
const maxSlot = oldSlots.at(-1) ?? 0;
// 正常拆关形成的低位空洞保留编号(例如历史「第 7 格」);只有槽号相对
// 叶数异常稀疏时才压密。阈值随叶数增长,不构成 pane 数量上限。
const compact = maxSlot > oldSlots.length * 8 + 1024;
const remap = new Map(oldSlots.map((slot, index) => [slot, compact ? index : slot]));
const tree = compact ? remapLeaves(restoredTree, remap) : restoredTree;
const slots: (string | null)[] = [];
oldSlots.forEach((slot, index) => {
const target = remap.get(slot)!;
const entry = restoredSlots[index] ?? null;
if (entry) slots[target] = entry;
});
let length = slots.length;
while (length > 0 && !slots[length - 1]) length -= 1;
return { tree, slots: Array.from({ length }, (_, index) => slots[index] ?? null) };
}
export function useSplitState(): SplitStateApi {
const [initial] = useState(readInitialSplitState);
const [slots, setSlots] = useState<Slots>(initial.slots);
const [tree, setTree] = useState<SplitNode>(initial.tree);
const [zoomed, setZoomed] = useState<number | null>(null);
const [focused, setFocused] = useState(() => leaves(validateTree(readSplitTreeRaw()) ?? PRESETS["1"])[0] ?? 0);
const [focused, setFocused] = useState(() => leaves(initial.tree)[0] ?? 0);
// 持久化走 effect 不进 setState 更新器(更新器要纯;挂载首拍回写读到的
// 归一化档,幂等)
@@ -95,6 +125,21 @@ export function useSplitState(): SplitStateApi {
return res.newSlot;
}, []);
const addRootPane = useCallback((edge: SplitRootEdge): number => {
const res = insertRootLeaf(snapRef.current.tree, edge);
setTree(res.tree);
setZoomed(null);
setFocused(res.newSlot);
return res.newSlot;
}, []);
const movePaneToRoot = useCallback((slot: number, edge: SplitRootEdge) => {
const next = moveLeafToRoot(snapRef.current.tree, slot, edge);
setTree(next);
setZoomed(null);
setFocused(slot);
}, []);
const closePane = useCallback((slot: number) => {
const cur = snapRef.current;
const next = removeLeaf(cur.tree, slot);
@@ -155,7 +200,7 @@ export function useSplitState(): SplitStateApi {
if (existing >= 0 && order.includes(existing)) {
target = existing; // 已在树上(含被放大遮住的):夺焦/切独占即可
} else {
// 不在树上的留档槽视同不在场:assign 的 move 语义会把旧槽摘干净
// 不在树上的异常/旧档槽视同不在场:assign 的 move 语义会把旧槽摘干净
target = firstEmptyIn(cur.slots, order) ?? (order.includes(cur.focused) ? cur.focused : (order[0] ?? 0));
setSlots((prev) => assign(prev, target, id));
}
@@ -172,6 +217,8 @@ export function useSplitState(): SplitStateApi {
setNodeRatio,
equalizeNode,
splitPane,
addRootPane,
movePaneToRoot,
closePane,
swapPanes,
focus,
-1
View File
@@ -52,7 +52,6 @@ export const en: Record<MessageKey, string> = {
"split.swapCancel": "Cancel swap",
"split.splitRight": "Split right",
"split.splitDown": "Split down",
"split.splitCap": "Pane limit reached",
"split.close": "Close pane (task keeps running)",
"split.emptyPane": "Empty panel",
"split.dragLoad": "Drag onto a pane to load",
-1
View File
@@ -60,7 +60,6 @@ export const zh = {
"split.swapCancel": "取消换任务",
"split.splitRight": "右分屏",
"split.splitDown": "下分屏",
"split.splitCap": "格子数已达上限",
"split.close": "关闭格子(任务继续后台运行)",
"split.emptyPane": "空面板",
"split.dragLoad": "拖到格子可装载",
+9 -11
View File
@@ -52,12 +52,10 @@ export function rememberLastTaskModel(model: string): void {
* - mc.splitTree = 布局树 JSON(叶=槽位、内部节点=切分,词汇与校验的
* 权威在 features/split/tree.ts——prefs 只做原始存取,不复刻树形状;
* 2026-08-16 用户终案「让用户自定义,随便他搞」,固定档位模型退役);
* - mc.splitSlots = JSON (string|null)[](恒定长 SPLIT_MAX_PANES,树上
* 不在场的槽位留档:换模板收缩只是叶变少,切回即恢复)。
* - mc.splitSlots = JSON (string|null)[](按需增长;启动时只恢复当前树引用
* 的槽,异常稀疏编号压密;关闭格已显式清档,不保留无入口的离树长尾)。
* 分屏开关本身刻意不持久化(启动恒常规视图,对齐「启动恒落本地任务」
* 定案)。 */
export const SPLIT_MAX_PANES = 6;
export function readSplitTreeRaw(): unknown {
try {
return JSON.parse(localStorage.getItem("mc.splitTree") ?? "null");
@@ -74,22 +72,22 @@ export function writeSplitTree(tree: unknown): void {
}
}
export function readSplitSlots(): (string | null)[] {
export function readSplitSlots(indices?: readonly number[]): (string | null)[] {
try {
const parsed: unknown = JSON.parse(localStorage.getItem("mc.splitSlots") ?? "[]");
const arr = Array.isArray(parsed) ? parsed : [];
// 逐位校验:坏档(旧格式/手改)按空槽兜住,不让一个坏位拖垮整组
return Array.from({ length: SPLIT_MAX_PANES }, (_, i) =>
typeof arr[i] === "string" && arr[i] !== "" ? (arr[i] as string) : null,
);
const valid = (value: unknown) => (typeof value === "string" && value !== "" ? value : null);
// 启动恢复已知树叶时只取树实际引用的槽:旧档的离树尾巴不再让每次渲染
// 都扫描整份数组;无 indices 的纯存取调用仍逐位校验完整旧格式。
return indices ? indices.map((index) => valid(arr[index])) : arr.map(valid);
} catch {
return Array.from({ length: SPLIT_MAX_PANES }, () => null);
return [];
}
}
export function writeSplitSlots(slots: readonly (string | null)[]): void {
try {
localStorage.setItem("mc.splitSlots", JSON.stringify(slots.slice(0, SPLIT_MAX_PANES)));
localStorage.setItem("mc.splitSlots", JSON.stringify(slots));
} catch {
// 只丢持久化
}