pi-vim-tree 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +327 -2
- package/extensions/vim-tree.ts +2698 -0
- package/package.json +32 -4
|
@@ -0,0 +1,2698 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vim-tree — 给内置 `/tree` 打三块补丁,其余一律交回原生:
|
|
3
|
+
*
|
|
4
|
+
* 1. 键位(原生没有的能力):
|
|
5
|
+
* - `h` / `l`(以及 `ctrl+k` / `ctrl+j`、`shift+up` / `shift+down`):
|
|
6
|
+
* 上一个 / 下一个分支首行(循环)
|
|
7
|
+
* - `ctrl+o` / `ctrl+i`(=Tab):跳转栈后退 / 前进(vim 的 jump list)
|
|
8
|
+
* - `ctrl+h`(或 f4) :开关右栏预览
|
|
9
|
+
* - `ctrl+e` / `ctrl+y` :预览内容上下翻一行
|
|
10
|
+
* - `ctrl+f` / `ctrl+b` :列表翻整页
|
|
11
|
+
* - `u` / `d`(以及 `ctrl+u` / `ctrl+d`):列表翻半页(上 / 下)
|
|
12
|
+
* - `ctrl+l` :清掉搜索词和命中高亮
|
|
13
|
+
* - `L` / `T` :标签编辑 / 标签时间戳(只认大写,小写让给动作键)
|
|
14
|
+
* - `q` :关掉树(原生只有 esc 能关;vim 的 help/preview 窗口也是 q)
|
|
15
|
+
* - `z` 家族按 vim 折叠语义走:`zc/zo/za` 收/展/切换,`zO/zC` 整棵子树收/展,
|
|
16
|
+
* `zm/zr` 收/放一层,`zM/zR` 全收/全展,`zj/zk` 跳到下一个/上一个折痕,
|
|
17
|
+
* `zA` 递归切换(折着就整棵展开,展开就整棵收起),
|
|
18
|
+
* `zv` 展开刚好够让光标那一行露出来(vim 的 view cursor line)。
|
|
19
|
+
* 层级按 **pi 画出来的显示层级**算,而且**只折列表里画着 ⊟ 的分支点**
|
|
20
|
+
* (折了才看得到 ⊞;根节点没有标志位,所以不折)。
|
|
21
|
+
* 折起来被藏住的行由**逻辑光标行**记住:展开回去时光标原路退回(vim 的折痕记忆)。
|
|
22
|
+
* 2. 布局:列表高度固定(fzf 风格 `height: 0.6`,上限 30 行),
|
|
23
|
+
* 内容变少/折叠/过滤都只在框内变化,**整个框不伸缩、不跳**。
|
|
24
|
+
* 3. 预览:fzf `--preview-window right:55%` 风格——树在左,选中项的完整正文在右;
|
|
25
|
+
* 正文交给 pi 自己的 `Markdown` 组件 + `getMarkdownTheme()` 渲染,所以标题、列表、
|
|
26
|
+
* 引用、代码块的**语法高亮**跟消息正文一模一样(同一套主题 token、同一个 highlight.js)。
|
|
27
|
+
* 预览只滑窗(ctrl+e/y 逐行),不整框滚动;
|
|
28
|
+
* 因为列表高度固定、预览只占右半,所以开关预览不产生任何高度重排。
|
|
29
|
+
*
|
|
30
|
+
* 界面上全是英文;折叠层级(Fold x/y)和匹配计数(Match x/y)紧跟在
|
|
31
|
+
* "Session Tree" 标题后面。折叠层级用**连续编号**(像 vim 的 foldlevel):
|
|
32
|
+
* pi 的 indent 只在分叉点加级(链式节点不加),直接报 indent 会跳号(1 → 3 → 5)。
|
|
33
|
+
*
|
|
34
|
+
* 状态栏按 vim 的 showcmd 语义,分三档:
|
|
35
|
+
* - 徽标只写模式(`NORMAL` / `SEARCH`),输入回显单独用默认前景色(白)跟在徽标后面
|
|
36
|
+
* - 还在等下一个键(`11` / `g` / `z`)→ 一直显示
|
|
37
|
+
* - 命令执行完(`j` / `11G`)→ 只闪 FLASH_MS 这么一下(到期主动重绘,字不会留在屏幕上)
|
|
38
|
+
* - 没匹配上的按键 → 什么都不显示
|
|
39
|
+
* 计数和 g/z 前缀**不过期**:交互界面里不该让人猜"刚才那个数字还在不在",
|
|
40
|
+
* 一直留着直到命令真正完成(vim 的 timeoutlen 是 1 秒,这里故意不做);
|
|
41
|
+
* 只有"等待中"那串字在屏幕上最多挂 5 秒(WAIT_DISPLAY_MS),不会一直占着。
|
|
42
|
+
*
|
|
43
|
+
* 行号按 vim 的口径:**折叠不改行号**(行号按未折叠的清单算,藏起来的号留空),
|
|
44
|
+
* 所以 `G` / `{n}G` / `gg` / `%` 永远指同一行;目标被折住时先把那个折叠展开再跳过去
|
|
45
|
+
* (`g0` 跳当前会话分支也是这个规矩)。
|
|
46
|
+
*
|
|
47
|
+
* 标记 = vim 的 **mark**:`m` + 字母/数字设标记,` + 字母/数字跳过去(`` = 上次跳转之前)。
|
|
48
|
+
* 标记存在扩展里(不绑在树上),关掉 /tree 再开还在;换会话时清空。
|
|
49
|
+
*
|
|
50
|
+
* 跳转栈 = vim 的 **jump list**:只记"跳转"(gg / G / % / g0 / 分支首行 h·l / 搜索 / n/N / 标记),
|
|
51
|
+
* j/k、u/d、zj/zk 这类移动不记;`ctrl+o` 后退、`ctrl+i` 前进,新的跳转会截断"向前"的那一段。
|
|
52
|
+
* 上限 100 条(vim 的 motion.txt:jump list 最多 100 条),同一行再跳一次时旧条目会被移除。
|
|
53
|
+
* 标记名字共 62 个:a-z(26)+ A-Z(26)+ 0-9(10)。
|
|
54
|
+
* 状态栏和折叠计数同款:跳转栈显示 `Jump 当前/总数`、标记显示 `Mark a,b`,
|
|
55
|
+
* 没东西的时候整段消失(和 Fold 计数一个脾气)。`J` 清空跳转栈、`M` 清空标记
|
|
56
|
+
*(单个标记不提供删除键:`d` 让给翻页了)。
|
|
57
|
+
*
|
|
58
|
+
* 折叠记忆 = vim 的**逻辑光标行**(vim 就只有这一个,实测过):
|
|
59
|
+
* - 折叠**不改变**它;它被折痕盖住时,光标显示在它最近的可见祖先(折痕行)上
|
|
60
|
+
* - 展开回去、它重新可见时,光标自动回到它
|
|
61
|
+
* - 只有**挪光标**才会换掉它(vim:挪了就不回来)
|
|
62
|
+
* 那一行现在被几层折叠盖着,按 **parent 链**现算(跨层折叠也不会把别的分支算进来)。
|
|
63
|
+
*
|
|
64
|
+
*
|
|
65
|
+
* 搜索框保持 pi 原生行为(追加 + 退格),不做可编辑输入框。
|
|
66
|
+
*
|
|
67
|
+
* 兼容性:pi 用 dist/bundle/cli.js 启动,内置类在 dist/bundle/chunks/*.js 里。
|
|
68
|
+
* chunk 文件名每版都变(1.5.0: chunk-44DLKSKE.js → 1.5.1: chunk-ZKNSXGL5.js),
|
|
69
|
+
* 所以按文件内容定位 chunk、动态 import 后 patch 原型;按绝对路径 import 拿到的
|
|
70
|
+
* 就是运行时那一份模块实例,因此 patch 对内建 /tree 生效。
|
|
71
|
+
* 依赖私有字段(treeList / searchQuery / filteredNodes / maxVisibleLines …),
|
|
72
|
+
* 所以带自检:结构变了就安静退回原生行为,并在 /vim-tree 里报告原因。
|
|
73
|
+
*
|
|
74
|
+
* 开关:`/vim-tree on | off`(裸命令 = 状态),或启动时 PI_VIM_TREE=0。
|
|
75
|
+
* off = **完全恢复原生**:每打一个补丁都登记了一条撤销,off 时全部撤销
|
|
76
|
+
* (类原型上的 handleInput/render、树实例上的 applyFilter、搜索状态),不留残留。
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
import { Container, Input, Markdown, decodeKittyPrintable, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
80
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
81
|
+
import { homedir } from "node:os";
|
|
82
|
+
import { dirname, join } from "node:path";
|
|
83
|
+
import { pathToFileURL } from "node:url";
|
|
84
|
+
|
|
85
|
+
import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
86
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
87
|
+
|
|
88
|
+
// ---------------------------------------------------------------- 布局常量
|
|
89
|
+
|
|
90
|
+
/** 列表占“可用高度”的比例(对齐 fzf 的 `height: 0.6`) */
|
|
91
|
+
const LIST_HEIGHT_RATIO = 0.6;
|
|
92
|
+
/** 列表行数上限,别在超高终端上变成一堵墙 */
|
|
93
|
+
const LIST_MAX_ROWS = 30;
|
|
94
|
+
/** 列表以外固定占用的行数(边框×3 + 标题 + 帮助 + 搜索行 + 空行) */
|
|
95
|
+
const LIST_CHROME_ROWS = 10;
|
|
96
|
+
/** 右栏预览占整行宽度的比例(对齐 fzf `--preview-window right:50~60%`) */
|
|
97
|
+
const PREVIEW_SPLIT = 0.55;
|
|
98
|
+
const DIM = "\x1b[2m";
|
|
99
|
+
const RESET = "\x1b[22m";
|
|
100
|
+
/** 搜索行里“当前匹配行号”的反显 */
|
|
101
|
+
const REVERSE = "\x1b[7m";
|
|
102
|
+
/** 关掉反显:\x1b[22m 只关粗体/淡色,关不掉反显,必须用 \x1b[27m */
|
|
103
|
+
const REVERSE_OFF = "\x1b[27m";
|
|
104
|
+
/** 匹配行的行号用 vim 的黄色(Dracula yellow #f1fa8c → 256:228) */
|
|
105
|
+
const YELLOW = "\x1b[38;5;228m";
|
|
106
|
+
const YELLOW_BOLD = "\x1b[1;38;5;228m";
|
|
107
|
+
/** 只关前景色 + 粗体(不能用 \x1b[22m,它关不掉颜色) */
|
|
108
|
+
const FG_RESET = "\x1b[39;22m";
|
|
109
|
+
/** 状态栏徽标(Dracula:normal = 紫 #bd93f9,search = 绿 #50fa7b,深色字) */
|
|
110
|
+
const MODE_NORMAL = "\x1b[48;5;141m\x1b[38;5;235m";
|
|
111
|
+
const MODE_SEARCH = "\x1b[48;5;84m\x1b[38;5;235m";
|
|
112
|
+
const MODE_END = "\x1b[0m";
|
|
113
|
+
|
|
114
|
+
/** 构建标记:/vim-tree 会把它显示出来,用来确认 /reload 之后跑的是不是新代码 */
|
|
115
|
+
const BUILD = "2026-11-13 keys: h/l branch, u/d half page, q quit, L/T uppercase only";
|
|
116
|
+
|
|
117
|
+
const STATE = {
|
|
118
|
+
enabled: process.env.PI_VIM_TREE !== "0",
|
|
119
|
+
preview: true,
|
|
120
|
+
cls: undefined as unknown,
|
|
121
|
+
patched: false,
|
|
122
|
+
notice: "",
|
|
123
|
+
warned: false,
|
|
124
|
+
treeList: undefined as any,
|
|
125
|
+
tui: undefined as any,
|
|
126
|
+
marks: new Map<string, string>(), // vim 的标记:名字 → 行 id(跨 /tree 开关都留着)
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// ---------------------------------------------------------------- 补丁登记
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 已打补丁的撤销动作(后打的先撤)。
|
|
133
|
+
* **每打一个补丁就登记一条撤销** —— 这样 `/vim-tree off` 才能彻底回到原生,
|
|
134
|
+
* 而不是只让按键走原生、补丁还留在树上(搜索过滤、行号、布局都会残留)。
|
|
135
|
+
* 以后新增补丁也必须走这里,否则 off 就不是“完全恢复默认”。
|
|
136
|
+
*/
|
|
137
|
+
const UNDO: Array<() => void> = [];
|
|
138
|
+
|
|
139
|
+
function onDisable(undo: () => void): void {
|
|
140
|
+
UNDO.push(undo);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function revertAll(): void {
|
|
144
|
+
while (UNDO.length > 0) {
|
|
145
|
+
const undo = UNDO.pop();
|
|
146
|
+
try {
|
|
147
|
+
undo?.();
|
|
148
|
+
} catch {
|
|
149
|
+
// 一条撤销失败不牵连其它
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------- 小工具
|
|
156
|
+
|
|
157
|
+
function stripAnsi(text: string): string {
|
|
158
|
+
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 取 raw 里前 n 个可见字符(保留 ANSI 样式) */
|
|
162
|
+
function rawPrefix(raw: string, visible: number): string {
|
|
163
|
+
let count = 0;
|
|
164
|
+
let out = "";
|
|
165
|
+
for (let i = 0; i < raw.length; i++) {
|
|
166
|
+
const ch = raw[i] as string;
|
|
167
|
+
if (ch === "\x1b") {
|
|
168
|
+
const match = /^\x1b\[[0-9;]*m/.exec(raw.slice(i));
|
|
169
|
+
if (match) {
|
|
170
|
+
out += match[0];
|
|
171
|
+
i += match[0].length - 1;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
count++;
|
|
176
|
+
if (count > visible) break;
|
|
177
|
+
out += ch;
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function padTo(text: string, target: number): string {
|
|
183
|
+
const pad = target - visibleWidth(text);
|
|
184
|
+
return pad > 0 ? text + " ".repeat(pad) : text;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 固定列表行数:每次渲染按当前终端行数重算(resize 自洽),但内容多少不影响它 */
|
|
188
|
+
function fixedListRows(treeList: any): number {
|
|
189
|
+
if (treeList.__vtNativeMax === undefined) treeList.__vtNativeMax = treeList.maxVisibleLines;
|
|
190
|
+
const rows = process.stdout.rows ?? 40;
|
|
191
|
+
const target = Math.floor((rows - LIST_CHROME_ROWS) * LIST_HEIGHT_RATIO);
|
|
192
|
+
// floor(rows/2) = 原生构造时的公式,用它兜底避免顶出可用区域
|
|
193
|
+
const nativeEquivalent = Math.max(5, Math.floor(rows / 2));
|
|
194
|
+
return Math.max(5, Math.min(LIST_MAX_ROWS, nativeEquivalent, target));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* off 的时候把我们在**树实例**上动过的地方还回去。
|
|
199
|
+
* 只撤原型方法不够:maxVisibleLines 被我们改成了固定高度,
|
|
200
|
+
* 原生接手后行数就不对了 —— 那就不是"完全恢复原状"。
|
|
201
|
+
*/
|
|
202
|
+
function restoreNativeTreeState(treeList: any): void {
|
|
203
|
+
if (!treeList) return;
|
|
204
|
+
if (treeList.__vtNativeMax !== undefined) {
|
|
205
|
+
treeList.maxVisibleLines = treeList.__vtNativeMax;
|
|
206
|
+
treeList.__vtNativeMax = undefined;
|
|
207
|
+
}
|
|
208
|
+
// 过滤器 / 折叠 / 时间戳都是**原生字段**,我们动过就得还回去,
|
|
209
|
+
// 否则 off 之后原生接手的不是原样(过滤还挂着、折痕还留着)。
|
|
210
|
+
if (treeList.__vtNativeFilterMode !== undefined) {
|
|
211
|
+
treeList.filterMode = treeList.__vtNativeFilterMode;
|
|
212
|
+
treeList.__vtNativeFilterMode = undefined;
|
|
213
|
+
}
|
|
214
|
+
if (treeList.__vtNativeShowTime !== undefined) {
|
|
215
|
+
treeList.showLabelTimestamps = treeList.__vtNativeShowTime;
|
|
216
|
+
treeList.__vtNativeShowTime = undefined;
|
|
217
|
+
}
|
|
218
|
+
if (treeList.__vtNativeFolds) {
|
|
219
|
+
try {
|
|
220
|
+
treeList.foldedNodes?.clear?.();
|
|
221
|
+
for (const id of treeList.__vtNativeFolds) treeList.foldedNodes?.add?.(id);
|
|
222
|
+
} catch {
|
|
223
|
+
// 忽略
|
|
224
|
+
}
|
|
225
|
+
treeList.__vtNativeFolds = undefined;
|
|
226
|
+
}
|
|
227
|
+
treeList.__vtMode = "normal";
|
|
228
|
+
treeList.searchQuery = "";
|
|
229
|
+
try {
|
|
230
|
+
ensureInput(treeList).setValue("");
|
|
231
|
+
} catch {
|
|
232
|
+
// 输入框还没建过就算了
|
|
233
|
+
}
|
|
234
|
+
treeList.__vtUnfolded = undefined;
|
|
235
|
+
try {
|
|
236
|
+
treeList.applyFilter();
|
|
237
|
+
} catch {
|
|
238
|
+
// 树已经不在了就算了
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------------------------------------------------------------- 发现内置类
|
|
243
|
+
|
|
244
|
+
function pkgBundle(install: string, version: string): string {
|
|
245
|
+
return join(
|
|
246
|
+
install,
|
|
247
|
+
"releases",
|
|
248
|
+
version,
|
|
249
|
+
"node_modules",
|
|
250
|
+
"@earendil-works",
|
|
251
|
+
"pi-coding-agent",
|
|
252
|
+
"dist",
|
|
253
|
+
"bundle",
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function bundleCandidates(): string[] {
|
|
258
|
+
const found: string[] = [];
|
|
259
|
+
const push = (dir: string | undefined) => {
|
|
260
|
+
if (!dir) return;
|
|
261
|
+
if (!existsSync(join(dir, "chunks"))) return;
|
|
262
|
+
if (!found.includes(dir)) found.push(dir);
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
// 1) 正在运行的入口(bin/pi → dist/bundle/cli.js)
|
|
266
|
+
const entry = process.argv[1];
|
|
267
|
+
if (entry) push(dirname(entry));
|
|
268
|
+
|
|
269
|
+
// 2) managed install:current-version 指向的 release
|
|
270
|
+
const install = join(homedir(), ".pi", "agent", "install");
|
|
271
|
+
try {
|
|
272
|
+
const version = readFileSync(join(install, "current-version"), "utf8").trim();
|
|
273
|
+
if (version) push(pkgBundle(install, version));
|
|
274
|
+
} catch {
|
|
275
|
+
// 非 managed install,继续兜底
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// 3) 兜底:所有 release 目录
|
|
279
|
+
try {
|
|
280
|
+
for (const version of readdirSync(join(install, "releases"))) push(pkgBundle(install, version));
|
|
281
|
+
} catch {
|
|
282
|
+
// 忽略
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return found;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** 入口文件直接 import 的那批 chunk 优先扫描:体积小、且必然已被运行时加载过 */
|
|
289
|
+
function prioritize(bundle: string, files: string[]): string[] {
|
|
290
|
+
let referenced: string[] = [];
|
|
291
|
+
try {
|
|
292
|
+
const entry = readFileSync(join(bundle, "cli-runtime.js"), "utf8");
|
|
293
|
+
referenced = [...entry.matchAll(/\.\/chunks\/([\w-]+\.js)/g)].map((m) => m[1] as string);
|
|
294
|
+
} catch {
|
|
295
|
+
// 没有入口文件就全量扫描
|
|
296
|
+
}
|
|
297
|
+
const first = referenced.filter((f) => files.includes(f));
|
|
298
|
+
return [...first, ...files.filter((f) => !first.includes(f))];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function findTreeSelectorClass(): Promise<Function | undefined> {
|
|
302
|
+
for (const bundle of bundleCandidates()) {
|
|
303
|
+
const chunksDir = join(bundle, "chunks");
|
|
304
|
+
let files: string[];
|
|
305
|
+
try {
|
|
306
|
+
files = prioritize(
|
|
307
|
+
bundle,
|
|
308
|
+
readdirSync(chunksDir).filter((f) => f.endsWith(".js")),
|
|
309
|
+
);
|
|
310
|
+
} catch {
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
for (const file of files) {
|
|
315
|
+
const full = join(chunksDir, file);
|
|
316
|
+
try {
|
|
317
|
+
if (!readFileSync(full, "utf8").includes("TreeSelectorComponent")) continue;
|
|
318
|
+
} catch {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
try {
|
|
322
|
+
const mod = (await import(pathToFileURL(full).href)) as Record<string, unknown>;
|
|
323
|
+
const cls = mod.TreeSelectorComponent;
|
|
324
|
+
if (typeof cls === "function") {
|
|
325
|
+
STATE.notice = `chunk: ${file}`;
|
|
326
|
+
return cls as Function;
|
|
327
|
+
}
|
|
328
|
+
} catch {
|
|
329
|
+
// 单个 chunk import 失败不影响其它
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
STATE.notice = "TreeSelectorComponent not found in dist/bundle/chunks";
|
|
334
|
+
return undefined;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// ---------------------------------------------------------------- 树操作
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 所有“分支首行”的下标:根节点,以及父节点有多个可见子节点时的每个子节点。
|
|
341
|
+
*/
|
|
342
|
+
function branchHeadIndexes(treeList: any): number[] {
|
|
343
|
+
const nodes: any[] = treeList.filteredNodes ?? [];
|
|
344
|
+
const childrenMap: Map<string, string[]> | undefined = treeList.visibleChildrenMap;
|
|
345
|
+
const parentMap: Map<string, string | null> | undefined = treeList.visibleParentMap;
|
|
346
|
+
const heads: number[] = [];
|
|
347
|
+
|
|
348
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
349
|
+
const id = nodes[i]?.node?.entry?.id;
|
|
350
|
+
if (!id) continue;
|
|
351
|
+
const parent = parentMap?.get(id);
|
|
352
|
+
if (parent === null || parent === undefined) {
|
|
353
|
+
heads.push(i); // 根
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const siblings = childrenMap?.get(parent) ?? [];
|
|
357
|
+
if (siblings.length > 1) heads.push(i); // 分支点的子节点
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return heads;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 循环跳分支首行(到底回第一个,到顶回最后一个) */
|
|
364
|
+
function jumpBranchHead(treeList: any, direction: "up" | "down"): boolean {
|
|
365
|
+
const nodes: any[] = treeList.filteredNodes ?? [];
|
|
366
|
+
if (nodes.length === 0) return false;
|
|
367
|
+
|
|
368
|
+
const heads = branchHeadIndexes(treeList);
|
|
369
|
+
if (heads.length === 0) return false;
|
|
370
|
+
|
|
371
|
+
const current: number = treeList.selectedIndex ?? 0;
|
|
372
|
+
const from = currentId(treeList);
|
|
373
|
+
if (direction === "down") {
|
|
374
|
+
const next = heads.find((i) => i > current);
|
|
375
|
+
treeList.selectedIndex = next !== undefined ? next : heads[0];
|
|
376
|
+
} else {
|
|
377
|
+
let previous: number | undefined;
|
|
378
|
+
for (const index of heads) {
|
|
379
|
+
if (index < current) previous = index;
|
|
380
|
+
else break;
|
|
381
|
+
}
|
|
382
|
+
treeList.selectedIndex = previous !== undefined ? previous : heads[heads.length - 1];
|
|
383
|
+
}
|
|
384
|
+
// 分支首行跳跃 = vim 的 { } / H M L 那一类结构化跳转,进 jump list(ctrl+o 能退回来处)
|
|
385
|
+
recordJump(treeList, from, currentId(treeList));
|
|
386
|
+
return true;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
type VisualSnapshot = {
|
|
390
|
+
indent: number;
|
|
391
|
+
showConnector: boolean;
|
|
392
|
+
isLast: boolean;
|
|
393
|
+
isVirtualRootChild: boolean;
|
|
394
|
+
gutters: unknown;
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
function rememberVisuals(treeList: any): void {
|
|
398
|
+
const cache: Map<string, VisualSnapshot> = (treeList.__vtLayout ??= new Map());
|
|
399
|
+
for (const flat of treeList.filteredNodes ?? []) {
|
|
400
|
+
const id = flat?.node?.entry?.id;
|
|
401
|
+
if (!id) continue;
|
|
402
|
+
cache.set(id, {
|
|
403
|
+
indent: flat.indent,
|
|
404
|
+
showConnector: flat.showConnector,
|
|
405
|
+
isLast: flat.isLast,
|
|
406
|
+
isVirtualRootChild: flat.isVirtualRootChild,
|
|
407
|
+
gutters: flat.gutters, // recalc 会赋新数组,旧数组不会被改
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function restoreVisuals(treeList: any): void {
|
|
413
|
+
const cache: Map<string, VisualSnapshot> | undefined = treeList.__vtLayout;
|
|
414
|
+
if (!cache || cache.size === 0) return;
|
|
415
|
+
for (const flat of treeList.filteredNodes ?? []) {
|
|
416
|
+
const id = flat?.node?.entry?.id;
|
|
417
|
+
const saved = id ? cache.get(id) : undefined;
|
|
418
|
+
if (!saved) continue;
|
|
419
|
+
flat.indent = saved.indent;
|
|
420
|
+
flat.showConnector = saved.showConnector;
|
|
421
|
+
flat.isLast = saved.isLast;
|
|
422
|
+
flat.isVirtualRootChild = saved.isVirtualRootChild;
|
|
423
|
+
flat.gutters = saved.gutters;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** ctrl+i:翻转当前节点的折叠状态(真正的 toggle) */
|
|
428
|
+
function toggleFold(treeList: any): boolean {
|
|
429
|
+
const node = treeList.filteredNodes?.[treeList.selectedIndex];
|
|
430
|
+
const id = node?.node?.entry?.id;
|
|
431
|
+
if (!id) return false;
|
|
432
|
+
|
|
433
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
434
|
+
if (!folded) return false;
|
|
435
|
+
|
|
436
|
+
if (folded.has(id)) {
|
|
437
|
+
folded.delete(id);
|
|
438
|
+
} else if (canFold(treeList, id) && !isRoot(treeList, id)) {
|
|
439
|
+
folded.add(id);
|
|
440
|
+
} else {
|
|
441
|
+
return false; // 没有 ⊟ 标志,折了也看不出来
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
refreshTree(treeList);
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ---------------------------------------------------------------- 模态 + 模糊搜索
|
|
449
|
+
|
|
450
|
+
type Mode = "normal" | "search";
|
|
451
|
+
|
|
452
|
+
/** 这次输入是不是“一个普通字符”(能打进文本框的那种),用于 normal 模式吞键判定 */
|
|
453
|
+
function isPrintableKey(data: string): boolean {
|
|
454
|
+
if (!data) return false;
|
|
455
|
+
if (decodeKittyPrintable(data) !== undefined) return true; // Kitty/modifyOtherKeys 下的普通字符
|
|
456
|
+
if (data.length !== 1) return false;
|
|
457
|
+
const code = data.codePointAt(0) ?? 0;
|
|
458
|
+
if (code < 32 || code === 0x7f) return false;
|
|
459
|
+
if (code >= 0x80 && code <= 0x9f) return false;
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function modeOf(treeList: any): Mode {
|
|
464
|
+
// 每次打开 /tree 都是新的 treeList → 默认从 normal 进入
|
|
465
|
+
return ((treeList.__vtMode ??= "normal") as Mode);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
type SearchState = { query: string; matches: number[]; cursor: number };
|
|
469
|
+
|
|
470
|
+
function searchState(treeList: any): SearchState {
|
|
471
|
+
return (treeList.__vtSearch ??= { query: "", matches: [], cursor: -1 });
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** 上一次“回车确认”的搜索结果(vim 里 `n`/`N` 和常驻高亮都用它) */
|
|
475
|
+
function committedState(treeList: any): SearchState {
|
|
476
|
+
return (treeList.__vtCommitted ??= { query: "", matches: [], cursor: -1 });
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* 当前该用于高亮/跳转的搜索状态:
|
|
481
|
+
* - search 模式且已经打了字 → 增量结果(incsearch)
|
|
482
|
+
* - 否则 → 上次确认的结果
|
|
483
|
+
*/
|
|
484
|
+
function activeSearch(treeList: any): SearchState {
|
|
485
|
+
const live = searchState(treeList);
|
|
486
|
+
if (modeOf(treeList) === "search" && live.query.trim().length > 0) return live;
|
|
487
|
+
return committedState(treeList);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** search 模式回车:把增量结果落盘 */
|
|
491
|
+
function commitSearch(treeList: any): void {
|
|
492
|
+
const live = searchState(treeList);
|
|
493
|
+
const committed = committedState(treeList);
|
|
494
|
+
committed.query = live.query;
|
|
495
|
+
committed.matches = live.matches.slice();
|
|
496
|
+
committed.cursor = live.cursor;
|
|
497
|
+
recordJump(treeList, treeList.__vtSearchOriginId, currentId(treeList));
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** search 模式 esc:丢弃增量,回到上次确认的结果与进入搜索前的光标位置 */
|
|
501
|
+
function cancelSearch(treeList: any): void {
|
|
502
|
+
const committed = committedState(treeList);
|
|
503
|
+
ensureInput(treeList).setValue(committed.query ?? "");
|
|
504
|
+
treeList.searchQuery = committed.query ?? "";
|
|
505
|
+
searchState(treeList).query = committed.query ?? "";
|
|
506
|
+
treeList.__vtMode = "normal";
|
|
507
|
+
treeList.applyFilter();
|
|
508
|
+
const origin = Number(treeList.__vtSearchOrigin);
|
|
509
|
+
if (Number.isFinite(origin) && (treeList.filteredNodes?.length ?? 0) > 0) {
|
|
510
|
+
treeList.selectedIndex = Math.max(0, Math.min(origin, treeList.filteredNodes.length - 1));
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** 跨 /tree 共享的 kill ring(KillRing 未导出,只能按引用借) */
|
|
515
|
+
let SHARED_KILL_RING: any;
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* search 模式的输入缓冲区:用 pi-tui 的 Input,所以和 pi 聊天输入框完全同样的手感
|
|
519
|
+
* (ctrl+a/e/u/k/w/f/b、Home/End、退格/删除、kill ring、撤销、光标左右)。
|
|
520
|
+
* 走 Input 后原生不再处理字符输入,searchQuery 只由我们同步。
|
|
521
|
+
*/
|
|
522
|
+
function ensureInput(treeList: any): Input {
|
|
523
|
+
if (!treeList.__vtInput) {
|
|
524
|
+
const input = new Input();
|
|
525
|
+
input.prompt = "";
|
|
526
|
+
if (SHARED_KILL_RING) input.killRing = SHARED_KILL_RING;
|
|
527
|
+
else SHARED_KILL_RING = input.killRing;
|
|
528
|
+
treeList.__vtInput = input;
|
|
529
|
+
}
|
|
530
|
+
return treeList.__vtInput;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** 清空搜索输入(保留已确认的结果用于高亮) */
|
|
534
|
+
function clearSearchInput(treeList: any): void {
|
|
535
|
+
ensureInput(treeList).setValue("");
|
|
536
|
+
treeList.searchQuery = "";
|
|
537
|
+
searchState(treeList).query = "";
|
|
538
|
+
searchState(treeList).matches = [];
|
|
539
|
+
treeList.applyFilter();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 包一层 applyFilter,把原生“搜到就过滤”(行号会变、退出搜索又变回来)换成 vim 的做法:
|
|
544
|
+
* - 不过滤:所有行都留着,行号稳定
|
|
545
|
+
* - 只算“哪些行命中”,供渲染层高亮,供 ctrl+n / ctrl+p 跳转
|
|
546
|
+
* 实现上把 searchQuery 临时清空再调原生,原生只做 filterMode/折叠。
|
|
547
|
+
*/
|
|
548
|
+
function ensureSearch(treeList: any): void {
|
|
549
|
+
if (treeList.__vtSearchPatched) return;
|
|
550
|
+
const origApply = treeList.applyFilter.bind(treeList);
|
|
551
|
+
|
|
552
|
+
// 记下原生状态,off 时原样还回去
|
|
553
|
+
if (treeList.__vtNativeFilterMode === undefined) treeList.__vtNativeFilterMode = treeList.filterMode ?? "default";
|
|
554
|
+
if (treeList.__vtNativeShowTime === undefined) treeList.__vtNativeShowTime = !!treeList.showLabelTimestamps;
|
|
555
|
+
if (!treeList.__vtNativeFolds) treeList.__vtNativeFolds = [...(treeList.foldedNodes ?? [])];
|
|
556
|
+
|
|
557
|
+
treeList.applyFilter = function patchedApply(this: any) {
|
|
558
|
+
const saved = String(this.searchQuery ?? "");
|
|
559
|
+
this.searchQuery = "";
|
|
560
|
+
try {
|
|
561
|
+
origApply();
|
|
562
|
+
} finally {
|
|
563
|
+
this.searchQuery = saved;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const state = searchState(this);
|
|
567
|
+
// 查询词没变(比如只是折叠/过滤/重渲染)→ 光标必须原地不动,
|
|
568
|
+
// 否则按 n/N 时会被 applyFilter 悄悄挪到下一个命中,看起来“结果自己在变”。
|
|
569
|
+
const queryChanged = saved !== state.query;
|
|
570
|
+
const tokens = saved.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
571
|
+
if (tokens.length === 0) {
|
|
572
|
+
state.query = "";
|
|
573
|
+
state.matches = [];
|
|
574
|
+
state.cursor = -1;
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
const getText =
|
|
579
|
+
typeof this.getSearchableText === "function"
|
|
580
|
+
? (node: any) => String(this.getSearchableText(node) ?? "").toLowerCase()
|
|
581
|
+
: () => "";
|
|
582
|
+
|
|
583
|
+
const matches: number[] = [];
|
|
584
|
+
(this.filteredNodes ?? []).forEach((flat: any, index: number) => {
|
|
585
|
+
const text = getText(flat?.node);
|
|
586
|
+
if (tokens.every((token: string) => text.includes(token))) matches.push(index);
|
|
587
|
+
});
|
|
588
|
+
|
|
589
|
+
state.query = saved;
|
|
590
|
+
state.matches = matches;
|
|
591
|
+
|
|
592
|
+
if (matches.length === 0) {
|
|
593
|
+
state.cursor = -1;
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// 查询变了(incsearch):才把光标送到“当前行之后的第一个命中”
|
|
598
|
+
if (!queryChanged) {
|
|
599
|
+
state.cursor = Math.max(0, matches.indexOf(this.selectedIndex ?? 0));
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
const from = Math.max(0, Math.min(this.selectedIndex ?? 0, (this.filteredNodes?.length ?? 1) - 1));
|
|
604
|
+
let cursor = matches.findIndex((index) => index >= from);
|
|
605
|
+
if (cursor < 0) cursor = 0;
|
|
606
|
+
state.cursor = cursor;
|
|
607
|
+
this.selectedIndex = matches[cursor];
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
treeList.__vtSearchPatched = true;
|
|
611
|
+
onDisable(() => {
|
|
612
|
+
delete treeList.applyFilter; // 回到原型上的原生 applyFilter
|
|
613
|
+
treeList.__vtSearchPatched = false;
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 在当前匹配集合里前后移动(ctrl+n / ctrl+p) */
|
|
618
|
+
/**
|
|
619
|
+
* n / N:以**当前光标行**为基准找下一个/上一个匹配(vim 语义)。
|
|
620
|
+
* 不用记忆的 cursor,所以用 j/k/G 手动移动过后,n/N 仍从你所在的位置算起。
|
|
621
|
+
*/
|
|
622
|
+
function stepMatch(treeList: any, delta: number): boolean {
|
|
623
|
+
const state = activeSearch(treeList);
|
|
624
|
+
const matches = state.matches;
|
|
625
|
+
if (matches.length === 0) return false;
|
|
626
|
+
|
|
627
|
+
const current = treeList.selectedIndex ?? 0;
|
|
628
|
+
let target: number | undefined;
|
|
629
|
+
if (delta > 0) {
|
|
630
|
+
target = matches.find((index) => index > current);
|
|
631
|
+
if (target === undefined) target = matches[0];
|
|
632
|
+
} else {
|
|
633
|
+
for (const index of matches) if (index < current) target = index;
|
|
634
|
+
if (target === undefined) target = matches[matches.length - 1];
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const from = currentId(treeList);
|
|
638
|
+
const total = treeList.filteredNodes?.length ?? 0;
|
|
639
|
+
if (target == null || target >= total) return false;
|
|
640
|
+
treeList.selectedIndex = target;
|
|
641
|
+
state.cursor = matches.indexOf(target);
|
|
642
|
+
recordJump(treeList, from, currentId(treeList));
|
|
643
|
+
return true;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** 切换过滤器(gt/gl/gu/ga/gd) */
|
|
647
|
+
function setFilter(treeList: any, mode: string): void {
|
|
648
|
+
treeList.filterMode = mode;
|
|
649
|
+
treeList.__vtLogical = undefined; // 过滤换了,逻辑行不再作数
|
|
650
|
+
treeList.__vtFoldTarget = undefined; // 同理,折走的那一行也不再作数
|
|
651
|
+
// 上次确认的匹配是**过滤前**的行号,换了过滤就作废(否则 n/N 会跳到越界或错误的行)
|
|
652
|
+
treeList.__vtCommitted = undefined;
|
|
653
|
+
treeList.__vtUnfolded = undefined;
|
|
654
|
+
try {
|
|
655
|
+
treeList.foldedNodes?.clear?.();
|
|
656
|
+
} catch {
|
|
657
|
+
// 忽略
|
|
658
|
+
}
|
|
659
|
+
treeList.applyFilter();
|
|
660
|
+
treeList.__vtCount = 0;
|
|
661
|
+
treeList.__vtPendingG = 0;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** 翻屏:factor=1 整页、0.5 半页;vim 的 ctrl+f/b、ctrl+u/d */
|
|
665
|
+
function scrollLines(treeList: any, factor: number): boolean {
|
|
666
|
+
const total = treeList.filteredNodes?.length ?? 0;
|
|
667
|
+
if (total === 0) return false;
|
|
668
|
+
const page = fixedListRows(treeList); // 列表的固定高度(maxVisibleLines 会随光标变)
|
|
669
|
+
const step = Math.max(1, Math.round(page * Math.abs(factor)));
|
|
670
|
+
const next = (treeList.selectedIndex ?? 0) + (factor < 0 ? -step : step);
|
|
671
|
+
treeList.selectedIndex = Math.max(0, Math.min(total - 1, next));
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** ctrl+l:清掉搜索词和命中高亮(vim 里 ctrl+l 是清屏,这里对应"清搜索") */
|
|
676
|
+
function clearSearchResults(treeList: any): void {
|
|
677
|
+
clearSearchInput(treeList);
|
|
678
|
+
const committed = committedState(treeList);
|
|
679
|
+
committed.query = "";
|
|
680
|
+
committed.matches = [];
|
|
681
|
+
committed.cursor = -1;
|
|
682
|
+
treeList.applyFilter();
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** ctrl+l:打开标签编辑(等价于原生 app.tree.editLabel) */
|
|
686
|
+
function openLabelEditor(treeList: any): boolean {
|
|
687
|
+
const flat = treeList.filteredNodes?.[treeList.selectedIndex];
|
|
688
|
+
const id = flat?.node?.entry?.id;
|
|
689
|
+
if (!id || typeof treeList.onLabelEdit !== "function") return false;
|
|
690
|
+
treeList.onLabelEdit(id, flat.node.label);
|
|
691
|
+
return true;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** 渲染层:把命中词染绿(当前匹配加粗绿)。在原始 ANSI 字符串上按“可见字符”定位插入 */
|
|
695
|
+
function highlightTokens(rawLine: string, tokens: string[], isCurrent: boolean): string {
|
|
696
|
+
if (tokens.length === 0) return rawLine;
|
|
697
|
+
|
|
698
|
+
// 1) 拆成 [可见字符, 原始片段],保留原有转义
|
|
699
|
+
const pieces: Array<{ char: string; raw: string }> = [];
|
|
700
|
+
let ansi = "";
|
|
701
|
+
let i = 0;
|
|
702
|
+
while (i < rawLine.length) {
|
|
703
|
+
const code = rawLine.charCodeAt(i);
|
|
704
|
+
if (code === 0x1b) {
|
|
705
|
+
const match = /^\x1b\[[0-9;]*[A-Za-z]/.exec(rawLine.slice(i));
|
|
706
|
+
if (match) {
|
|
707
|
+
ansi += match[0];
|
|
708
|
+
i += match[0].length;
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
pieces.push({ char: rawLine[i] as string, raw: ansi + rawLine[i] });
|
|
713
|
+
ansi = "";
|
|
714
|
+
i += 1;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const plain = pieces.map((p) => p.char).join("").toLowerCase();
|
|
718
|
+
const ranges: Array<[number, number]> = [];
|
|
719
|
+
for (const token of tokens) {
|
|
720
|
+
if (!token) continue;
|
|
721
|
+
let from = 0;
|
|
722
|
+
for (;;) {
|
|
723
|
+
const at = plain.indexOf(token, from);
|
|
724
|
+
if (at < 0) break;
|
|
725
|
+
ranges.push([at, at + token.length]);
|
|
726
|
+
from = at + token.length;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (ranges.length === 0) return rawLine;
|
|
730
|
+
|
|
731
|
+
ranges.sort((a, b) => a[0] - b[0]);
|
|
732
|
+
const open = isCurrent ? "\x1b[1;32m" : "\x1b[32m";
|
|
733
|
+
const close = "\x1b[39;22m";
|
|
734
|
+
|
|
735
|
+
let out = "";
|
|
736
|
+
let active = false;
|
|
737
|
+
for (let index = 0; index < pieces.length; index++) {
|
|
738
|
+
const starting = ranges.some(([from]) => from === index);
|
|
739
|
+
const ending = ranges.some(([, to]) => to === index);
|
|
740
|
+
if (ending && active) {
|
|
741
|
+
out += close;
|
|
742
|
+
active = false;
|
|
743
|
+
}
|
|
744
|
+
if (starting && !active) {
|
|
745
|
+
out += open;
|
|
746
|
+
active = true;
|
|
747
|
+
}
|
|
748
|
+
out += pieces[index].raw;
|
|
749
|
+
}
|
|
750
|
+
if (active) out += close;
|
|
751
|
+
return out;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
type Unfolded = { ids: string[]; numbers: Map<string, number> };
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* 未折叠时的行清单 —— **vim 的行号基准**。
|
|
759
|
+
* 折叠只是把行藏起来,行号不变(vim 里折叠区的行号保持原样),
|
|
760
|
+
* 所以“第 N 行”永远指同一行;目标被折住时,把它展开就行。
|
|
761
|
+
*/
|
|
762
|
+
function unfolded(treeList: any): Unfolded {
|
|
763
|
+
const flat = treeList.flatNodes ?? [];
|
|
764
|
+
const cached = treeList.__vtUnfolded as Unfolded | undefined;
|
|
765
|
+
// 结构指纹:换了树结构就重算(搜索/折叠不影响这份"未折叠清单")
|
|
766
|
+
if (cached && treeList.__vtUnfoldRef === flat && treeList.__vtUnfoldLen === flat.length) return cached;
|
|
767
|
+
|
|
768
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
769
|
+
const saved = folded ? [...folded] : [];
|
|
770
|
+
const selected = treeList.selectedIndex;
|
|
771
|
+
const lastId = treeList.lastSelectedId;
|
|
772
|
+
|
|
773
|
+
// 临时全展开一次,把“没折时”的行清单抓出来
|
|
774
|
+
rememberVisuals(treeList);
|
|
775
|
+
if (folded) folded.clear();
|
|
776
|
+
treeList.applyFilter();
|
|
777
|
+
const ids = (treeList.filteredNodes ?? [])
|
|
778
|
+
.map((flat: any) => flat?.node?.entry?.id)
|
|
779
|
+
.filter((id: unknown): id is string => typeof id === "string");
|
|
780
|
+
if (folded) {
|
|
781
|
+
folded.clear();
|
|
782
|
+
for (const id of saved) folded.add(id);
|
|
783
|
+
}
|
|
784
|
+
treeList.applyFilter();
|
|
785
|
+
treeList.selectedIndex = selected;
|
|
786
|
+
treeList.lastSelectedId = lastId;
|
|
787
|
+
restoreVisuals(treeList);
|
|
788
|
+
|
|
789
|
+
const numbers = new Map<string, number>();
|
|
790
|
+
ids.forEach((id, index) => numbers.set(id, index + 1));
|
|
791
|
+
const value: Unfolded = { ids, numbers };
|
|
792
|
+
treeList.__vtUnfolded = value;
|
|
793
|
+
treeList.__vtUnfoldRef = flat;
|
|
794
|
+
treeList.__vtUnfoldLen = flat.length;
|
|
795
|
+
return value;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/** 可见行对应的“未折叠行号”(vim 的行号,折叠也不变) */
|
|
799
|
+
function rowNumber(treeList: any, visibleIndex: number): number {
|
|
800
|
+
const id = treeList.filteredNodes?.[visibleIndex]?.node?.entry?.id;
|
|
801
|
+
if (!id) return visibleIndex + 1;
|
|
802
|
+
return unfolded(treeList).numbers.get(id) ?? visibleIndex + 1;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* 让目标行露出来:把它上面的折叠全部展开,再定位过去。
|
|
807
|
+
* (vim 里 `G` 跳到被折起来的那行,会自动把那个折叠打开。)
|
|
808
|
+
*/
|
|
809
|
+
function revealNode(treeList: any, id: string): boolean {
|
|
810
|
+
const parentOf = parentMap(treeList);
|
|
811
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
812
|
+
let changed = false;
|
|
813
|
+
for (let cur = parentOf.get(id) ?? null; cur != null; cur = parentOf.get(cur) ?? null) {
|
|
814
|
+
if (folded?.has(cur)) {
|
|
815
|
+
folded.delete(cur);
|
|
816
|
+
changed = true;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
if (changed) refreshTree(treeList);
|
|
820
|
+
|
|
821
|
+
const index = visibleIndex(treeList, id);
|
|
822
|
+
if (index < 0) return false;
|
|
823
|
+
treeList.selectedIndex = index;
|
|
824
|
+
treeList.lastSelectedId = id;
|
|
825
|
+
// 逻辑行改成这一行(跳转属于"挪光标")
|
|
826
|
+
treeList.__vtLogical = id;
|
|
827
|
+
return true;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* g0:跳到当前会话的分支(活动叶子 = treeList.currentLeafId)。
|
|
832
|
+
* 原生 TreeList 有 findNearestVisibleIndex,被折叠/过滤时会自动退到最近的可见祖先。
|
|
833
|
+
*/
|
|
834
|
+
function jumpToActiveBranch(treeList: any): void {
|
|
835
|
+
const leaf = treeList.currentLeafId;
|
|
836
|
+
if (leaf == null) return;
|
|
837
|
+
const from = currentId(treeList);
|
|
838
|
+
if (revealNode(treeList, leaf)) recordJump(treeList, from, leaf);
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// ---------------------------------------------------------------- 跳转栈(vim 的 jump list)
|
|
842
|
+
|
|
843
|
+
/** vim 的 jump list 上限固定 100 条(见 vim 的 motion.txt:"The maximum number of entries is fixed at 100") */
|
|
844
|
+
const MAX_JUMPS = 100;
|
|
845
|
+
|
|
846
|
+
/** 当前光标所在行的 id(拿不到就退而求其次:原生记的 lastSelectedId / 逻辑行) */
|
|
847
|
+
function currentId(treeList: any): string | undefined {
|
|
848
|
+
return (
|
|
849
|
+
treeList.filteredNodes?.[treeList.selectedIndex ?? 0]?.node?.entry?.id ??
|
|
850
|
+
treeList.lastSelectedId ??
|
|
851
|
+
(treeList.__vtLogical as string | undefined)
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* 记一跳(vim 的 jump list)。
|
|
857
|
+
* 只记"跳转"(gg / G / % / g0 / 分支首行 h·l / 搜索 / 标记),j/k、u/d、zj/zk 这类移动不记 —— 和 vim 一样。
|
|
858
|
+
*
|
|
859
|
+
* 关键:**跳之前的位置也要压进栈**。只压目标行的话,
|
|
860
|
+
* "跳去一个之前也去过的行"(比如 gg 回首行)会把来处覆盖掉,ctrl+o 就退不回去。
|
|
861
|
+
* 新的跳转会截断"向前"的那一段(浏览器前进/后退同款)。
|
|
862
|
+
*/
|
|
863
|
+
function recordJump(treeList: any, fromId: string | undefined, toId: string | undefined): void {
|
|
864
|
+
if (!toId) return;
|
|
865
|
+
const jumps: string[] = (treeList.__vtJumps ??= []);
|
|
866
|
+
const index: number = treeList.__vtJumpIndex ?? -1;
|
|
867
|
+
const last = jumps.length > 0 ? jumps[jumps.length - 1] : undefined;
|
|
868
|
+
|
|
869
|
+
if (fromId === toId && last === toId) return; // 原地不动
|
|
870
|
+
|
|
871
|
+
// 新的跳转会截断"向前"的那一段
|
|
872
|
+
if (index < jumps.length - 1) jumps.length = index + 1;
|
|
873
|
+
|
|
874
|
+
// vim:同一行再跳一次时,旧的条目会被移除(ctrl+o 只会退到那里一次)
|
|
875
|
+
const pushUnique = (id: string) => {
|
|
876
|
+
for (let i = jumps.length - 1; i >= 0; i--) if (jumps[i] === id) jumps.splice(i, 1);
|
|
877
|
+
jumps.push(id);
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
// 先记来处(和栈顶一样就不重复记)
|
|
881
|
+
if (fromId && fromId !== toId && fromId !== last) pushUnique(fromId);
|
|
882
|
+
// 再记去处
|
|
883
|
+
pushUnique(toId);
|
|
884
|
+
|
|
885
|
+
// 超过 100 条就丢最老的
|
|
886
|
+
while (jumps.length > MAX_JUMPS) jumps.shift();
|
|
887
|
+
|
|
888
|
+
treeList.__vtJumpIndex = jumps.length - 1;
|
|
889
|
+
treeList.__vtPrevBack = true; // 新的跳转之后,下一次 `` 从"退"开始
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** ctrl+o / ctrl+i:在跳转栈里后退 / 前进(vim) */
|
|
893
|
+
function stepJump(treeList: any, delta: number): boolean {
|
|
894
|
+
const jumps: string[] = treeList.__vtJumps ?? [];
|
|
895
|
+
const index: number = treeList.__vtJumpIndex ?? -1;
|
|
896
|
+
const next = index + delta;
|
|
897
|
+
if (next < 0 || next >= jumps.length) return false;
|
|
898
|
+
treeList.__vtJumpIndex = next;
|
|
899
|
+
revealNode(treeList, jumps[next] as string);
|
|
900
|
+
return true;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** 跳到标记所在的那一行(折住了就展开它) */
|
|
904
|
+
function jumpToMark(treeList: any, id: string): boolean {
|
|
905
|
+
const from = currentId(treeList);
|
|
906
|
+
if (!revealNode(treeList, id)) return false;
|
|
907
|
+
recordJump(treeList, from, id);
|
|
908
|
+
return true;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* ``:上一次跳转之前的位置(vim 的 previous context)。
|
|
913
|
+
* **来回切**:退过去之后再按一次就弹回来,再按又退过去(跟 ctrl+o / ctrl+i 一个方向逻辑)。
|
|
914
|
+
*/
|
|
915
|
+
function jumpPreviousContext(treeList: any): boolean {
|
|
916
|
+
const jumps: string[] = treeList.__vtJumps ?? [];
|
|
917
|
+
const index: number = treeList.__vtJumpIndex ?? -1;
|
|
918
|
+
// 上一次是"退",这次就"进";中间没有跳转就一直退到底
|
|
919
|
+
const back = treeList.__vtPrevBack !== false;
|
|
920
|
+
const next = back ? index - 1 : index + 1;
|
|
921
|
+
if (next < 0 || next >= jumps.length) return false;
|
|
922
|
+
treeList.__vtPrevBack = !back;
|
|
923
|
+
treeList.__vtJumpIndex = next;
|
|
924
|
+
revealNode(treeList, jumps[next] as string);
|
|
925
|
+
return true;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** g 是 leader */
|
|
929
|
+
/** vim 风格定位:gg / G / {n}G / {n}gg(行号按未折叠的清单算,目标折住了就展开它) */
|
|
930
|
+
function gotoRow(treeList: any, row: number): void {
|
|
931
|
+
const { ids } = unfolded(treeList);
|
|
932
|
+
if (ids.length === 0) return;
|
|
933
|
+
const index = Math.max(0, Math.min(ids.length - 1, row - 1));
|
|
934
|
+
const from = currentId(treeList);
|
|
935
|
+
const to = ids[index] as string;
|
|
936
|
+
if (revealNode(treeList, to)) recordJump(treeList, from, to);
|
|
937
|
+
treeList.__vtCount = 0;
|
|
938
|
+
treeList.__vtPendingG = 0;
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// ---------------------------------------------------------------- 预览
|
|
942
|
+
|
|
943
|
+
/** 纯文本换行(没有 markdown 可用时的退路;也可能是 pi 已经染好色的单行摘要) */
|
|
944
|
+
function wrapPlain(text: string, width: number): string[] {
|
|
945
|
+
const lines: string[] = [];
|
|
946
|
+
if (!text) return lines;
|
|
947
|
+
for (const rawLine of text.split("\n")) {
|
|
948
|
+
const line = rawLine.trimEnd();
|
|
949
|
+
lines.push(...(line ? wrapTextWithAnsi(line, width) : [""]));
|
|
950
|
+
}
|
|
951
|
+
return lines;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/**
|
|
955
|
+
* 预览走 pi 自己的 Markdown 渲染器:主题、代码块语法高亮(highlight.js)都跟消息正文一模一样。
|
|
956
|
+
* 每个 treeList 只留一个实例,选中项变了才 setText,宽度变化由组件内部重排。
|
|
957
|
+
* 主题没初始化(裸 node 之类)时返回 undefined,由调用方退回纯文本。
|
|
958
|
+
*/
|
|
959
|
+
function renderMarkdown(
|
|
960
|
+
treeList: any,
|
|
961
|
+
node: any,
|
|
962
|
+
text: string,
|
|
963
|
+
width: number,
|
|
964
|
+
): { lines: string[]; total: number; plain: boolean } | undefined {
|
|
965
|
+
const holder = (treeList.__vtMd ??= { failed: false, key: undefined, md: undefined });
|
|
966
|
+
if (holder.failed) return undefined;
|
|
967
|
+
if (!holder.md) {
|
|
968
|
+
try {
|
|
969
|
+
holder.md = new Markdown("", 0, 0, getMarkdownTheme());
|
|
970
|
+
} catch {
|
|
971
|
+
holder.failed = true;
|
|
972
|
+
return undefined;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
const key = `${node?.entry?.id ?? ""}:${text.length}`;
|
|
976
|
+
if (holder.key !== key) {
|
|
977
|
+
holder.md.setText(text);
|
|
978
|
+
holder.key = key;
|
|
979
|
+
}
|
|
980
|
+
const lines: string[] = holder.md.render(Math.max(1, width));
|
|
981
|
+
return { lines, total: lines.length, plain: false };
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/**
|
|
985
|
+
* 选中项的完整内容;返回总行数便于翻页。
|
|
986
|
+
* `plain=true` 表示内容已经是带 ANSI 的纯文本(此时才值得再染搜索词)。
|
|
987
|
+
*/
|
|
988
|
+
function wrapPreview(treeList: any, width: number): { lines: string[]; total: number; plain: boolean } {
|
|
989
|
+
const node = treeList.filteredNodes?.[treeList.selectedIndex]?.node;
|
|
990
|
+
if (!node) return { lines: [], total: 0, plain: true };
|
|
991
|
+
|
|
992
|
+
// 1) 正文(markdown 原文)→ 交给 pi 的 Markdown 渲染
|
|
993
|
+
let raw = "";
|
|
994
|
+
try {
|
|
995
|
+
if (typeof treeList.getEntryCopyText === "function") raw = String(treeList.getEntryCopyText(node) ?? "");
|
|
996
|
+
} catch {
|
|
997
|
+
raw = "";
|
|
998
|
+
}
|
|
999
|
+
raw = raw.replace(/\r/g, "").trim();
|
|
1000
|
+
if (raw) {
|
|
1001
|
+
const rendered = renderMarkdown(treeList, node, raw, width);
|
|
1002
|
+
if (rendered) return rendered;
|
|
1003
|
+
const lines = wrapPlain(raw, width);
|
|
1004
|
+
return { lines, total: lines.length, plain: true };
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// 2) 没有正文 → 退回原生的一行摘要(已经带 ANSI,不再二次渲染)
|
|
1008
|
+
let text = "";
|
|
1009
|
+
try {
|
|
1010
|
+
if (typeof treeList.getEntryDisplayText === "function") {
|
|
1011
|
+
text = String(treeList.getEntryDisplayText(node, false) ?? "");
|
|
1012
|
+
}
|
|
1013
|
+
} catch {
|
|
1014
|
+
text = "";
|
|
1015
|
+
}
|
|
1016
|
+
const lines = wrapPlain(text.replace(/\r/g, "").trim(), width);
|
|
1017
|
+
return { lines, total: lines.length, plain: true };
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/** 预览翻页状态:选中项变化时归零,偏移在渲染时按内容长度夹紧 */
|
|
1021
|
+
function previewState(treeList: any, entryId: string | undefined): { id: string | undefined; offset: number } {
|
|
1022
|
+
const state = (treeList.__vtPreview ??= { id: undefined, offset: 0 });
|
|
1023
|
+
if (state.id !== entryId) {
|
|
1024
|
+
state.id = entryId;
|
|
1025
|
+
state.offset = 0;
|
|
1026
|
+
}
|
|
1027
|
+
return state;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
// ---------------------------------------------------------------- 折叠(vim z 家族)
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* 当前可见行的**显示层级**(pi 自己画的 flat.indent):
|
|
1035
|
+
* 只有“分支点”(父级有多个孩子)才往下加一级,链式节点跟父级同层。
|
|
1036
|
+
* 折叠层级必须用它 —— 这样列表里看到的缩进、⊟/⊞ 标志和 zm/zr 的行为才对得上。
|
|
1037
|
+
*/
|
|
1038
|
+
function visibleLevels(treeList: any): Map<string, number> {
|
|
1039
|
+
const levels = new Map<string, number>();
|
|
1040
|
+
for (const flat of treeList.filteredNodes ?? []) {
|
|
1041
|
+
const id = flat?.node?.entry?.id;
|
|
1042
|
+
if (!id) continue;
|
|
1043
|
+
levels.set(id, Number(flat?.indent ?? 0));
|
|
1044
|
+
}
|
|
1045
|
+
return levels;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/** 每个节点的**真实**孩子数(visibleChildrenMap 只装当前可见的孩子,折起来就是空的) */
|
|
1049
|
+
function childCounts(treeList: any): Map<string, number> {
|
|
1050
|
+
const flat = treeList.flatNodes ?? [];
|
|
1051
|
+
const cached = treeList.__vtChildCounts as Map<string, number> | undefined;
|
|
1052
|
+
// 结构指纹:pi 换新数组或加节点都会变(引用或长度),变了就重算
|
|
1053
|
+
if (cached && treeList.__vtChildRef === flat && treeList.__vtChildLen === flat.length) return cached;
|
|
1054
|
+
|
|
1055
|
+
const counts = new Map<string, number>();
|
|
1056
|
+
for (const node of flat) {
|
|
1057
|
+
const parentId = node?.node?.entry?.parentId;
|
|
1058
|
+
if (parentId == null) continue;
|
|
1059
|
+
counts.set(parentId, (counts.get(parentId) ?? 0) + 1);
|
|
1060
|
+
}
|
|
1061
|
+
treeList.__vtChildCounts = counts;
|
|
1062
|
+
treeList.__vtChildRef = flat;
|
|
1063
|
+
treeList.__vtChildLen = flat.length;
|
|
1064
|
+
return counts;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/** 每个节点的父 id */
|
|
1068
|
+
function parentMap(treeList: any): Map<string, string | null> {
|
|
1069
|
+
const flat = treeList.flatNodes ?? [];
|
|
1070
|
+
const cached = treeList.__vtParents as Map<string, string | null> | undefined;
|
|
1071
|
+
if (cached && treeList.__vtParentRef === flat && treeList.__vtParentLen === flat.length) return cached;
|
|
1072
|
+
|
|
1073
|
+
const parents = new Map<string, string | null>();
|
|
1074
|
+
for (const node of flat) {
|
|
1075
|
+
const entry = node?.node?.entry;
|
|
1076
|
+
if (!entry?.id) continue;
|
|
1077
|
+
parents.set(entry.id, entry.parentId ?? null);
|
|
1078
|
+
}
|
|
1079
|
+
treeList.__vtParents = parents;
|
|
1080
|
+
treeList.__vtParentRef = flat;
|
|
1081
|
+
treeList.__vtParentLen = flat.length;
|
|
1082
|
+
return parents;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* 结构上的“分支点”:有孩子,且(自己是根 或 父级有多个孩子)。
|
|
1087
|
+
* 这正是 pi 会画 ⊟ 标志的那批节点 —— 只有它们折了才看得见标志。
|
|
1088
|
+
*/
|
|
1089
|
+
function isBranchNode(treeList: any, id: string): boolean {
|
|
1090
|
+
const counts = childCounts(treeList);
|
|
1091
|
+
if ((counts.get(id) ?? 0) === 0) return false;
|
|
1092
|
+
const parentId = parentMap(treeList).get(id) ?? null;
|
|
1093
|
+
if (parentId == null) return true;
|
|
1094
|
+
return (counts.get(parentId) ?? 0) > 1;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/**
|
|
1098
|
+
* 能不能折:**跟 pi 画的那个标志同口径**(原生 isFoldable)。
|
|
1099
|
+
* 不能只看“有孩子”:父级不是分支点的节点画的是 ─,折了也看不见 ⊞,
|
|
1100
|
+
* 结果就是折了却毫无反馈(这正是“折叠指令异常”的一半来源)。
|
|
1101
|
+
*/
|
|
1102
|
+
function canFold(treeList: any, id: string | undefined): boolean {
|
|
1103
|
+
if (!id) return false;
|
|
1104
|
+
if (typeof treeList.isFoldable === "function") {
|
|
1105
|
+
try {
|
|
1106
|
+
return Boolean(treeList.isFoldable(id));
|
|
1107
|
+
} catch {
|
|
1108
|
+
// 原生结构变了 → 退回结构判定
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
return isBranchNode(treeList, id);
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/** 根节点:pi 不给它画折叠标志(没有缩进就没有 ⊟/⊞),折了也看不出来 */
|
|
1115
|
+
function isRoot(treeList: any, id: string): boolean {
|
|
1116
|
+
return (parentMap(treeList).get(id) ?? null) === null;
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* 当前可以折的节点 = **列表里画着 ⊟ 的那些**(分支点,排除根)。
|
|
1121
|
+
* 只折这批,折完才看得到 ⊞;折别的等于白折。
|
|
1122
|
+
*/
|
|
1123
|
+
function foldTargets(treeList: any): string[] {
|
|
1124
|
+
const ids: string[] = [];
|
|
1125
|
+
for (const flat of treeList.filteredNodes ?? []) {
|
|
1126
|
+
const id = flat?.node?.entry?.id;
|
|
1127
|
+
if (!id) continue;
|
|
1128
|
+
if (isRoot(treeList, id)) continue;
|
|
1129
|
+
if (!canFold(treeList, id)) continue;
|
|
1130
|
+
ids.push(id);
|
|
1131
|
+
}
|
|
1132
|
+
return ids;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/** 重算可见树(折前记住视觉信息,折后放回 → 列表不重排、不跳) */
|
|
1136
|
+
function refreshTree(treeList: any): void {
|
|
1137
|
+
rememberVisuals(treeList);
|
|
1138
|
+
treeList.applyFilter();
|
|
1139
|
+
restoreVisuals(treeList);
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// ---- 光标跟节点走(vim:折起来记住位置,展开再回到原处) ----
|
|
1143
|
+
|
|
1144
|
+
/** 当前选中的 entry id */
|
|
1145
|
+
function selectedId(treeList: any): string | undefined {
|
|
1146
|
+
return treeList.filteredNodes?.[treeList.selectedIndex]?.node?.entry?.id;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/** id 在可见列表里的下标(-1 = 不可见) */
|
|
1150
|
+
function visibleIndex(treeList: any, id: string | undefined): number {
|
|
1151
|
+
if (!id) return -1;
|
|
1152
|
+
const nodes = treeList.filteredNodes ?? [];
|
|
1153
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
1154
|
+
if (nodes[i]?.node?.entry?.id === id) return i;
|
|
1155
|
+
}
|
|
1156
|
+
return -1;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
/** id 的最近可见祖先(节点被折进去时,光标停在折痕那一行) */
|
|
1160
|
+
function visibleAncestor(treeList: any, id: string): string | undefined {
|
|
1161
|
+
const parentOf = parentMap(treeList);
|
|
1162
|
+
for (let cur = parentOf.get(id) ?? null; cur != null; cur = parentOf.get(cur) ?? null) {
|
|
1163
|
+
if (visibleIndex(treeList, cur) >= 0) return cur;
|
|
1164
|
+
}
|
|
1165
|
+
return undefined;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/**
|
|
1169
|
+
* 逻辑光标行 —— **vim 就只有这一个**(实测:折叠从不改变它,挪光标才会换它)。
|
|
1170
|
+
* 折叠把这一行藏起来时,光标显示在它最近的可见祖先(折痕行)上;
|
|
1171
|
+
* 展开回去、这一行重新可见时,光标自动回到它。
|
|
1172
|
+
*/
|
|
1173
|
+
function logicalRow(treeList: any): string | undefined {
|
|
1174
|
+
return treeList.__vtLogical as string | undefined;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** 这一行现在被哪些折叠盖着(顺着 parent 链现算,不用存) */
|
|
1178
|
+
function chainFolds(treeList: any, row?: string): Set<string> {
|
|
1179
|
+
const target = row ?? logicalRow(treeList);
|
|
1180
|
+
if (!target) return new Set<string>();
|
|
1181
|
+
|
|
1182
|
+
const out = new Set<string>();
|
|
1183
|
+
const parentOf = parentMap(treeList);
|
|
1184
|
+
const folded = treeList.foldedNodes as Set<string> | undefined;
|
|
1185
|
+
for (let cur = parentOf.get(target) ?? null; cur != null; cur = parentOf.get(cur) ?? null) {
|
|
1186
|
+
if (folded?.has(cur)) out.add(cur);
|
|
1187
|
+
}
|
|
1188
|
+
return out;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/**
|
|
1192
|
+
* 所有折叠操作都走这里:**光标跟节点,不跟行号**。
|
|
1193
|
+
* 折叠后行号整体平移,按行号保存 = 光标落到别的节点上(vim 里不会这样)。
|
|
1194
|
+
* 折起来 → 记住当前行;展开 → 光标切回折起来前的那一行。
|
|
1195
|
+
* 光标被用户挪开过就不切回(vim 只在光标还停在那个折痕上时才回原位)。
|
|
1196
|
+
*/
|
|
1197
|
+
function withCursorKept(treeList: any, mutate: () => void): void {
|
|
1198
|
+
mutate();
|
|
1199
|
+
treeList.__vtFoldOp = true; // 折叠不改逻辑行(vim 语义)
|
|
1200
|
+
|
|
1201
|
+
// 逻辑行可见 → 光标回到它;还藏着 → 吸附到它最近的可见祖先(折痕行)
|
|
1202
|
+
const logical = logicalRow(treeList);
|
|
1203
|
+
if (!logical) return;
|
|
1204
|
+
|
|
1205
|
+
const at = visibleIndex(treeList, logical);
|
|
1206
|
+
if (at >= 0) {
|
|
1207
|
+
treeList.selectedIndex = at;
|
|
1208
|
+
treeList.lastSelectedId = logical;
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// 藏起来了 → 记住它。zv 要能回到这一行,**光标后来挪到别处也不作废**
|
|
1213
|
+
//(逻辑行会被普通移动换掉,但"折走的那一行"是另一回事)。
|
|
1214
|
+
treeList.__vtFoldTarget = logical;
|
|
1215
|
+
|
|
1216
|
+
const ancestor = visibleAncestor(treeList, logical);
|
|
1217
|
+
const ancIndex = visibleIndex(treeList, ancestor);
|
|
1218
|
+
if (ancIndex >= 0) {
|
|
1219
|
+
treeList.selectedIndex = ancIndex;
|
|
1220
|
+
treeList.lastSelectedId = ancestor;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** 收起一层:同一显示层级上的"分支点"全部折起来(已经折的不动) */
|
|
1225
|
+
function closeLevel(treeList: any, level: number): boolean {
|
|
1226
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1227
|
+
if (!folded) return false;
|
|
1228
|
+
|
|
1229
|
+
const levels = visibleLevels(treeList);
|
|
1230
|
+
let changed = false;
|
|
1231
|
+
for (const id of foldTargets(treeList)) {
|
|
1232
|
+
if ((levels.get(id) ?? 0) !== level) continue;
|
|
1233
|
+
if (!folded.has(id)) {
|
|
1234
|
+
folded.add(id);
|
|
1235
|
+
changed = true;
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
if (!changed) return false;
|
|
1239
|
+
|
|
1240
|
+
refreshTree(treeList);
|
|
1241
|
+
return true;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** 展开一层:同一显示层级上折起来的节点全部展开 */
|
|
1245
|
+
function openLevel(treeList: any, level: number): boolean {
|
|
1246
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1247
|
+
if (!folded) return false;
|
|
1248
|
+
|
|
1249
|
+
const levels = visibleLevels(treeList);
|
|
1250
|
+
let changed = false;
|
|
1251
|
+
for (const id of [...folded]) {
|
|
1252
|
+
if (!levels.has(id)) continue; // 被上层折进去的,不算这一层
|
|
1253
|
+
if ((levels.get(id) ?? 0) !== level) continue;
|
|
1254
|
+
if (folded.delete(id)) changed = true;
|
|
1255
|
+
}
|
|
1256
|
+
if (!changed) return false;
|
|
1257
|
+
|
|
1258
|
+
refreshTree(treeList);
|
|
1259
|
+
return true;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/** 折根:整棵树是一条链(没有任何 ⊟ 可折)时的兜底,否则 zm/zM 什么也不发生 */
|
|
1263
|
+
function foldRoot(treeList: any): boolean {
|
|
1264
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1265
|
+
if (!folded) return false;
|
|
1266
|
+
|
|
1267
|
+
// 别处还有分支点 → 不折根(根没有标志位,折了也看不见)
|
|
1268
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1269
|
+
const id = flat?.node?.entry?.id;
|
|
1270
|
+
if (!id || isRoot(treeList, id)) continue;
|
|
1271
|
+
if (isBranchNode(treeList, id)) return false;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1275
|
+
const id = flat?.node?.entry?.id;
|
|
1276
|
+
if (!id || !isRoot(treeList, id)) continue;
|
|
1277
|
+
if (!canFold(treeList, id) || folded.has(id)) return false;
|
|
1278
|
+
folded.add(id);
|
|
1279
|
+
refreshTree(treeList);
|
|
1280
|
+
return true;
|
|
1281
|
+
}
|
|
1282
|
+
return false;
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
/** zm:再收一层(折起当前看得见的、最深那一层的分支点) */
|
|
1286
|
+
function closeOneMoreLevel(treeList: any): boolean {
|
|
1287
|
+
const levels = visibleLevels(treeList);
|
|
1288
|
+
let deepest = -Infinity;
|
|
1289
|
+
for (const id of foldTargets(treeList)) {
|
|
1290
|
+
deepest = Math.max(deepest, levels.get(id) ?? 0);
|
|
1291
|
+
}
|
|
1292
|
+
if (!Number.isFinite(deepest)) return foldRoot(treeList);
|
|
1293
|
+
return closeLevel(treeList, deepest);
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/** zr:再放一层(展开已折起来的最浅那一层) */
|
|
1297
|
+
function openOneLevel(treeList: any): boolean {
|
|
1298
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1299
|
+
if (!folded || folded.size === 0) return false;
|
|
1300
|
+
|
|
1301
|
+
const levels = visibleLevels(treeList);
|
|
1302
|
+
let shallowest = Infinity;
|
|
1303
|
+
for (const id of folded) {
|
|
1304
|
+
if (!levels.has(id)) continue;
|
|
1305
|
+
shallowest = Math.min(shallowest, levels.get(id) ?? 0);
|
|
1306
|
+
}
|
|
1307
|
+
if (!Number.isFinite(shallowest)) return false;
|
|
1308
|
+
return openLevel(treeList, shallowest);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
/** zM:全折(只剩顶层 + 折痕行) */
|
|
1312
|
+
function closeAllFolds(treeList: any): boolean {
|
|
1313
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1314
|
+
if (!folded) return false;
|
|
1315
|
+
|
|
1316
|
+
rememberVisuals(treeList);
|
|
1317
|
+
folded.clear();
|
|
1318
|
+
let branches = 0;
|
|
1319
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1320
|
+
const id = flat?.node?.entry?.id;
|
|
1321
|
+
if (!id) continue;
|
|
1322
|
+
if (!isBranchNode(treeList, id)) continue; // 只有分支点才折(列表里才看得到 ⊞)
|
|
1323
|
+
if (!isRoot(treeList, id)) branches++;
|
|
1324
|
+
folded.add(id);
|
|
1325
|
+
}
|
|
1326
|
+
// 根没标志,折了看不见 → 根不折;折完只剩根的话,等于没折
|
|
1327
|
+
if (branches > 0) {
|
|
1328
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1329
|
+
const id = flat?.node?.entry?.id;
|
|
1330
|
+
if (id && isRoot(treeList, id)) folded.delete(id);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
treeList.applyFilter();
|
|
1334
|
+
|
|
1335
|
+
// 兜底:折叠绝不能把列表清空
|
|
1336
|
+
if ((treeList.filteredNodes?.length ?? 0) === 0) {
|
|
1337
|
+
folded.clear();
|
|
1338
|
+
treeList.applyFilter();
|
|
1339
|
+
}
|
|
1340
|
+
restoreVisuals(treeList);
|
|
1341
|
+
return true;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/** zR:全展开 */
|
|
1345
|
+
function openAllFolds(treeList: any): boolean {
|
|
1346
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1347
|
+
if (!folded || folded.size === 0) return false;
|
|
1348
|
+
|
|
1349
|
+
rememberVisuals(treeList);
|
|
1350
|
+
folded.clear();
|
|
1351
|
+
treeList.applyFilter();
|
|
1352
|
+
restoreVisuals(treeList);
|
|
1353
|
+
return true;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
/** zC / zO:光标节点的整棵子树 */
|
|
1357
|
+
function subtreeIds(treeList: any, rootId: string): string[] {
|
|
1358
|
+
const childrenOf = new Map<string, string[]>();
|
|
1359
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1360
|
+
const entry = flat?.node?.entry;
|
|
1361
|
+
const parentId = entry?.parentId ?? null;
|
|
1362
|
+
if (!entry?.id || parentId == null) continue;
|
|
1363
|
+
const list = childrenOf.get(parentId) ?? [];
|
|
1364
|
+
list.push(entry.id);
|
|
1365
|
+
childrenOf.set(parentId, list);
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
const out: string[] = [];
|
|
1369
|
+
const seen = new Set<string>();
|
|
1370
|
+
const stack = [rootId];
|
|
1371
|
+
while (stack.length > 0) {
|
|
1372
|
+
const id = stack.pop() as string;
|
|
1373
|
+
if (seen.has(id)) continue;
|
|
1374
|
+
seen.add(id);
|
|
1375
|
+
out.push(id);
|
|
1376
|
+
for (const child of childrenOf.get(id) ?? []) stack.push(child);
|
|
1377
|
+
}
|
|
1378
|
+
return out;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/** zC:光标下面全折起来 */
|
|
1382
|
+
function closeUnderCursor(treeList: any): boolean {
|
|
1383
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1384
|
+
if (!folded) return false;
|
|
1385
|
+
|
|
1386
|
+
const id = selectedId(treeList);
|
|
1387
|
+
if (!id) return false;
|
|
1388
|
+
|
|
1389
|
+
let changed = false;
|
|
1390
|
+
for (const nodeId of subtreeIds(treeList, id)) {
|
|
1391
|
+
if (!isBranchNode(treeList, nodeId)) continue; // 只有分支点才折
|
|
1392
|
+
if (isRoot(treeList, nodeId)) continue; // 根没有标志,折了看不见
|
|
1393
|
+
if (!folded.has(nodeId)) {
|
|
1394
|
+
folded.add(nodeId);
|
|
1395
|
+
changed = true;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
if (!changed) return false;
|
|
1399
|
+
|
|
1400
|
+
refreshTree(treeList);
|
|
1401
|
+
return true;
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
/** zO:光标下面全展开 */
|
|
1405
|
+
function openUnderCursor(treeList: any): boolean {
|
|
1406
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1407
|
+
if (!folded) return false;
|
|
1408
|
+
|
|
1409
|
+
const id = selectedId(treeList);
|
|
1410
|
+
if (!id) return false;
|
|
1411
|
+
|
|
1412
|
+
let changed = false;
|
|
1413
|
+
for (const nodeId of subtreeIds(treeList, id)) {
|
|
1414
|
+
if (folded.delete(nodeId)) changed = true;
|
|
1415
|
+
}
|
|
1416
|
+
if (!changed) return false;
|
|
1417
|
+
|
|
1418
|
+
refreshTree(treeList);
|
|
1419
|
+
return true;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** zc / zo / za:对当前节点收起 / 展开 / 切换 */
|
|
1423
|
+
function setFoldAtCursor(treeList: any, mode: "fold" | "unfold" | "toggle"): boolean {
|
|
1424
|
+
const node = treeList.filteredNodes?.[treeList.selectedIndex];
|
|
1425
|
+
const id = node?.node?.entry?.id;
|
|
1426
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1427
|
+
if (!id || !folded) return false;
|
|
1428
|
+
|
|
1429
|
+
if (mode === "toggle") return toggleFold(treeList);
|
|
1430
|
+
|
|
1431
|
+
const isFolded = folded.has(id);
|
|
1432
|
+
const wantFold = mode === "fold";
|
|
1433
|
+
if (isFolded === wantFold) return false; // 已经是这个状态
|
|
1434
|
+
if (wantFold && (!canFold(treeList, id) || isRoot(treeList, id))) return false;
|
|
1435
|
+
|
|
1436
|
+
if (wantFold) folded.add(id);
|
|
1437
|
+
else folded.delete(id);
|
|
1438
|
+
refreshTree(treeList);
|
|
1439
|
+
return true;
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/** zj / zk:跳到下一个 / 上一个“可折叠(或已折叠)”的节点 */
|
|
1443
|
+
function jumpFold(treeList: any, delta: number): boolean {
|
|
1444
|
+
const total: number = treeList.filteredNodes?.length ?? 0;
|
|
1445
|
+
if (total === 0) return false;
|
|
1446
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1447
|
+
|
|
1448
|
+
for (let index = (treeList.selectedIndex ?? 0) + delta; index >= 0 && index < total; index += delta) {
|
|
1449
|
+
const id = treeList.filteredNodes[index]?.node?.entry?.id;
|
|
1450
|
+
if (!id) continue;
|
|
1451
|
+
if (folded?.has(id) || (canFold(treeList, id) && !isRoot(treeList, id))) {
|
|
1452
|
+
treeList.selectedIndex = index;
|
|
1453
|
+
return true;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
return false;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
/**
|
|
1460
|
+
* 所有"分支点"(能折的节点)所在的**不同层级**,从浅到深。
|
|
1461
|
+
* pi 的 indent 只在分叉点加级(链式节点不加),所以这些层级可能不连续(1、3、5…)。
|
|
1462
|
+
*/
|
|
1463
|
+
function branchLevels(treeList: any): number[] {
|
|
1464
|
+
const levels = new Set<number>();
|
|
1465
|
+
for (const flat of treeList.flatNodes ?? []) {
|
|
1466
|
+
const id = flat?.node?.entry?.id;
|
|
1467
|
+
if (!id) continue;
|
|
1468
|
+
if (isRoot(treeList, id)) continue; // 根没有折叠标志,不算一层
|
|
1469
|
+
if (!isBranchNode(treeList, id)) continue;
|
|
1470
|
+
levels.add(Number(flat?.indent ?? 0));
|
|
1471
|
+
}
|
|
1472
|
+
return [...levels].sort((a, b) => a - b);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
* 折叠计数:`Fold x/y`
|
|
1477
|
+
* x = 当前处在第几层折叠,y = 一共有几层。
|
|
1478
|
+
* 用**连续编号**(像 vim 的 foldlevel),而不是 pi 的原始 indent ——
|
|
1479
|
+
* 因为链式节点不加级,直接报 indent 会跳号(1 → 3 → 5),看不出"开了一层"。
|
|
1480
|
+
*/
|
|
1481
|
+
/**
|
|
1482
|
+
* zA:递归切换光标下的折痕(vim)。
|
|
1483
|
+
* 折着 → 整棵展开;展开着 → 整棵收起(子树里所有能折的都折上)。
|
|
1484
|
+
*/
|
|
1485
|
+
function toggleFoldRecursive(treeList: any): boolean {
|
|
1486
|
+
const node = treeList.filteredNodes?.[treeList.selectedIndex];
|
|
1487
|
+
const id = node?.node?.entry?.id;
|
|
1488
|
+
if (!id) return false;
|
|
1489
|
+
|
|
1490
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1491
|
+
if (!folded) return false;
|
|
1492
|
+
|
|
1493
|
+
const ids = subtreeIds(treeList, id);
|
|
1494
|
+
const isOpen = ids.every((x) => !folded.has(x)); // 这一支现在没折 → 收;否则 → 开
|
|
1495
|
+
|
|
1496
|
+
let changed = false;
|
|
1497
|
+
if (isOpen) {
|
|
1498
|
+
for (const x of ids) {
|
|
1499
|
+
if (x === id && !canFold(treeList, x)) continue; // 光标自己折不了就跳过
|
|
1500
|
+
if (isRoot(treeList, x)) continue; // 根没有折叠标志
|
|
1501
|
+
if (!canFold(treeList, x)) continue;
|
|
1502
|
+
if (!folded.has(x)) {
|
|
1503
|
+
folded.add(x);
|
|
1504
|
+
changed = true;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
} else {
|
|
1508
|
+
for (const x of ids) {
|
|
1509
|
+
if (folded.delete(x)) changed = true;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
if (!changed) return false;
|
|
1513
|
+
|
|
1514
|
+
refreshTree(treeList);
|
|
1515
|
+
return true;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* zv:view cursor line(vim)—— 展开刚好够让光标所在的那一行露出来。
|
|
1520
|
+
* 我们这边光标必须落在可见行上,所以"光标所在的那一行"= 逻辑行(可能被折痕盖住的那行);
|
|
1521
|
+
* 展开藏住它的那些折叠,光标就回到那一行。
|
|
1522
|
+
*/
|
|
1523
|
+
function viewCursorLine(treeList: any): boolean {
|
|
1524
|
+
// 优先用"被折走的那一行":光标挪动不该把它作废(逻辑行会被普通移动换掉)
|
|
1525
|
+
const logical = (treeList.__vtFoldTarget as string | undefined) ?? logicalRow(treeList);
|
|
1526
|
+
if (!logical) return false;
|
|
1527
|
+
if (visibleIndex(treeList, logical) >= 0) return false; // 已经看得见了
|
|
1528
|
+
|
|
1529
|
+
const folded = treeList.foldedNodes as Set<string> | undefined;
|
|
1530
|
+
let changed = false;
|
|
1531
|
+
for (const id of chainFolds(treeList, logical)) {
|
|
1532
|
+
if (folded?.delete(id)) changed = true;
|
|
1533
|
+
}
|
|
1534
|
+
if (!changed) return false;
|
|
1535
|
+
|
|
1536
|
+
refreshTree(treeList);
|
|
1537
|
+
const at = visibleIndex(treeList, logical);
|
|
1538
|
+
if (at >= 0) {
|
|
1539
|
+
treeList.selectedIndex = at;
|
|
1540
|
+
treeList.lastSelectedId = logical;
|
|
1541
|
+
}
|
|
1542
|
+
return true;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
function foldCounter(treeList: any): string {
|
|
1546
|
+
const folded: Set<string> | undefined = treeList.foldedNodes;
|
|
1547
|
+
if (!folded || folded.size === 0) return "";
|
|
1548
|
+
|
|
1549
|
+
const levels = visibleLevels(treeList);
|
|
1550
|
+
let closed = Infinity;
|
|
1551
|
+
for (const id of folded) {
|
|
1552
|
+
if (!levels.has(id)) continue;
|
|
1553
|
+
closed = Math.min(closed, levels.get(id) ?? 0);
|
|
1554
|
+
}
|
|
1555
|
+
if (!Number.isFinite(closed)) return "";
|
|
1556
|
+
|
|
1557
|
+
const all = branchLevels(treeList);
|
|
1558
|
+
const index = all.indexOf(closed);
|
|
1559
|
+
if (index < 0) return "";
|
|
1560
|
+
|
|
1561
|
+
return `Fold ${index + 1}/${all.length}`;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
/** 跳转栈计数:`Jump 当前/总数`(vim 的 :jumps 里那列 jump 数字) */
|
|
1565
|
+
function jumpCounter(treeList: any): string {
|
|
1566
|
+
const jumps: string[] = treeList.__vtJumps ?? [];
|
|
1567
|
+
if (jumps.length === 0) return "";
|
|
1568
|
+
const index = Number(treeList.__vtJumpIndex ?? -1);
|
|
1569
|
+
return `Jump ${index + 1}/${jumps.length}`;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/** 标记计数:已设的标记名(像 vim 的 :marks,但只占标题一行) */
|
|
1573
|
+
function markCounter(): string {
|
|
1574
|
+
if (STATE.marks.size === 0) return "";
|
|
1575
|
+
const names = [...STATE.marks.keys()].sort().join(",");
|
|
1576
|
+
return names.length <= 10 ? `Mark ${names}` : `Mark ${names.slice(0, 10)}…`;
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
/** 匹配计数:`匹配 当前序号/总数` */
|
|
1580
|
+
function matchCounter(treeList: any): string {
|
|
1581
|
+
const state = activeSearch(treeList);
|
|
1582
|
+
if (state.matches.length === 0) return "";
|
|
1583
|
+
const current = state.matches.indexOf(treeList.selectedIndex ?? -1);
|
|
1584
|
+
return `Match ${current >= 0 ? current + 1 : 0}/${state.matches.length}`;
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
/**
|
|
1588
|
+
* 原生固定文案的定制(这些字符串本身是 pi 写死的,但我们改的是输出行):
|
|
1589
|
+
* - `Type to search:` → `/`
|
|
1590
|
+
* - 原生帮助行 → 我们的键位提示(行数保持不变,避免高度漂移)
|
|
1591
|
+
* - 标题行右侧 → 搜索匹配计数 `[2/17]`
|
|
1592
|
+
*/
|
|
1593
|
+
function customizeChrome(treeList: any, out: string[], width: number): void {
|
|
1594
|
+
const plain = (line: string) => stripAnsi(line);
|
|
1595
|
+
let searchIdx = -1;
|
|
1596
|
+
let titleIdx = -1;
|
|
1597
|
+
for (let i = 0; i < out.length; i++) {
|
|
1598
|
+
const text = plain(String(out[i] ?? ""));
|
|
1599
|
+
if (searchIdx < 0 && text.includes("Type to search")) searchIdx = i;
|
|
1600
|
+
if (titleIdx < 0 && text.includes("Session Tree")) titleIdx = i;
|
|
1601
|
+
}
|
|
1602
|
+
if (searchIdx < 0) return;
|
|
1603
|
+
|
|
1604
|
+
// 最前面:模式徽标(vim 状态栏配色,Dracula:normal 紫 / search 绿),后面跟查询词与匹配行号
|
|
1605
|
+
const inSearch = modeOf(treeList) === "search";
|
|
1606
|
+
const state = activeSearch(treeList);
|
|
1607
|
+
const badgeText = ` ${modeBadge(treeList)} `;
|
|
1608
|
+
const badge = `${inSearch ? MODE_SEARCH : MODE_NORMAL}${badgeText}${MODE_END}`;
|
|
1609
|
+
|
|
1610
|
+
// 状态行只放徽标(+ search 模式的输入框);「匹配行」清单已经整块挪到下一行(见 layoutScreen)
|
|
1611
|
+
let body = "";
|
|
1612
|
+
if (inSearch) {
|
|
1613
|
+
const input = ensureInput(treeList);
|
|
1614
|
+
input.prompt = "";
|
|
1615
|
+
input.focused = true;
|
|
1616
|
+
body = String(input.render(Math.max(8, width - visibleWidth(badge) - 2))[0] ?? "");
|
|
1617
|
+
} else {
|
|
1618
|
+
// normal 模式:输入回显用默认前景色(白),跟查找模式的输入框一个样式
|
|
1619
|
+
const flash = Boolean(treeList.__vtEchoFlash);
|
|
1620
|
+
const at = Number(treeList.__vtEchoAt ?? 0);
|
|
1621
|
+
const alive = !flash || (at > 0 && Date.now() - at < FLASH_MS);
|
|
1622
|
+
body = alive ? String(treeList.__vtEcho ?? "") : "";
|
|
1623
|
+
}
|
|
1624
|
+
// 状态行只放徽标(+ 回显 / 搜索框);计数器挪到标题后面
|
|
1625
|
+
out[searchIdx] = truncateToWidth(`${badge}${body}`, width, "");
|
|
1626
|
+
|
|
1627
|
+
// 标题行右侧:折叠层级 + 匹配计数(跟在 "Session Tree" 标题后面)
|
|
1628
|
+
if (titleIdx >= 0) {
|
|
1629
|
+
const counters = [foldCounter(treeList), matchCounter(treeList), jumpCounter(treeList), markCounter()]
|
|
1630
|
+
.filter(Boolean)
|
|
1631
|
+
.join(" · ");
|
|
1632
|
+
if (counters) {
|
|
1633
|
+
// 原生把标题补满了一整行空白 → 先截掉,再把计数器紧接在标题后面
|
|
1634
|
+
const raw = String(out[titleIdx] ?? "");
|
|
1635
|
+
const textLen = visibleWidth(plain(raw).trimEnd());
|
|
1636
|
+
const prefix = rawPrefix(raw, textLen);
|
|
1637
|
+
const used = textLen + 2 + visibleWidth(counters);
|
|
1638
|
+
const pad = Math.max(0, width - used);
|
|
1639
|
+
out[titleIdx] = truncateToWidth(`${prefix} ${DIM}${counters}${RESET}${" ".repeat(pad)}`, width, "");
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
// 帮助行:title 与 搜索行 之间的那几行(英文,沿用原生 tree 的叫法:
|
|
1644
|
+
// move / page / branch / filters / label / label time)。
|
|
1645
|
+
// 原生这段会自己折行,所以我们也折行后逐行填回去,行数保持不变(高度不漂)。
|
|
1646
|
+
if (titleIdx >= 0 && searchIdx > titleIdx + 1) {
|
|
1647
|
+
// 按重要性排序:放不下时从尾部丢(原生给几行就用几行,绝不加高)
|
|
1648
|
+
const items = [
|
|
1649
|
+
"j/k move",
|
|
1650
|
+
"u/d half page",
|
|
1651
|
+
"ctrl+f/b page",
|
|
1652
|
+
"ctrl+l clear search",
|
|
1653
|
+
"ctrl+o/i jump back/fwd",
|
|
1654
|
+
"zc/zo/za/zO/zC/zA folds",
|
|
1655
|
+
"zm/zr fold level",
|
|
1656
|
+
"zj/zk jump fold",
|
|
1657
|
+
"zv view cursor line",
|
|
1658
|
+
"zM/zR all folds",
|
|
1659
|
+
"n/N/p match jump",
|
|
1660
|
+
"m/` marks",
|
|
1661
|
+
"J clear jumps · M clear marks",
|
|
1662
|
+
"h/l branch · g0 current",
|
|
1663
|
+
"ctrl+j/k branch",
|
|
1664
|
+
"gt/gl/gu/ga/gd filters",
|
|
1665
|
+
"ctrl+h ctrl+e/y preview",
|
|
1666
|
+
"L label",
|
|
1667
|
+
"T label time",
|
|
1668
|
+
"/ search",
|
|
1669
|
+
"enter select",
|
|
1670
|
+
"q quit",
|
|
1671
|
+
];
|
|
1672
|
+
const slots = searchIdx - titleIdx - 1;
|
|
1673
|
+
const layout = (separator: string) => {
|
|
1674
|
+
const lines: string[] = [];
|
|
1675
|
+
let current = "";
|
|
1676
|
+
for (const item of items) {
|
|
1677
|
+
const candidate = current ? `${current}${separator}${item}` : item;
|
|
1678
|
+
if (visibleWidth(candidate) + 2 <= width) current = candidate;
|
|
1679
|
+
else {
|
|
1680
|
+
if (current) lines.push(current);
|
|
1681
|
+
current = item;
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
if (current) lines.push(current);
|
|
1685
|
+
return lines;
|
|
1686
|
+
};
|
|
1687
|
+
// 先试好看的 “ · ”,放不下就换成空格;行数必须 ≤ 原生给的行数(否则高度会漂)
|
|
1688
|
+
let lines = layout(" · ");
|
|
1689
|
+
if (lines.length > slots) lines = layout(" ");
|
|
1690
|
+
if (lines.length > slots) lines = lines.slice(0, slots);
|
|
1691
|
+
for (let i = 0; i < slots; i++) {
|
|
1692
|
+
out[titleIdx + 1 + i] = lines[i] !== undefined ? truncateToWidth(`${DIM} ${lines[i]}${RESET}`, width, "") : "";
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
// ---------------------------------------------------------------- 自检 / 提示
|
|
1699
|
+
|
|
1700
|
+
function warnOnce(message: string): void {
|
|
1701
|
+
STATE.notice = message;
|
|
1702
|
+
if (STATE.warned) return;
|
|
1703
|
+
STATE.warned = true;
|
|
1704
|
+
console.error(`[vim-tree] ${message}`);
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
// ---------------------------------------------------------------- 匹配行块
|
|
1708
|
+
|
|
1709
|
+
const MAX_MATCH_BLOCK = 2;
|
|
1710
|
+
|
|
1711
|
+
/**
|
|
1712
|
+
* 把匹配行号压成“区间 token”:连续 3 个及以上显示成 `a-b`,当前匹配单独反显
|
|
1713
|
+
* (当前在区间两端时直接并进区间)。width 是该 token 的可见宽度(不含 ANSI)。
|
|
1714
|
+
*/
|
|
1715
|
+
function matchLineTokens(
|
|
1716
|
+
matches: number[],
|
|
1717
|
+
current: number,
|
|
1718
|
+
numberOf: (index: number) => number,
|
|
1719
|
+
): Array<{ text: string; width: number }> {
|
|
1720
|
+
const plain = (n: number) => String(numberOf(n));
|
|
1721
|
+
const tokens: Array<{ text: string; width: number }> = [];
|
|
1722
|
+
const reversed = (n: number) => ({
|
|
1723
|
+
text: `${REVERSE}${plain(n)}${REVERSE_OFF}${DIM}`,
|
|
1724
|
+
width: plain(n).length,
|
|
1725
|
+
});
|
|
1726
|
+
|
|
1727
|
+
let runStart = 0;
|
|
1728
|
+
for (let i = 1; i <= matches.length; i++) {
|
|
1729
|
+
const continues = i < matches.length && matches[i] === (matches[i - 1] as number) + 1;
|
|
1730
|
+
if (continues) continue;
|
|
1731
|
+
|
|
1732
|
+
const run = matches.slice(runStart, i);
|
|
1733
|
+
runStart = i;
|
|
1734
|
+
const first = run[0] as number;
|
|
1735
|
+
const last = run[run.length - 1] as number;
|
|
1736
|
+
|
|
1737
|
+
if (run.length <= 2) {
|
|
1738
|
+
for (const index of run) tokens.push(index === current ? reversed(index) : { text: plain(index), width: plain(index).length });
|
|
1739
|
+
continue;
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
const emitRange = (from: number, to: number) => {
|
|
1743
|
+
if (from > to) return;
|
|
1744
|
+
const text = from === to ? plain(from) : `${plain(from)}-${plain(to)}`;
|
|
1745
|
+
tokens.push({ text, width: text.length });
|
|
1746
|
+
};
|
|
1747
|
+
|
|
1748
|
+
if (current === first && current === last) {
|
|
1749
|
+
tokens.push(reversed(current));
|
|
1750
|
+
} else if (current === first) {
|
|
1751
|
+
const text = `${REVERSE}${plain(current)}${REVERSE_OFF}${DIM}-${plain(last)}`;
|
|
1752
|
+
tokens.push({ text, width: plain(current).length + 1 + plain(last).length });
|
|
1753
|
+
} else if (current === last) {
|
|
1754
|
+
const text = `${plain(first)}-${REVERSE}${plain(current)}${REVERSE_OFF}${DIM}`;
|
|
1755
|
+
tokens.push({ text, width: plain(first).length + 1 + plain(current).length });
|
|
1756
|
+
} else if (current > first && current < last) {
|
|
1757
|
+
emitRange(first, current - 1);
|
|
1758
|
+
tokens.push(reversed(current));
|
|
1759
|
+
emitRange(current + 1, last);
|
|
1760
|
+
} else {
|
|
1761
|
+
emitRange(first, last);
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
return tokens;
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
/**
|
|
1768
|
+
* 「匹配行」块:整块**另起一行**,行号按可用宽度顺序折行。
|
|
1769
|
+
* 第一行带 `匹配行` 前缀,续行缩进对齐;最多 MAX_MATCH_BLOCK 行,超出用 `…` 收尾。
|
|
1770
|
+
*/
|
|
1771
|
+
function matchBlockLines(treeList: any, width: number): string[] {
|
|
1772
|
+
const state = activeSearch(treeList);
|
|
1773
|
+
if (state.matches.length === 0) return [];
|
|
1774
|
+
|
|
1775
|
+
const current = treeList.selectedIndex ?? -1;
|
|
1776
|
+
const label = `${DIM}Matches${RESET} `;
|
|
1777
|
+
const labelWidth = visibleWidth(label);
|
|
1778
|
+
const tokens = matchLineTokens(state.matches, current, (index) => rowNumber(treeList, index));
|
|
1779
|
+
|
|
1780
|
+
const lines: string[] = [];
|
|
1781
|
+
let line = "";
|
|
1782
|
+
let lineWidth = 0;
|
|
1783
|
+
let max = Math.max(8, width - 2 - labelWidth);
|
|
1784
|
+
for (const token of tokens) {
|
|
1785
|
+
const need = token.width + (line ? 1 : 0);
|
|
1786
|
+
if (line && lineWidth + need > max) {
|
|
1787
|
+
lines.push(line);
|
|
1788
|
+
if (lines.length >= MAX_MATCH_BLOCK) {
|
|
1789
|
+
lines[MAX_MATCH_BLOCK - 1] = `${lines[MAX_MATCH_BLOCK - 1]}${DIM}…${RESET}`;
|
|
1790
|
+
break;
|
|
1791
|
+
}
|
|
1792
|
+
line = "";
|
|
1793
|
+
lineWidth = 0;
|
|
1794
|
+
max = Math.max(8, width - 5);
|
|
1795
|
+
}
|
|
1796
|
+
line += (line ? "," : "") + token.text;
|
|
1797
|
+
lineWidth += token.width + (lineWidth > 0 ? 1 : 0);
|
|
1798
|
+
}
|
|
1799
|
+
if (line && lines.length < MAX_MATCH_BLOCK) lines.push(line);
|
|
1800
|
+
|
|
1801
|
+
return lines.map((text, i) => truncateToWidth(`${i === 0 ? ` ${label}` : " "}${DIM}${text}${RESET}`, width, ""));
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/** 渲染前算好「匹配行」块的最终行(受总高度限制;标签编辑时不显示) */
|
|
1805
|
+
function layoutBlockLines(component: any, treeList: any, width: number, total: number): string[] {
|
|
1806
|
+
if (component.labelInput || !STATE.enabled) return [];
|
|
1807
|
+
const lines = matchBlockLines(treeList, width);
|
|
1808
|
+
const room = Math.max(0, total - 5); // 列表至少留 5 行
|
|
1809
|
+
return lines.slice(0, Math.min(lines.length, room));
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
// ---------------------------------------------------------------- 状态栏
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* 当前计数 / 待定 leader:**不过期**。
|
|
1816
|
+
* vim 的 timeoutlen 默认 1 秒,命令超时就没了;但那是编辑器,
|
|
1817
|
+
* 交互界面里让人盯着屏幕猜"刚才那个数字还在不在"是大忌 ——
|
|
1818
|
+
* 所以这里一直留着,直到命令真正完成(或被别的命令顶掉)。
|
|
1819
|
+
*/
|
|
1820
|
+
function currentCount(treeList: any): number {
|
|
1821
|
+
return Math.max(0, Number(treeList.__vtCount ?? 0));
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
function currentLeader(treeList: any): "" | "g" | "z" | "m" | "`" {
|
|
1825
|
+
if (Number(treeList.__vtPendingG ?? 0) > 0) return "g";
|
|
1826
|
+
if (Number(treeList.__vtPendingZ ?? 0) > 0) return "z";
|
|
1827
|
+
if (Number(treeList.__vtPendingM ?? 0) > 0) return "m";
|
|
1828
|
+
if (Number(treeList.__vtPendingTick ?? 0) > 0) return "`";
|
|
1829
|
+
return "";
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/** 徽标只管模式,不掺输入内容(输入单独白字显示在它后面) */
|
|
1833
|
+
function modeBadge(treeList: any): string {
|
|
1834
|
+
return modeOf(treeList) === "search" ? "SEARCH" : "NORMAL";
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
/** 把按键翻成人看的文字(vim showcmd 那一串) */
|
|
1838
|
+
function echoLabel(data: string): string {
|
|
1839
|
+
if (data === "\n" || data === "\r") return "enter";
|
|
1840
|
+
if (data === "\x1b") return "esc";
|
|
1841
|
+
if (data === "\t") return "ctrl+i";
|
|
1842
|
+
const named: Array<[string, string]> = [
|
|
1843
|
+
["ctrl+j", "ctrl+j"],
|
|
1844
|
+
["ctrl+k", "ctrl+k"],
|
|
1845
|
+
["ctrl+i", "ctrl+i"],
|
|
1846
|
+
["ctrl+h", "ctrl+h"],
|
|
1847
|
+
["ctrl+d", "ctrl+d"],
|
|
1848
|
+
["ctrl+u", "ctrl+u"],
|
|
1849
|
+
["ctrl+e", "ctrl+e"],
|
|
1850
|
+
["ctrl+y", "ctrl+y"],
|
|
1851
|
+
["ctrl+f", "ctrl+f"],
|
|
1852
|
+
["ctrl+b", "ctrl+b"],
|
|
1853
|
+
["ctrl+l", "ctrl+l"],
|
|
1854
|
+
["ctrl+t", "ctrl+t"],
|
|
1855
|
+
["shift+down", "shift+↓"],
|
|
1856
|
+
["shift+up", "shift+↑"],
|
|
1857
|
+
["pageDown", "pgdn"],
|
|
1858
|
+
["pageUp", "pgup"],
|
|
1859
|
+
["up", "↑"],
|
|
1860
|
+
["down", "↓"],
|
|
1861
|
+
["left", "←"],
|
|
1862
|
+
["right", "→"],
|
|
1863
|
+
];
|
|
1864
|
+
for (const [key, label] of named) {
|
|
1865
|
+
try {
|
|
1866
|
+
if (matchesKey(data, key)) return label;
|
|
1867
|
+
} catch {
|
|
1868
|
+
// 某些多字节序列 matchesKey 会抛,忽略
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
if (isPrintableKey(data)) return data.length > 8 ? `${data.slice(0, 8)}…` : data;
|
|
1872
|
+
return "";
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/** 完整命令的回显只闪这么一下(毫秒) */
|
|
1876
|
+
const FLASH_MS = 100;
|
|
1877
|
+
|
|
1878
|
+
/** 等待中的回显最多挂这么久(毫秒)——计数本身不过期,只是屏幕上不一直留着 */
|
|
1879
|
+
const WAIT_DISPLAY_MS = 5000;
|
|
1880
|
+
|
|
1881
|
+
/**
|
|
1882
|
+
* 状态栏回显(vim showcmd 的三档):
|
|
1883
|
+
* - 还在等下一个键(`11` / `g` / `z`)→ **一直显示**
|
|
1884
|
+
* - 命令执行完(`j` / `11G`)→ **只闪 FLASH_MS 这么一下**
|
|
1885
|
+
* - 没匹配上的按键 → **什么都不显示**
|
|
1886
|
+
* `__vtCmd` = 当前这条命令敲出来的按键;`__vtEcho` = 屏幕上的那一串。
|
|
1887
|
+
*/
|
|
1888
|
+
function refreshEcho(treeList: any): void {
|
|
1889
|
+
const count = currentCount(treeList);
|
|
1890
|
+
const leader = currentLeader(treeList);
|
|
1891
|
+
|
|
1892
|
+
if (treeList.__vtUnmatched) {
|
|
1893
|
+
// 没匹配上:vim 只会响一声,屏幕上什么都不显示
|
|
1894
|
+
treeList.__vtEcho = "";
|
|
1895
|
+
treeList.__vtCmd = "";
|
|
1896
|
+
treeList.__vtEchoFlash = false;
|
|
1897
|
+
return;
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
const waiting = count > 0 || leader !== "";
|
|
1901
|
+
if (waiting) {
|
|
1902
|
+
// 还在等下一个键 → 显示着;但也不该永远挂在屏幕上
|
|
1903
|
+
const pendingAt = Number(treeList.__vtPendingAt ?? 0);
|
|
1904
|
+
if (pendingAt > 0 && Date.now() - pendingAt > WAIT_DISPLAY_MS) {
|
|
1905
|
+
treeList.__vtEcho = "";
|
|
1906
|
+
treeList.__vtCmd = "";
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
treeList.__vtEcho = String(treeList.__vtCmd ?? "");
|
|
1910
|
+
treeList.__vtEchoAt = Date.now();
|
|
1911
|
+
treeList.__vtEchoFlash = false;
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
treeList.__vtEcho = String(treeList.__vtCmd ?? "");
|
|
1916
|
+
treeList.__vtEchoAt = Date.now();
|
|
1917
|
+
treeList.__vtEchoFlash = true; // 执行完 = 闪一下
|
|
1918
|
+
treeList.__vtCmd = "";
|
|
1919
|
+
scheduleEchoClear(treeList);
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
/**
|
|
1923
|
+
* 闪一下的回显到期后:清掉 + 让 TUI 重绘(否则那行字会一直留在屏幕上)。
|
|
1924
|
+
* 扩展 API 没有 requestRender,靠 setWidget 的工厂函数借一个 TUI 引用(见文件末尾)。
|
|
1925
|
+
*/
|
|
1926
|
+
function scheduleEchoClear(treeList: any): void {
|
|
1927
|
+
const at = Number(treeList.__vtEchoAt ?? 0);
|
|
1928
|
+
const timer = setTimeout(() => {
|
|
1929
|
+
if (Number(treeList.__vtEchoAt ?? 0) !== at) return; // 已经换成别的命令了
|
|
1930
|
+
treeList.__vtEcho = "";
|
|
1931
|
+
treeList.__vtEchoFlash = false;
|
|
1932
|
+
try {
|
|
1933
|
+
STATE.tui?.requestRender?.();
|
|
1934
|
+
} catch {
|
|
1935
|
+
// 重绘失败就算了
|
|
1936
|
+
}
|
|
1937
|
+
}, FLASH_MS + 10);
|
|
1938
|
+
timer.unref?.();
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
// ---------------------------------------------------------------- 渲染
|
|
1942
|
+
|
|
1943
|
+
/**
|
|
1944
|
+
* 窗口定位:**始终把选中行放在列表区中间**。
|
|
1945
|
+
* 不接管原生切片,而是反解 maxVisibleLines,让原生的 startIndex 恰好落在我们想要的位置
|
|
1946
|
+
* (列表不足一屏时顶部对齐,宁可下方留白)。
|
|
1947
|
+
*/
|
|
1948
|
+
function stabilizeWindow(treeList: any, hardMax: number): void {
|
|
1949
|
+
const len: number = treeList.filteredNodes?.length ?? 0;
|
|
1950
|
+
if (len === 0) {
|
|
1951
|
+
treeList.maxVisibleLines = hardMax;
|
|
1952
|
+
treeList.__vtWin = { sel: 0, start: 0 };
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
const sel: number = Math.max(0, Math.min(treeList.selectedIndex ?? 0, len - 1));
|
|
1957
|
+
const half = Math.floor(hardMax / 2);
|
|
1958
|
+
const desiredStart = Math.max(0, sel - half);
|
|
1959
|
+
const startFor = (max: number) => Math.max(0, Math.min(sel - Math.floor(max / 2), len - max));
|
|
1960
|
+
|
|
1961
|
+
// len - max == desiredStart ⇒ 原生不会被 len 钳制,起点就是我们想要的
|
|
1962
|
+
let max = Math.max(1, Math.min(hardMax, len - desiredStart));
|
|
1963
|
+
if (startFor(max) !== desiredStart) {
|
|
1964
|
+
for (let candidate = max; candidate >= 1; candidate--) {
|
|
1965
|
+
if (startFor(candidate) === desiredStart) {
|
|
1966
|
+
max = candidate;
|
|
1967
|
+
break;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
treeList.maxVisibleLines = max;
|
|
1973
|
+
treeList.__vtWin = { sel, start: startFor(max) };
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
type Region = { first: number; last: number; border: number; status: number };
|
|
1977
|
+
|
|
1978
|
+
/**
|
|
1979
|
+
* 找列表区域:底部最后一条边框往上数 rendered 行就是列表;
|
|
1980
|
+
* 原生在列表末尾还画一行 `(12/340) [filters]`,那行不算列表。
|
|
1981
|
+
*/
|
|
1982
|
+
function locateList(lines: string[], rendered: number): Region | undefined {
|
|
1983
|
+
let lastBorder = -1;
|
|
1984
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1985
|
+
const plain = stripAnsi(String(lines[i] ?? "")).trim();
|
|
1986
|
+
if (plain.length > 5 && /^─+$/.test(plain)) {
|
|
1987
|
+
lastBorder = i;
|
|
1988
|
+
break;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
if (lastBorder < 0) return undefined;
|
|
1992
|
+
|
|
1993
|
+
let last = lastBorder - 1;
|
|
1994
|
+
while (last >= 0 && stripAnsi(String(lines[last] ?? "")).trim() === "") last--;
|
|
1995
|
+
|
|
1996
|
+
let status = -1;
|
|
1997
|
+
if (last >= 0 && /^\s*\(\d+\/\d+\)/.test(stripAnsi(String(lines[last] ?? "")))) {
|
|
1998
|
+
status = last;
|
|
1999
|
+
last -= 1;
|
|
2000
|
+
}
|
|
2001
|
+
|
|
2002
|
+
if (rendered <= 0) return { first: lastBorder, last: lastBorder - 1, border: lastBorder, status };
|
|
2003
|
+
const first = last - rendered + 1;
|
|
2004
|
+
if (first < 0) return undefined;
|
|
2005
|
+
return { first, last, border: lastBorder, status };
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
/**
|
|
2009
|
+
* 整屏重排:固定尺寸 + 行号 + 右栏预览 + 状态栏/帮助行定制。
|
|
2010
|
+
* 所有“借行”都从补白里拿,绝不改变总高度。
|
|
2011
|
+
*/
|
|
2012
|
+
function layoutScreen(component: any, lines: string[], width: number, hardMax: number): string[] {
|
|
2013
|
+
const treeList = component?.treeList;
|
|
2014
|
+
if (!treeList) return lines;
|
|
2015
|
+
|
|
2016
|
+
const start: number = treeList.__vtWin?.start ?? 0;
|
|
2017
|
+
const total: number = treeList.filteredNodes?.length ?? 0;
|
|
2018
|
+
const rendered = Math.max(0, Math.min(treeList.maxVisibleLines ?? 0, total - start));
|
|
2019
|
+
|
|
2020
|
+
const region = locateList(lines, rendered);
|
|
2021
|
+
if (!region) return lines;
|
|
2022
|
+
|
|
2023
|
+
const out = [...lines];
|
|
2024
|
+
|
|
2025
|
+
// 0) 「匹配行」块:整块另起一行(在搜索行下方)。行数已经在 render 包装里从
|
|
2026
|
+
// fixedListRows 扣掉了,所以这里只负责插入,不需要裁剪,总高度自然不变。
|
|
2027
|
+
const block: string[] = Array.isArray(treeList.__vtMatchBlock) ? treeList.__vtMatchBlock : [];
|
|
2028
|
+
let searchRow = -1;
|
|
2029
|
+
for (let i = 0; i < region.first; i++) {
|
|
2030
|
+
if (stripAnsi(String(out[i] ?? "")).includes("Type to search")) searchRow = i;
|
|
2031
|
+
}
|
|
2032
|
+
if (searchRow >= 0 && block.length > 0) {
|
|
2033
|
+
out.splice(searchRow + 1, 0, ...block);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
const region2 = block.length > 0 && searchRow >= 0 ? (locateList(out, rendered) ?? region) : region;
|
|
2037
|
+
const renderedRows = rendered;
|
|
2038
|
+
|
|
2039
|
+
// 0.5) 原生那行 `(3/18)` 是“可见位置/可见总数”,跟稳定行号打架 → 换成行号口径
|
|
2040
|
+
if (region2.status >= 0) {
|
|
2041
|
+
const line = stripAnsi(String(out[region2.status] ?? ""));
|
|
2042
|
+
const match = /^(\s*)\((\d+)\/(\d+)\)(.*)$/.exec(line);
|
|
2043
|
+
if (match) {
|
|
2044
|
+
const current = rowNumber(treeList, treeList.selectedIndex ?? 0);
|
|
2045
|
+
const total = unfolded(treeList).ids.length;
|
|
2046
|
+
out[region2.status] = truncateToWidth(
|
|
2047
|
+
`${match[1]}(${current}/${total})${match[4]}`,
|
|
2048
|
+
width,
|
|
2049
|
+
"",
|
|
2050
|
+
);
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
// 列表行数 = 目标整框高度 - 头部(标题/帮助/搜索行/块)- 尾部(状态行/边框)。
|
|
2055
|
+
// 头部折行多一行,列表就少一行 → 整框高度恒定。
|
|
2056
|
+
const tailCount = Math.max(0, out.length - (region2.first + rendered));
|
|
2057
|
+
const target = Number(treeList.__vtTargetTotal ?? hardMax + LIST_CHROME_ROWS);
|
|
2058
|
+
const rows = Math.max(3, Math.min(hardMax, target - region2.first - tailCount));
|
|
2059
|
+
|
|
2060
|
+
// 1) 补空行到固定高度(插在状态行之后;没有状态行就插在列表最后一行之后)
|
|
2061
|
+
const missing = rows - renderedRows;
|
|
2062
|
+
if (missing > 0 && !component.labelInput) {
|
|
2063
|
+
const insertAt =
|
|
2064
|
+
region2.status >= 0 ? region2.status + 1 : renderedRows > 0 ? region2.last + 1 : region2.border;
|
|
2065
|
+
out.splice(insertAt, 0, ...Array.from({ length: missing }, () => ""));
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
// 2) 右栏预览(列表区固定就是 rows 行)
|
|
2069
|
+
const first = renderedRows > 0 ? region2.first : region2.border;
|
|
2070
|
+
const previewEnabled = STATE.preview && !component.labelInput;
|
|
2071
|
+
const leftWidth = Math.max(24, Math.round(width * (1 - PREVIEW_SPLIT)));
|
|
2072
|
+
const rightWidth = width - leftWidth - 1;
|
|
2073
|
+
const canSplit = previewEnabled && rightWidth >= 12;
|
|
2074
|
+
|
|
2075
|
+
let previewLines: string[] = [];
|
|
2076
|
+
treeList.__vtPreviewInfo = { page: 0, total: 0 };
|
|
2077
|
+
if (canSplit) {
|
|
2078
|
+
const selectedId = treeList.filteredNodes?.[treeList.selectedIndex]?.node?.entry?.id;
|
|
2079
|
+
const state = previewState(treeList, selectedId);
|
|
2080
|
+
const wrapped = wrapPreview(treeList, rightWidth);
|
|
2081
|
+
const page = Math.max(1, rows - 1); // 第一行留给标题/页码
|
|
2082
|
+
const maxOffset = Math.max(0, wrapped.total - page);
|
|
2083
|
+
if (state.offset > maxOffset) state.offset = maxOffset;
|
|
2084
|
+
if (state.offset < 0) state.offset = 0;
|
|
2085
|
+
treeList.__vtPreviewInfo = { page, total: wrapped.total };
|
|
2086
|
+
|
|
2087
|
+
const previewTokens = activeSearch(treeList).query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
2088
|
+
// 搜索词染色只对纯文本做:markdown 行里已经有主题色,再塞 ANSI 会把标记打乱
|
|
2089
|
+
const visible = wrapped.lines
|
|
2090
|
+
.slice(state.offset, state.offset + page)
|
|
2091
|
+
.map((line) => (wrapped.plain && previewTokens.length > 0 ? highlightTokens(line, previewTokens, false) : line));
|
|
2092
|
+
const label =
|
|
2093
|
+
wrapped.total > page
|
|
2094
|
+
? `preview ${state.offset + 1}-${Math.min(wrapped.total, state.offset + page)}/${wrapped.total} ctrl+d/u half · ctrl+e/y line`
|
|
2095
|
+
: "preview (all)";
|
|
2096
|
+
previewLines = [`${DIM}${label}${RESET}`, ...visible];
|
|
2097
|
+
} else if (previewEnabled) {
|
|
2098
|
+
previewLines = [`${DIM}preview: no room${RESET}`];
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
// 3) 行号(只编真行,空白补行不编号)+ 分栏
|
|
2102
|
+
const numWidth = String(Math.max(9, start + rows)).length;
|
|
2103
|
+
for (let i = 0; i < rows; i++) {
|
|
2104
|
+
const index = first + i;
|
|
2105
|
+
if (index >= out.length) break;
|
|
2106
|
+
|
|
2107
|
+
const active = activeSearch(treeList);
|
|
2108
|
+
const isMatch = i < renderedRows && active.matches.includes(start + i);
|
|
2109
|
+
const isCurrent = i < renderedRows && start + i === treeList.selectedIndex;
|
|
2110
|
+
|
|
2111
|
+
// 行号:匹配行全黄(当前匹配再加粗),非匹配保持暗色
|
|
2112
|
+
const numColor = isCurrent ? YELLOW_BOLD : isMatch ? YELLOW : DIM;
|
|
2113
|
+
const numReset = numColor === DIM ? RESET : FG_RESET;
|
|
2114
|
+
// 行号按“未折叠”的清单算(vim 语义:折叠不改行号)
|
|
2115
|
+
const gutter =
|
|
2116
|
+
i < renderedRows
|
|
2117
|
+
? `${numColor}${String(rowNumber(treeList, start + i)).padStart(numWidth)}${numReset} `
|
|
2118
|
+
: " ".repeat(numWidth + 1);
|
|
2119
|
+
|
|
2120
|
+
let content = String(out[index] ?? "");
|
|
2121
|
+
// 正文只染“当前匹配”这一行(其余匹配靠行号颜色标记)
|
|
2122
|
+
if (isCurrent) {
|
|
2123
|
+
const tokens = active.query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
2124
|
+
if (tokens.length > 0) content = highlightTokens(content, tokens, true);
|
|
2125
|
+
}
|
|
2126
|
+
|
|
2127
|
+
const body = gutter + content;
|
|
2128
|
+
|
|
2129
|
+
if (!canSplit) {
|
|
2130
|
+
out[index] = truncateToWidth(body, width, "");
|
|
2131
|
+
continue;
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
const row = previewLines[i];
|
|
2135
|
+
const left = padTo(truncateToWidth(body, leftWidth, ""), leftWidth);
|
|
2136
|
+
const right = row ? padTo(truncateToWidth(row, rightWidth, ""), rightWidth) : " ".repeat(rightWidth);
|
|
2137
|
+
out[index] = `${left}${DIM}│${RESET}${right}`;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
// 3.5) 定制原生固定文案:状态行徽标/输入、匹配行块、帮助行
|
|
2141
|
+
customizeChrome(treeList, out, width);
|
|
2142
|
+
|
|
2143
|
+
return out;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
// ---------------------------------------------------------------- 按键
|
|
2147
|
+
|
|
2148
|
+
/** 主键位处理:所有分支都在这里,命中就 return,未命中交回原生 forward(data) */
|
|
2149
|
+
function vtHandle(component: any, data: string, forward: (data: string) => unknown): unknown {
|
|
2150
|
+
const treeList = component?.treeList;
|
|
2151
|
+
const normal = treeList ? modeOf(treeList) === "normal" : false;
|
|
2152
|
+
const rowBefore = normal ? selectedId(treeList) : undefined;
|
|
2153
|
+
if (normal) {
|
|
2154
|
+
treeList.__vtUnmatched = false;
|
|
2155
|
+
treeList.__vtFoldOp = false;
|
|
2156
|
+
if (!treeList.__vtLogical) treeList.__vtLogical = rowBefore; // 逻辑行的初值
|
|
2157
|
+
currentCount(treeList); // 顺手把过期的待定作废(vim:超时后这条命令就没了)
|
|
2158
|
+
currentLeader(treeList);
|
|
2159
|
+
const label = echoLabel(data);
|
|
2160
|
+
if (label) treeList.__vtCmd = `${treeList.__vtCmd ?? ""}${label}`;
|
|
2161
|
+
}
|
|
2162
|
+
try {
|
|
2163
|
+
return vtHandleInner(component, data, forward);
|
|
2164
|
+
} finally {
|
|
2165
|
+
if (normal) {
|
|
2166
|
+
// 逻辑行:**只有用户真的挪了光标才换**(vim 语义)。
|
|
2167
|
+
// 折叠把光标挪到折痕行不算(__vtFoldOp)—— 那只是显示位置变了,逻辑行没变。
|
|
2168
|
+
if (!treeList.__vtFoldOp && selectedId(treeList) !== rowBefore) {
|
|
2169
|
+
treeList.__vtLogical = selectedId(treeList);
|
|
2170
|
+
}
|
|
2171
|
+
refreshEcho(treeList);
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
function vtHandleInner(component: any, data: string, forward: (data: string) => unknown): unknown {
|
|
2177
|
+
const treeList = component?.treeList;
|
|
2178
|
+
if (!treeList || !Array.isArray(treeList.filteredNodes) || typeof treeList.applyFilter !== "function") {
|
|
2179
|
+
warnOnce("internal structure mismatch (treeList/filteredNodes/applyFilter), falling back to native");
|
|
2180
|
+
return forward(data);
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
ensureSearch(treeList);
|
|
2184
|
+
|
|
2185
|
+
if (process.env.PI_VIM_TREE_DEBUG === "2") console.error(`[vim-tree] key ${JSON.stringify(data)}`);
|
|
2186
|
+
|
|
2187
|
+
const mode = modeOf(treeList);
|
|
2188
|
+
|
|
2189
|
+
// ---- 下面这些是指令键,只在 normal 生效;search 模式是纯输入(像 chat 输入框)
|
|
2190
|
+
if (mode === "normal") {
|
|
2191
|
+
// esc 在 normal 下不拦:原样交给原生(原生 esc = 取消/关树)。
|
|
2192
|
+
// “取消待定命令 / 清除搜索高亮”已经有 ctrl+l,不再叠一层。
|
|
2193
|
+
|
|
2194
|
+
// 分支首行导航:`l` / `h`(主)+ ctrl+j / ctrl+k(能区分时)+ shift+down / shift+up
|
|
2195
|
+
// 传统终端 Ctrl+J = LF = "\n",与 Enter 同字节,所以只在非 "\n" 时认 ctrl+j
|
|
2196
|
+
const wantsNext =
|
|
2197
|
+
data === "l" || matchesKey(data, "shift+down") || (data !== "\n" && matchesKey(data, "ctrl+j"));
|
|
2198
|
+
const wantsPrevious = data === "h" || matchesKey(data, "shift+up") || matchesKey(data, "ctrl+k");
|
|
2199
|
+
if (wantsNext || wantsPrevious) {
|
|
2200
|
+
jumpBranchHead(treeList, wantsNext ? "down" : "up");
|
|
2201
|
+
return;
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
// ctrl+o / ctrl+i(传统终端里 Tab 与 ctrl+i 同字节 \x09):跳转栈后退 / 前进(vim)
|
|
2205
|
+
if (matchesKey(data, "ctrl+o") || matchesKey(data, "ctrl+i")) {
|
|
2206
|
+
const step = Math.max(1, currentCount(treeList)) * (matchesKey(data, "ctrl+i") ? 1 : -1);
|
|
2207
|
+
stepJump(treeList, step);
|
|
2208
|
+
treeList.__vtCount = 0;
|
|
2209
|
+
treeList.__vtPendingG = 0;
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
// ctrl+f / ctrl+b 翻整页,u / d(以及 ctrl+u / ctrl+d)翻半页(vim 的翻屏)
|
|
2214
|
+
if (
|
|
2215
|
+
matchesKey(data, "ctrl+f") ||
|
|
2216
|
+
matchesKey(data, "ctrl+b") ||
|
|
2217
|
+
matchesKey(data, "ctrl+u") ||
|
|
2218
|
+
matchesKey(data, "ctrl+d")
|
|
2219
|
+
) {
|
|
2220
|
+
const down = matchesKey(data, "ctrl+f") || matchesKey(data, "ctrl+d");
|
|
2221
|
+
const half = matchesKey(data, "ctrl+u") || matchesKey(data, "ctrl+d");
|
|
2222
|
+
scrollLines(treeList, (down ? 1 : -1) * (half ? 0.5 : 1));
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// ctrl+l:清掉搜索词和命中高亮
|
|
2227
|
+
if (matchesKey(data, "ctrl+l")) {
|
|
2228
|
+
clearSearchResults(treeList);
|
|
2229
|
+
return;
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
// 预览滚动:ctrl+e/y 一行;预览不可滚时吞掉(别掉进原生的过滤器键)
|
|
2233
|
+
if (matchesKey(data, "ctrl+e") || matchesKey(data, "ctrl+y")) {
|
|
2234
|
+
const info: { page: number; total: number } | undefined = treeList.__vtPreviewInfo;
|
|
2235
|
+
const canScroll = STATE.preview && info !== undefined && info.page > 0 && info.total > info.page;
|
|
2236
|
+
if (!canScroll) return;
|
|
2237
|
+
|
|
2238
|
+
const down = matchesKey(data, "ctrl+e");
|
|
2239
|
+
const step = 1;
|
|
2240
|
+
|
|
2241
|
+
const selectedId = treeList.filteredNodes?.[treeList.selectedIndex]?.node?.entry?.id;
|
|
2242
|
+
const state = previewState(treeList, selectedId);
|
|
2243
|
+
state.offset += down ? step : -step;
|
|
2244
|
+
if (state.offset < 0) state.offset = 0;
|
|
2245
|
+
return;
|
|
2246
|
+
}
|
|
2247
|
+
|
|
2248
|
+
// 预览开关:ctrl+h(或 f4)。传统终端 Ctrl+H 与 Backspace 同为 \x08,
|
|
2249
|
+
// 所以只在搜索词为空时才当 ctrl+h(search 模式下 \x08 永远是退格)。
|
|
2250
|
+
const isBackspace = data === "\x08";
|
|
2251
|
+
const wantsPreviewToggle =
|
|
2252
|
+
matchesKey(data, "f4") ||
|
|
2253
|
+
(!isBackspace && matchesKey(data, "ctrl+h")) ||
|
|
2254
|
+
(isBackspace && String(treeList.searchQuery ?? "").length === 0);
|
|
2255
|
+
if (wantsPreviewToggle) {
|
|
2256
|
+
STATE.preview = !STATE.preview;
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
// search 模式下 ctrl+u 是“清空输入”(vim 命令行习惯)
|
|
2262
|
+
if (mode === "search" && matchesKey(data, "ctrl+u")) {
|
|
2263
|
+
clearSearchInput(treeList);
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
// ---- normal(默认,vim 风格)
|
|
2268
|
+
if (mode === "normal") {
|
|
2269
|
+
// 0) leader 前缀放到最前面消费:一旦有 g/z 待定,下一个键就是它的第二键,
|
|
2270
|
+
// 不会被 j/k/n 之类的动作抢走(超时的待定在这里作废)
|
|
2271
|
+
const count = currentCount(treeList);
|
|
2272
|
+
const leader = currentLeader(treeList);
|
|
2273
|
+
|
|
2274
|
+
// ---- g 前缀的第二键
|
|
2275
|
+
if (leader === "g") {
|
|
2276
|
+
treeList.__vtPendingG = 0;
|
|
2277
|
+
if (data === "g") {
|
|
2278
|
+
gotoRow(treeList, count || 1);
|
|
2279
|
+
treeList.__vtCount = 0;
|
|
2280
|
+
return;
|
|
2281
|
+
}
|
|
2282
|
+
// g0:回到当前会话所在的分支(活动叶子;被折叠时会展开到它)
|
|
2283
|
+
if (data === "0") {
|
|
2284
|
+
jumpToActiveBranch(treeList);
|
|
2285
|
+
treeList.__vtCount = 0;
|
|
2286
|
+
return;
|
|
2287
|
+
}
|
|
2288
|
+
const gActions: Record<string, () => void> = {
|
|
2289
|
+
t: () => setFilter(treeList, "no-tools"),
|
|
2290
|
+
l: () => setFilter(treeList, "labeled-only"),
|
|
2291
|
+
u: () => setFilter(treeList, "user-only"),
|
|
2292
|
+
a: () => setFilter(treeList, "all"),
|
|
2293
|
+
d: () => setFilter(treeList, "default"),
|
|
2294
|
+
};
|
|
2295
|
+
gActions[data]?.();
|
|
2296
|
+
treeList.__vtCount = 0;
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
// ---- z 前缀的第二键(vim 的 z 家族)
|
|
2301
|
+
if (leader === "z") {
|
|
2302
|
+
treeList.__vtPendingZ = 0;
|
|
2303
|
+
const zActions: Record<string, () => void> = {
|
|
2304
|
+
a: () => withCursorKept(treeList, () => void setFoldAtCursor(treeList, "toggle")),
|
|
2305
|
+
o: () => withCursorKept(treeList, () => void setFoldAtCursor(treeList, "unfold")),
|
|
2306
|
+
c: () => withCursorKept(treeList, () => void setFoldAtCursor(treeList, "fold")),
|
|
2307
|
+
O: () => withCursorKept(treeList, () => void openUnderCursor(treeList)),
|
|
2308
|
+
C: () => withCursorKept(treeList, () => void closeUnderCursor(treeList)),
|
|
2309
|
+
R: () => withCursorKept(treeList, () => void openAllFolds(treeList)),
|
|
2310
|
+
M: () => withCursorKept(treeList, () => void closeAllFolds(treeList)),
|
|
2311
|
+
m: () => withCursorKept(treeList, () => void closeOneMoreLevel(treeList)),
|
|
2312
|
+
r: () => withCursorKept(treeList, () => void openOneLevel(treeList)),
|
|
2313
|
+
j: () => void jumpFold(treeList, 1),
|
|
2314
|
+
k: () => void jumpFold(treeList, -1),
|
|
2315
|
+
A: () => void toggleFoldRecursive(treeList),
|
|
2316
|
+
v: () => void viewCursorLine(treeList),
|
|
2317
|
+
};
|
|
2318
|
+
zActions[data]?.();
|
|
2319
|
+
treeList.__vtCount = 0;
|
|
2320
|
+
return;
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
// ---- m 前缀:设标记(vim 的 ma/mb/...)
|
|
2324
|
+
if (leader === "m") {
|
|
2325
|
+
treeList.__vtPendingM = 0;
|
|
2326
|
+
if (/^[a-zA-Z0-9]$/.test(data)) {
|
|
2327
|
+
const id = currentId(treeList);
|
|
2328
|
+
if (id) STATE.marks.set(data, id);
|
|
2329
|
+
}
|
|
2330
|
+
treeList.__vtCount = 0;
|
|
2331
|
+
return;
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
// ---- ` 前缀:跳到标记(vim 的 `a/`b/...,`' = 回到上次跳转之前)
|
|
2335
|
+
if (leader === "`") {
|
|
2336
|
+
treeList.__vtPendingTick = 0;
|
|
2337
|
+
if (matchesKey(data, "`")) jumpPreviousContext(treeList);
|
|
2338
|
+
else if (/^[a-zA-Z0-9]$/.test(data)) {
|
|
2339
|
+
const id = STATE.marks.get(data);
|
|
2340
|
+
if (id) jumpToMark(treeList, id);
|
|
2341
|
+
}
|
|
2342
|
+
treeList.__vtCount = 0;
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
if (data === "/") {
|
|
2347
|
+
treeList.__vtMode = "search";
|
|
2348
|
+
treeList.__vtCount = 0;
|
|
2349
|
+
treeList.__vtPendingG = 0;
|
|
2350
|
+
treeList.__vtCmd = ""; // 搜索模式有自己的输入框,回显别串过来
|
|
2351
|
+
// 记住进入搜索前的位置(esc 取消时回到这里),并清空输入框;
|
|
2352
|
+
// 上次确认的匹配结果仍然保留用于高亮 → 就是 vim 的 incsearch 行为
|
|
2353
|
+
treeList.__vtSearchOrigin = treeList.selectedIndex ?? 0;
|
|
2354
|
+
treeList.__vtSearchOriginId = currentId(treeList);
|
|
2355
|
+
clearSearchInput(treeList);
|
|
2356
|
+
return;
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
if (data === "G") {
|
|
2360
|
+
gotoRow(treeList, count > 0 ? count : unfolded(treeList).ids.length);
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
// g 是 leader:等下一个键(gg/g0/gt/gl/gu/ga/gd)
|
|
2365
|
+
if (data === "g") {
|
|
2366
|
+
treeList.__vtPendingG = Date.now();
|
|
2367
|
+
treeList.__vtPendingZ = 0;
|
|
2368
|
+
treeList.__vtPendingAt = Date.now();
|
|
2369
|
+
return;
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2372
|
+
// z 是折叠 leader:等下一个键(za/zo/zc/zM/zR/zm/zr/zj/zk)
|
|
2373
|
+
if (data === "z") {
|
|
2374
|
+
treeList.__vtPendingZ = Date.now();
|
|
2375
|
+
treeList.__vtPendingG = 0;
|
|
2376
|
+
treeList.__vtPendingAt = Date.now();
|
|
2377
|
+
return;
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
// m 是标记 leader:等下一个键(ma/mb/...,vim 的 mark)
|
|
2381
|
+
if (data === "m") {
|
|
2382
|
+
treeList.__vtPendingM = Date.now();
|
|
2383
|
+
treeList.__vtPendingG = 0;
|
|
2384
|
+
treeList.__vtPendingZ = 0;
|
|
2385
|
+
treeList.__vtPendingTick = 0;
|
|
2386
|
+
treeList.__vtPendingAt = Date.now();
|
|
2387
|
+
return;
|
|
2388
|
+
}
|
|
2389
|
+
|
|
2390
|
+
// ` 是跳标记 leader:等下一个键(`a/`b/...,vim 的 backtick)
|
|
2391
|
+
if (matchesKey(data, "`")) {
|
|
2392
|
+
treeList.__vtPendingTick = Date.now();
|
|
2393
|
+
treeList.__vtPendingG = 0;
|
|
2394
|
+
treeList.__vtPendingZ = 0;
|
|
2395
|
+
treeList.__vtPendingM = 0;
|
|
2396
|
+
treeList.__vtPendingAt = Date.now();
|
|
2397
|
+
return;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
// J:清空跳转栈(vim 的 :clearjumps)
|
|
2401
|
+
if (data === "J") {
|
|
2402
|
+
treeList.__vtJumps = [];
|
|
2403
|
+
treeList.__vtJumpIndex = -1;
|
|
2404
|
+
treeList.__vtCount = 0;
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
// M:清掉所有标记(vim 的 :delmarks)
|
|
2409
|
+
if (data === "M") {
|
|
2410
|
+
STATE.marks.clear();
|
|
2411
|
+
treeList.__vtCount = 0;
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
// q:关掉树(vim 的 help / preview 窗口里 q 就是关;less / fzf 同款)
|
|
2416
|
+
if (data === "q") {
|
|
2417
|
+
treeList.__vtCount = 0;
|
|
2418
|
+
treeList.__vtPendingG = 0;
|
|
2419
|
+
if (typeof treeList.onCancel === "function") treeList.onCancel();
|
|
2420
|
+
return;
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
// L 标签编辑 / T 标签时间戳(只认大写:小写 l 让给分支切换,小写 t 不占用)
|
|
2424
|
+
if (data === "L") {
|
|
2425
|
+
openLabelEditor(treeList);
|
|
2426
|
+
treeList.__vtCount = 0;
|
|
2427
|
+
return;
|
|
2428
|
+
}
|
|
2429
|
+
if (data === "T") {
|
|
2430
|
+
treeList.showLabelTimestamps = !treeList.showLabelTimestamps;
|
|
2431
|
+
treeList.applyFilter();
|
|
2432
|
+
treeList.__vtCount = 0;
|
|
2433
|
+
return;
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
// n / N / p:跳到下一个 / 上一个搜索匹配(vim 的 n/N,外加一个 p)
|
|
2437
|
+
if (data === "n" || data === "N" || data === "p") {
|
|
2438
|
+
stepMatch(treeList, data === "n" ? 1 : -1);
|
|
2439
|
+
treeList.__vtCount = 0;
|
|
2440
|
+
treeList.__vtPendingG = 0;
|
|
2441
|
+
return;
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
// vim 手感:{n}j / {n}k 移动 n 行(不环绕,到边停住)
|
|
2445
|
+
if (data === "j" || data === "k") {
|
|
2446
|
+
const listTotal = treeList.filteredNodes?.length ?? 0;
|
|
2447
|
+
if (listTotal > 0) {
|
|
2448
|
+
const step = Math.max(1, count || 1);
|
|
2449
|
+
const delta = data === "j" ? step : -step;
|
|
2450
|
+
const next = (treeList.selectedIndex ?? 0) + delta;
|
|
2451
|
+
treeList.selectedIndex = Math.max(0, Math.min(listTotal - 1, next));
|
|
2452
|
+
}
|
|
2453
|
+
treeList.__vtCount = 0;
|
|
2454
|
+
treeList.__vtPendingG = 0;
|
|
2455
|
+
return;
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
// {n}G 的计数(也支持 {n}% 里的数字)
|
|
2459
|
+
if (/^[0-9]$/.test(data)) {
|
|
2460
|
+
const next = Number(treeList.__vtCount ?? 0) * 10 + Number(data);
|
|
2461
|
+
treeList.__vtCount = Math.min(next, 9999);
|
|
2462
|
+
treeList.__vtPendingG = 0;
|
|
2463
|
+
treeList.__vtPendingAt = Date.now();
|
|
2464
|
+
return;
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
// 百分号跳转:{n}%
|
|
2468
|
+
if (data === "%") {
|
|
2469
|
+
const listTotal = unfolded(treeList).ids.length;
|
|
2470
|
+
if (count > 0 && listTotal > 0) {
|
|
2471
|
+
gotoRow(treeList, Math.max(1, Math.round((count / 100) * listTotal)));
|
|
2472
|
+
}
|
|
2473
|
+
treeList.__vtCount = 0;
|
|
2474
|
+
return;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
// u / d:翻半页(vim 的 ctrl+u / ctrl+d),和 ctrl+u / ctrl+d 是同一个动作
|
|
2478
|
+
if (data === "u" || data === "d") {
|
|
2479
|
+
scrollLines(treeList, data === "d" ? 0.5 : -0.5);
|
|
2480
|
+
treeList.__vtCount = 0;
|
|
2481
|
+
treeList.__vtPendingG = 0;
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
// 一页 = 原生 pgup/pgdn
|
|
2486
|
+
if (matchesKey(data, "pageDown") || matchesKey(data, "pageUp")) {
|
|
2487
|
+
treeList.__vtCount = 0;
|
|
2488
|
+
treeList.__vtPendingG = 0;
|
|
2489
|
+
return forward(data);
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
// 原生树自己的 ctrl 快捷键在 normal 模式下全部关掉(过滤器走 gt/gl/gu/ga/gd,
|
|
2493
|
+
// 标签走 L,时间戳走 T),不要在这里“顺手放行”造成误触。
|
|
2494
|
+
const swallowCtrl = ["ctrl+a", "ctrl+t", "ctrl+x"];
|
|
2495
|
+
if (swallowCtrl.some((key) => matchesKey(data, key))) {
|
|
2496
|
+
treeList.__vtCount = 0;
|
|
2497
|
+
treeList.__vtPendingG = 0;
|
|
2498
|
+
return;
|
|
2499
|
+
}
|
|
2500
|
+
|
|
2501
|
+
// normal 模式下普通字符一律吞掉(不落到搜索框)
|
|
2502
|
+
if (isPrintableKey(data)) {
|
|
2503
|
+
treeList.__vtUnmatched = true; // 没匹配上的按键 → 不显示回显
|
|
2504
|
+
return;
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
// 其余控制键(↑↓、enter、折叠键、粘贴…)照旧给原生
|
|
2508
|
+
treeList.__vtCount = 0;
|
|
2509
|
+
treeList.__vtPendingG = 0;
|
|
2510
|
+
return forward(data);
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
// ---- search 模式:**纯输入**(和 pi 聊天输入框一样),指令键一律不生效
|
|
2514
|
+
// enter:确认搜索(vim 的 /pat<CR>),结果落盘供 n/N 与常驻高亮使用
|
|
2515
|
+
if (matchesKey(data, "enter")) {
|
|
2516
|
+
commitSearch(treeList);
|
|
2517
|
+
treeList.__vtMode = "normal";
|
|
2518
|
+
return;
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
// esc:取消这次增量搜索,回到 normal(搜索串在 normal 下不显示 = 视觉上已清掉)
|
|
2522
|
+
if (matchesKey(data, "escape")) {
|
|
2523
|
+
cancelSearch(treeList);
|
|
2524
|
+
return;
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
// 其余按键全部交给 pi-tui 的 Input(= pi 聊天输入框的手感):
|
|
2528
|
+
// ctrl+a/e/u/k/w/f/b、Home/End、←/→、退格/删除、ctrl+y kill ring、ctrl+- 撤销、粘贴
|
|
2529
|
+
const input = ensureInput(treeList);
|
|
2530
|
+
input.handleInput(data);
|
|
2531
|
+
if (String(treeList.searchQuery ?? "") !== input.getValue()) {
|
|
2532
|
+
treeList.searchQuery = input.getValue();
|
|
2533
|
+
treeList.applyFilter();
|
|
2534
|
+
}
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
// ---------------------------------------------------------------- 补丁
|
|
2539
|
+
|
|
2540
|
+
function patchClass(cls: any): void {
|
|
2541
|
+
const proto = cls.prototype;
|
|
2542
|
+
|
|
2543
|
+
// /reload 会把扩展重新求值,但 **类对象是同一个**(chunk 被 pi 缓存)。
|
|
2544
|
+
// 所以不能靠 “已打过补丁就 return” 去防叠加 —— 那样 reload 后跑的还是上一版闭包,
|
|
2545
|
+
// 看起来就是“reload 不起作用”。正确做法:把**原始方法**存在 prototype 上,
|
|
2546
|
+
// 每次加载都从原始方法重新包一层,覆盖上一次的补丁。
|
|
2547
|
+
const stored = proto.__vtOrig as OrigMethods | undefined;
|
|
2548
|
+
const orig: OrigMethods =
|
|
2549
|
+
stored && typeof stored.handleInput === "function" && typeof stored.render === "function"
|
|
2550
|
+
? stored
|
|
2551
|
+
: { handleInput: proto.handleInput, render: proto.render };
|
|
2552
|
+
proto.__vtOrig = orig;
|
|
2553
|
+
proto.__vtPatched = true;
|
|
2554
|
+
|
|
2555
|
+
proto.handleInput = function handleInput(this: any, data: string): unknown {
|
|
2556
|
+
if (!STATE.enabled) return orig.handleInput.call(this, data);
|
|
2557
|
+
// 标签编辑框开着的时候整套交给原生:它才知道怎么把按键喂给 LabelInput,
|
|
2558
|
+
// 我们接管了 handleInput 就得把这个分支还回去,否则标签打不进字。
|
|
2559
|
+
if (this.labelInput) return orig.handleInput.call(this, data);
|
|
2560
|
+
STATE.treeList = this.treeList;
|
|
2561
|
+
try {
|
|
2562
|
+
return vtHandle(this, data, (key) => orig.handleInput.call(this, key));
|
|
2563
|
+
} catch (error) {
|
|
2564
|
+
warnOnce(`patch error, falling back to native: ${(error as Error)?.message ?? String(error)}`);
|
|
2565
|
+
return orig.handleInput.call(this, data);
|
|
2566
|
+
}
|
|
2567
|
+
};
|
|
2568
|
+
|
|
2569
|
+
proto.render = function render(this: any, width: number): string[] {
|
|
2570
|
+
if (!STATE.enabled) return orig.render.call(this, width);
|
|
2571
|
+
|
|
2572
|
+
let hardMax = 0;
|
|
2573
|
+
try {
|
|
2574
|
+
const treeList = this.treeList;
|
|
2575
|
+
if (treeList) STATE.treeList = treeList;
|
|
2576
|
+
if (treeList && typeof treeList.maxVisibleLines === "number") {
|
|
2577
|
+
ensureSearch(treeList);
|
|
2578
|
+
// 行号基准(未折叠的行清单):先算好,渲染中就不会改树状态
|
|
2579
|
+
unfolded(treeList);
|
|
2580
|
+
// 目标整框高度(列表 + 头部 + 状态行/边框)恒定:宽度变窄时帮助行会折行,
|
|
2581
|
+
// 列表就少一行补回来,整框高度不会跟着变。
|
|
2582
|
+
const listRows = fixedListRows(treeList);
|
|
2583
|
+
treeList.__vtTargetTotal = listRows + LIST_CHROME_ROWS;
|
|
2584
|
+
// 「匹配行」块另起一行占 N 行,所以列表区要少 N 行(总高度不变)。
|
|
2585
|
+
const block = layoutBlockLines(this, treeList, width, listRows);
|
|
2586
|
+
treeList.__vtMatchBlock = block;
|
|
2587
|
+
hardMax = Math.max(3, listRows - block.length);
|
|
2588
|
+
stabilizeWindow(treeList, hardMax);
|
|
2589
|
+
}
|
|
2590
|
+
} catch {
|
|
2591
|
+
// 渲染不能抛
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
const lines = orig.render.call(this, width);
|
|
2595
|
+
if (hardMax <= 0) return lines;
|
|
2596
|
+
try {
|
|
2597
|
+
return layoutScreen(this, lines, width, hardMax);
|
|
2598
|
+
} catch (error) {
|
|
2599
|
+
// 渲染不能抛,但也不能一声不响:布局出错时画面会退回原生,
|
|
2600
|
+
// 用户看到的是"折叠失灵",没有告警就查不出来。
|
|
2601
|
+
warnOnce(`render/layout error, falling back to native: ${(error as Error)?.message ?? String(error)}`);
|
|
2602
|
+
return lines;
|
|
2603
|
+
}
|
|
2604
|
+
};
|
|
2605
|
+
|
|
2606
|
+
STATE.patched = true;
|
|
2607
|
+
onDisable(() => {
|
|
2608
|
+
proto.handleInput = orig.handleInput;
|
|
2609
|
+
proto.render = orig.render;
|
|
2610
|
+
proto.__vtPatched = false;
|
|
2611
|
+
STATE.patched = false;
|
|
2612
|
+
restoreNativeTreeState(STATE.treeList);
|
|
2613
|
+
});
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
// ---------------------------------------------------------------- 扩展入口
|
|
2617
|
+
|
|
2618
|
+
/**
|
|
2619
|
+
* 借一个 TUI 引用:扩展 API 没有 requestRender,但 `ctx.ui.setWidget` 的工厂函数能拿到它
|
|
2620
|
+
*(工厂是同步调用的 → 拿完立刻把 widget 撤掉,布局上不留任何痕迹)。
|
|
2621
|
+
* 事件回调里带 ctx.ui,所以从 session_start / session_tree 借一次就够了。
|
|
2622
|
+
*/
|
|
2623
|
+
function captureTui(ui: any): void {
|
|
2624
|
+
if (STATE.tui || !ui || typeof ui.setWidget !== "function") return;
|
|
2625
|
+
try {
|
|
2626
|
+
ui.setWidget("vim-tree-tui", (tui: any) => {
|
|
2627
|
+
STATE.tui = tui;
|
|
2628
|
+
return new Container();
|
|
2629
|
+
});
|
|
2630
|
+
ui.setWidget("vim-tree-tui", undefined);
|
|
2631
|
+
} catch {
|
|
2632
|
+
// 拿不到就算了(回显照画,只是不主动重绘)
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
export default function vimTreeExtension(pi: ExtensionAPI): void {
|
|
2637
|
+
pi.on("session_start", (_event: unknown, ctx: any) => {
|
|
2638
|
+
STATE.marks.clear(); // 换会话了,旧标记的行 id 没意义
|
|
2639
|
+
captureTui(ctx?.ui);
|
|
2640
|
+
});
|
|
2641
|
+
pi.on("session_tree", (_event: unknown, ctx: any) => captureTui(ctx?.ui));
|
|
2642
|
+
|
|
2643
|
+
const startInner = async () => {
|
|
2644
|
+
if (STATE.cls) {
|
|
2645
|
+
if (STATE.enabled) patchClass(STATE.cls);
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2648
|
+
const cls = await findTreeSelectorClass();
|
|
2649
|
+
if (!cls) {
|
|
2650
|
+
console.error(`[vim-tree] ${STATE.notice}; patch not applied, /tree keeps native behavior`);
|
|
2651
|
+
return;
|
|
2652
|
+
}
|
|
2653
|
+
STATE.cls = cls;
|
|
2654
|
+
if (STATE.enabled) patchClass(cls); // PI_VIM_TREE=0 启动就完全不打补丁
|
|
2655
|
+
if (process.env.PI_VIM_TREE_DEBUG) console.error(`[vim-tree] /tree is patched (${STATE.notice})`);
|
|
2656
|
+
};
|
|
2657
|
+
|
|
2658
|
+
const start = async () => {
|
|
2659
|
+
try {
|
|
2660
|
+
await startInner();
|
|
2661
|
+
} catch (error) {
|
|
2662
|
+
console.error(`[vim-tree] startup failed: ${(error as Error)?.message ?? String(error)}`);
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
|
|
2666
|
+
void start();
|
|
2667
|
+
|
|
2668
|
+
pi.registerCommand("vim-tree", {
|
|
2669
|
+
description: "key bindings / layout / preview for the built-in /tree: /vim-tree on | off",
|
|
2670
|
+
handler: async (args: string, ctx: any) => {
|
|
2671
|
+
const action = String(args ?? "").trim().toLowerCase();
|
|
2672
|
+
|
|
2673
|
+
if (action === "off") {
|
|
2674
|
+
STATE.enabled = false;
|
|
2675
|
+
// 撤销所有补丁 → 完全回到原生。
|
|
2676
|
+
// 树实例上动过的地方(maxVisibleLines / 过滤器 / 折叠 / 搜索框)
|
|
2677
|
+
// 由补丁自己的撤销动作还原。
|
|
2678
|
+
revertAll();
|
|
2679
|
+
// 树实例上动过的地方也得还回去(maxVisibleLines / 搜索框),
|
|
2680
|
+
// 否则原生接手的不是原样:行数不对、搜索框里还留着我们的东西
|
|
2681
|
+
ctx.ui.notify("vim-tree: off - /tree restored to native behavior");
|
|
2682
|
+
return;
|
|
2683
|
+
}
|
|
2684
|
+
|
|
2685
|
+
if (action === "on") {
|
|
2686
|
+
STATE.enabled = true;
|
|
2687
|
+
if (!STATE.cls) await start();
|
|
2688
|
+
else if (!STATE.patched) patchClass(STATE.cls);
|
|
2689
|
+
ctx.ui.notify(STATE.patched ? `vim-tree: on · build ${BUILD}` : "vim-tree: not applied - " + STATE.notice);
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
ctx.ui.notify(
|
|
2694
|
+
`vim-tree: ${STATE.patched && STATE.enabled ? "on" : "off"} · build ${BUILD}${STATE.notice ? `(${STATE.notice})` : ""}`,
|
|
2695
|
+
);
|
|
2696
|
+
},
|
|
2697
|
+
});
|
|
2698
|
+
}
|