@uncarved/jade 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/LICENSE +21 -0
- package/README.md +191 -2
- package/bin/jade.js +20 -0
- package/dist/commands.d.ts +30 -0
- package/dist/commands.js +106 -0
- package/dist/commands.js.map +1 -0
- package/dist/config.d.ts +34 -0
- package/dist/config.js +130 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.js +53 -0
- package/dist/context.js.map +1 -0
- package/dist/distro.d.ts +97 -0
- package/dist/distro.js +311 -0
- package/dist/distro.js.map +1 -0
- package/dist/history.d.ts +10 -0
- package/dist/history.js +47 -0
- package/dist/history.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +1214 -0
- package/dist/main.js.map +1 -0
- package/dist/mcp.d.ts +114 -0
- package/dist/mcp.js +640 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory.d.ts +19 -0
- package/dist/memory.js +129 -0
- package/dist/memory.js.map +1 -0
- package/dist/mentions.d.ts +35 -0
- package/dist/mentions.js +130 -0
- package/dist/mentions.js.map +1 -0
- package/dist/plugin-cli.d.ts +16 -0
- package/dist/plugin-cli.js +251 -0
- package/dist/plugin-cli.js.map +1 -0
- package/dist/plugins/budget.d.ts +9 -0
- package/dist/plugins/budget.js +30 -0
- package/dist/plugins/budget.js.map +1 -0
- package/dist/plugins/builtins.d.ts +10 -0
- package/dist/plugins/builtins.js +22 -0
- package/dist/plugins/builtins.js.map +1 -0
- package/dist/plugins/checks.d.ts +70 -0
- package/dist/plugins/checks.js +335 -0
- package/dist/plugins/checks.js.map +1 -0
- package/dist/plugins/compact.d.ts +26 -0
- package/dist/plugins/compact.js +216 -0
- package/dist/plugins/compact.js.map +1 -0
- package/dist/plugins/core.d.ts +42 -0
- package/dist/plugins/core.js +190 -0
- package/dist/plugins/core.js.map +1 -0
- package/dist/plugins/install.d.ts +68 -0
- package/dist/plugins/install.js +377 -0
- package/dist/plugins/install.js.map +1 -0
- package/dist/plugins/loader.d.ts +182 -0
- package/dist/plugins/loader.js +253 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/plugins/policy.d.ts +80 -0
- package/dist/plugins/policy.js +541 -0
- package/dist/plugins/policy.js.map +1 -0
- package/dist/plugins/prompts.d.ts +30 -0
- package/dist/plugins/prompts.js +182 -0
- package/dist/plugins/prompts.js.map +1 -0
- package/dist/plugins/repeats.d.ts +9 -0
- package/dist/plugins/repeats.js +90 -0
- package/dist/plugins/repeats.js.map +1 -0
- package/dist/plugins/schema.d.ts +2 -0
- package/dist/plugins/schema.js +64 -0
- package/dist/plugins/schema.js.map +1 -0
- package/dist/provider.d.ts +111 -0
- package/dist/provider.js +326 -0
- package/dist/provider.js.map +1 -0
- package/dist/sessions.d.ts +22 -0
- package/dist/sessions.js +53 -0
- package/dist/sessions.js.map +1 -0
- package/dist/skills.d.ts +37 -0
- package/dist/skills.js +179 -0
- package/dist/skills.js.map +1 -0
- package/dist/sys.d.ts +48 -0
- package/dist/sys.js +116 -0
- package/dist/sys.js.map +1 -0
- package/dist/tools/checkpoint.d.ts +43 -0
- package/dist/tools/checkpoint.js +144 -0
- package/dist/tools/checkpoint.js.map +1 -0
- package/dist/tools/fs.d.ts +35 -0
- package/dist/tools/fs.js +417 -0
- package/dist/tools/fs.js.map +1 -0
- package/dist/tools/grep.d.ts +6 -0
- package/dist/tools/grep.js +243 -0
- package/dist/tools/grep.js.map +1 -0
- package/dist/tools/screenshot.d.ts +15 -0
- package/dist/tools/screenshot.js +162 -0
- package/dist/tools/screenshot.js.map +1 -0
- package/dist/tools/shell.d.ts +55 -0
- package/dist/tools/shell.js +314 -0
- package/dist/tools/shell.js.map +1 -0
- package/dist/tools/task.d.ts +31 -0
- package/dist/tools/task.js +86 -0
- package/dist/tools/task.js.map +1 -0
- package/dist/tools/todo.d.ts +10 -0
- package/dist/tools/todo.js +55 -0
- package/dist/tools/todo.js.map +1 -0
- package/dist/tools/web.d.ts +23 -0
- package/dist/tools/web.js +426 -0
- package/dist/tools/web.js.map +1 -0
- package/dist/ui/configure.d.ts +20 -0
- package/dist/ui/configure.js +369 -0
- package/dist/ui/configure.js.map +1 -0
- package/dist/ui/diff.d.ts +20 -0
- package/dist/ui/diff.js +142 -0
- package/dist/ui/diff.js.map +1 -0
- package/dist/ui/editor.d.ts +33 -0
- package/dist/ui/editor.js +128 -0
- package/dist/ui/editor.js.map +1 -0
- package/dist/ui/render.d.ts +13 -0
- package/dist/ui/render.js +84 -0
- package/dist/ui/render.js.map +1 -0
- package/dist/ui/screen.d.ts +95 -0
- package/dist/ui/screen.js +105 -0
- package/dist/ui/screen.js.map +1 -0
- package/dist/ui/transcript.d.ts +33 -0
- package/dist/ui/transcript.js +372 -0
- package/dist/ui/transcript.js.map +1 -0
- package/dist/ui/tui.d.ts +45 -0
- package/dist/ui/tui.js +1107 -0
- package/dist/ui/tui.js.map +1 -0
- package/package.json +59 -4
- package/src/commands.ts +120 -0
- package/src/config.ts +146 -0
- package/src/context.ts +64 -0
- package/src/distro.ts +395 -0
- package/src/history.ts +55 -0
- package/src/index.ts +27 -0
- package/src/main.ts +1267 -0
- package/src/mcp.ts +693 -0
- package/src/memory.ts +135 -0
- package/src/mentions.ts +135 -0
- package/src/plugin-cli.ts +239 -0
- package/src/plugins/budget.ts +37 -0
- package/src/plugins/builtins.ts +31 -0
- package/src/plugins/checks.ts +390 -0
- package/src/plugins/compact.ts +257 -0
- package/src/plugins/core.ts +217 -0
- package/src/plugins/install.ts +429 -0
- package/src/plugins/loader.ts +386 -0
- package/src/plugins/policy.ts +578 -0
- package/src/plugins/prompts.ts +215 -0
- package/src/plugins/repeats.ts +96 -0
- package/src/plugins/schema.ts +67 -0
- package/src/provider.ts +363 -0
- package/src/sessions.ts +61 -0
- package/src/skills.ts +197 -0
- package/src/sys.ts +136 -0
- package/src/tools/checkpoint.ts +164 -0
- package/src/tools/fs.ts +432 -0
- package/src/tools/grep.ts +268 -0
- package/src/tools/screenshot.ts +171 -0
- package/src/tools/shell.ts +357 -0
- package/src/tools/task.ts +105 -0
- package/src/tools/todo.ts +67 -0
- package/src/tools/web.ts +451 -0
- package/src/ui/configure.ts +397 -0
- package/src/ui/diff.ts +136 -0
- package/src/ui/editor.ts +136 -0
- package/src/ui/render.ts +74 -0
- package/src/ui/screen.ts +166 -0
- package/src/ui/transcript.ts +377 -0
- package/src/ui/tui.tsx +1662 -0
package/dist/ui/tui.js
ADDED
|
@@ -0,0 +1,1107 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
// 终端界面(Ink):全屏(备用屏幕缓冲区)分三块——顶部标题(版本、模型、目录),中间是对话,
|
|
3
|
+
// 自己滚动(滚轮、PgUp/PgDn),底部固定显示运行状态、排队的消息、输入框(或对话框)和状态栏。
|
|
4
|
+
// 运行中也能输入:提交的内容由宿主决定立即执行还是排队。
|
|
5
|
+
import { writeSync } from "node:fs";
|
|
6
|
+
import { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize, } from "ink";
|
|
7
|
+
import { useEffect, useReducer, useRef, useState, useSyncExternalStore, } from "react";
|
|
8
|
+
import stringWidth from "string-width";
|
|
9
|
+
import wrapAnsi from "wrap-ansi";
|
|
10
|
+
import { mentionAt, mentionText, rankPaths } from "../mentions.js";
|
|
11
|
+
import { edit, empty, layout } from "./editor.js";
|
|
12
|
+
import { dim, } from "./screen.js";
|
|
13
|
+
/**
|
|
14
|
+
* 界面可用的尺寸:宽度比终端少一列。
|
|
15
|
+
* Ink 增量重画时每行写成「内容 + ESC[K」;一行正好占满终端宽度时光标停在最后一列(等待换行),
|
|
16
|
+
* 紧跟的 ESC[K 会把最后一个字符擦掉,输入框之类的右边框就缺了一块。留出最后一列就不会这样
|
|
17
|
+
*/
|
|
18
|
+
function useScreenSize() {
|
|
19
|
+
const { columns, rows } = useWindowSize();
|
|
20
|
+
return { columns: Math.max(1, columns - 1), rows };
|
|
21
|
+
}
|
|
22
|
+
/** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
|
|
23
|
+
const MAX_LINES = 10_000;
|
|
24
|
+
/** 按显示宽度折行,保留颜色;每一项是屏幕上的一行 */
|
|
25
|
+
const wrap = (text, width) => wrapAnsi(text, width, { hard: true, trim: false }).split("\n");
|
|
26
|
+
/** 按宽度截成一行,截掉了内容时以 … 结尾;留出两列给 … 和展开标记 */
|
|
27
|
+
function oneRow(text, width) {
|
|
28
|
+
const rows = wrap(text, Math.max(1, width - 3));
|
|
29
|
+
const cut = rows.length > 1;
|
|
30
|
+
return { row: cut ? `${rows[0]}${dim("…")}` : rows[0], cut };
|
|
31
|
+
}
|
|
32
|
+
/** 这一项能不能展开:有折叠的内容,或者收起时被截掉了一部分 */
|
|
33
|
+
function foldable(l, width) {
|
|
34
|
+
if (l.think)
|
|
35
|
+
return l.think.text.trim() !== "";
|
|
36
|
+
return l.details !== undefined || (Boolean(l.oneRow) && oneRow(l.text, width).cut);
|
|
37
|
+
}
|
|
38
|
+
const elapsed = (t) => `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
|
|
39
|
+
/** 按显示宽度取 text 末尾最多 cols 列;截掉了开头时以 … 开头 */
|
|
40
|
+
export function tail(text, cols) {
|
|
41
|
+
if (stringWidth(text) <= cols)
|
|
42
|
+
return text;
|
|
43
|
+
const chars = [...text];
|
|
44
|
+
let out = "";
|
|
45
|
+
let w = 1;
|
|
46
|
+
for (let i = chars.length - 1; i >= 0; i--) {
|
|
47
|
+
const cw = stringWidth(chars[i]);
|
|
48
|
+
if (w + cw > cols)
|
|
49
|
+
break;
|
|
50
|
+
out = chars[i] + out;
|
|
51
|
+
w += cw;
|
|
52
|
+
}
|
|
53
|
+
return `…${out}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 思考收起时的一行(不含展开标记):思考中显示"✻ Thinking 12s · "加上最新一行的末尾,跟着模型实时往前走;
|
|
57
|
+
* 结束后显示"✻ Thought for 12s"
|
|
58
|
+
*/
|
|
59
|
+
function thinkingRow(t, width) {
|
|
60
|
+
if (t.end !== undefined)
|
|
61
|
+
return dim(`✻ Thought for ${elapsed(t)}`);
|
|
62
|
+
const label = `✻ Thinking ${elapsed(t)}`;
|
|
63
|
+
const latest = t.text
|
|
64
|
+
.split("\n")
|
|
65
|
+
.findLast((l) => l.trim())
|
|
66
|
+
?.trim()
|
|
67
|
+
.replace(/\s+/g, " ");
|
|
68
|
+
// 留出 " · "、" ▸" 和一列余量
|
|
69
|
+
const room = width - stringWidth(label) - 6;
|
|
70
|
+
return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
|
|
71
|
+
}
|
|
72
|
+
function wrapLine(l, width) {
|
|
73
|
+
if (l.think) {
|
|
74
|
+
if (!foldable(l, width))
|
|
75
|
+
return [thinkingRow(l.think, width)];
|
|
76
|
+
if (!l.open)
|
|
77
|
+
return [`${thinkingRow(l.think, width)}${dim(" ▸")}`];
|
|
78
|
+
const t = l.think;
|
|
79
|
+
const title = dim(t.end === undefined ? `✻ Thinking ${elapsed(t)}` : `✻ Thought for ${elapsed(t)}`);
|
|
80
|
+
const body = t.text
|
|
81
|
+
.replace(/\s+$/, "")
|
|
82
|
+
.split("\n")
|
|
83
|
+
.map((r) => (r ? dim(` ${r}`) : r))
|
|
84
|
+
.join("\n");
|
|
85
|
+
return [...wrap(`${title}${dim(" ▾")}`, width), ...wrap(body, width)];
|
|
86
|
+
}
|
|
87
|
+
if (!foldable(l, width))
|
|
88
|
+
return wrap(l.text, width);
|
|
89
|
+
if (!l.open) {
|
|
90
|
+
const head = l.oneRow ? oneRow(l.text, width).row : l.text;
|
|
91
|
+
return wrap(`${head}${dim(" ▸")}`, width);
|
|
92
|
+
}
|
|
93
|
+
const head = wrap(`${l.title ?? l.text}${dim(" ▾")}`, width);
|
|
94
|
+
return l.details === undefined ? head : [...head, ...wrap(l.details, width)];
|
|
95
|
+
}
|
|
96
|
+
/** 状态容器:频繁的流式更新合并到一帧再通知界面 */
|
|
97
|
+
class Store {
|
|
98
|
+
state;
|
|
99
|
+
#listeners = new Set();
|
|
100
|
+
#timer;
|
|
101
|
+
/** 已经完成的输出(折行前);普通的一项一行 */
|
|
102
|
+
#lines = [];
|
|
103
|
+
/** 按 #width 折好的行 */
|
|
104
|
+
#wrapped = [];
|
|
105
|
+
/** #wrapped 的每一行属于哪一项 */
|
|
106
|
+
#owners = [];
|
|
107
|
+
/** 带名字的项,amend 用 */
|
|
108
|
+
#named = new Map();
|
|
109
|
+
#width = 0;
|
|
110
|
+
constructor(status) {
|
|
111
|
+
this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status };
|
|
112
|
+
}
|
|
113
|
+
subscribe = (fn) => {
|
|
114
|
+
this.#listeners.add(fn);
|
|
115
|
+
return () => this.#listeners.delete(fn);
|
|
116
|
+
};
|
|
117
|
+
get = () => this.state;
|
|
118
|
+
update(patch, now = false) {
|
|
119
|
+
this.state = { ...this.state, ...patch };
|
|
120
|
+
if (now)
|
|
121
|
+
return this.#emit();
|
|
122
|
+
this.#timer ??= setTimeout(() => this.#emit(), 16);
|
|
123
|
+
}
|
|
124
|
+
#emit() {
|
|
125
|
+
clearTimeout(this.#timer);
|
|
126
|
+
this.#timer = undefined;
|
|
127
|
+
for (const fn of this.#listeners)
|
|
128
|
+
fn();
|
|
129
|
+
}
|
|
130
|
+
/** 追加普通的行;带 item 时 texts 合成一项(可折叠、可以之后补充),texts 是收起时显示的部分 */
|
|
131
|
+
append(texts, item) {
|
|
132
|
+
if (texts.length === 0)
|
|
133
|
+
return;
|
|
134
|
+
const lines = item === undefined
|
|
135
|
+
? texts.flatMap((t) => t.split("\n")).map((text) => ({ text }))
|
|
136
|
+
: [{ ...item, text: texts.join("\n") }];
|
|
137
|
+
this.#lines.push(...lines);
|
|
138
|
+
for (const l of lines)
|
|
139
|
+
if (l.id !== undefined)
|
|
140
|
+
this.#named.set(l.id, l);
|
|
141
|
+
if (this.#lines.length > MAX_LINES) {
|
|
142
|
+
this.#lines = this.#lines.slice(-MAX_LINES * 0.8);
|
|
143
|
+
this.#named = new Map(this.#lines.flatMap((l) => (l.id === undefined ? [] : [[l.id, l]])));
|
|
144
|
+
this.#width = 0;
|
|
145
|
+
}
|
|
146
|
+
const before = this.#wrapped.length;
|
|
147
|
+
if (this.#width)
|
|
148
|
+
for (const l of lines)
|
|
149
|
+
this.#push(l);
|
|
150
|
+
// 往上翻看时新内容不能把正在看的地方顶走
|
|
151
|
+
const scroll = this.state.scroll > 0
|
|
152
|
+
? this.state.scroll + this.#wrapped.length - before
|
|
153
|
+
: 0;
|
|
154
|
+
this.update({ version: this.state.version + 1, scroll });
|
|
155
|
+
}
|
|
156
|
+
/** 改写带名字的那一项;找不到时返回 false */
|
|
157
|
+
amend(id, change) {
|
|
158
|
+
const line = this.#named.get(id);
|
|
159
|
+
if (!line)
|
|
160
|
+
return false;
|
|
161
|
+
change(line);
|
|
162
|
+
if (!this.#width) {
|
|
163
|
+
this.update({ version: this.state.version + 1 });
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
const first = this.#owners.indexOf(line);
|
|
167
|
+
let count = 0;
|
|
168
|
+
while (first >= 0 && this.#owners[first + count] === line)
|
|
169
|
+
count++;
|
|
170
|
+
const rows = wrapLine(line, this.#width);
|
|
171
|
+
let scroll = this.state.scroll;
|
|
172
|
+
if (first >= 0) {
|
|
173
|
+
this.#wrapped.splice(first, count, ...rows);
|
|
174
|
+
this.#owners.splice(first, count, ...rows.map(() => line));
|
|
175
|
+
// 这一项在往上翻看时的可见部分下面,行数变了要跟着调,看的地方才不动
|
|
176
|
+
if (scroll > 0 && first >= this.#wrapped.length - scroll)
|
|
177
|
+
scroll += rows.length - count;
|
|
178
|
+
}
|
|
179
|
+
this.update({ version: this.state.version + 1, scroll });
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
#push(l) {
|
|
183
|
+
const rows = wrapLine(l, this.#width);
|
|
184
|
+
this.#wrapped.push(...rows);
|
|
185
|
+
for (const _ of rows)
|
|
186
|
+
this.#owners.push(l);
|
|
187
|
+
}
|
|
188
|
+
/** 按给定宽度折好的全部输出;宽度变了(终端缩放)才重新折行 */
|
|
189
|
+
lines(width) {
|
|
190
|
+
if (width !== this.#width) {
|
|
191
|
+
this.#width = width;
|
|
192
|
+
this.#wrapped = [];
|
|
193
|
+
this.#owners = [];
|
|
194
|
+
for (const l of this.#lines)
|
|
195
|
+
this.#push(l);
|
|
196
|
+
}
|
|
197
|
+
return this.#wrapped;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* 展开或收起第 row 行(折好的行)所在的项;不是可折叠项时什么也不做。
|
|
201
|
+
* start、view 是当前可见的第一行和可见行数:可见部分的开头保持不动;
|
|
202
|
+
* 展开时标题如果在可见部分的底部,往下滚到能看见展开的内容,但标题不滚出去
|
|
203
|
+
*/
|
|
204
|
+
toggle(row, start, view) {
|
|
205
|
+
const line = this.#owners[row];
|
|
206
|
+
if (!line || !foldable(line, this.#width))
|
|
207
|
+
return;
|
|
208
|
+
let first = row;
|
|
209
|
+
while (first > 0 && this.#owners[first - 1] === line)
|
|
210
|
+
first--;
|
|
211
|
+
let count = 0;
|
|
212
|
+
while (this.#owners[first + count] === line)
|
|
213
|
+
count++;
|
|
214
|
+
line.open = !line.open;
|
|
215
|
+
const rows = wrapLine(line, this.#width);
|
|
216
|
+
this.#wrapped.splice(first, count, ...rows);
|
|
217
|
+
this.#owners.splice(first, count, ...rows.map(() => line));
|
|
218
|
+
const end = Math.max(start + view, line.open ? Math.min(first + rows.length, first + view) : 0);
|
|
219
|
+
this.update({
|
|
220
|
+
version: this.state.version + 1,
|
|
221
|
+
scroll: Math.max(0, this.#wrapped.length - end),
|
|
222
|
+
}, true);
|
|
223
|
+
}
|
|
224
|
+
clear() {
|
|
225
|
+
this.#lines = [];
|
|
226
|
+
this.#wrapped = [];
|
|
227
|
+
this.#owners = [];
|
|
228
|
+
this.#named.clear();
|
|
229
|
+
this.update({ version: this.state.version + 1, live: undefined, progress: [], scroll: 0 }, true);
|
|
230
|
+
}
|
|
231
|
+
/** 往上(正数)或往下滚 n 行,不超过 max */
|
|
232
|
+
scrollBy(n, max) {
|
|
233
|
+
const scroll = Math.max(0, Math.min(max, this.state.scroll + n));
|
|
234
|
+
if (scroll !== this.state.scroll)
|
|
235
|
+
this.update({ scroll }, true);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/** 开关鼠标事件上报(SGR 格式),用来接收滚轮和点击;开着时终端里选中文字要按住 Shift */
|
|
239
|
+
const MOUSE_ON = "\x1b[?1000h\x1b[?1006h";
|
|
240
|
+
const MOUSE_OFF = "\x1b[?1006l\x1b[?1000l";
|
|
241
|
+
export function tuiScreen(opts) {
|
|
242
|
+
const stdout = opts.io?.stdout ?? process.stdout;
|
|
243
|
+
const store = new Store(opts.status);
|
|
244
|
+
/**
|
|
245
|
+
* 正在进行的思考:一开始就作为一项放进对话(可以点击展开),之后的增量攒起来,每隔一小段时间改写一次那一项。
|
|
246
|
+
* 收起时只占一行,显示模型最新想到了哪里;结束时换成用了多久
|
|
247
|
+
*/
|
|
248
|
+
let thinking;
|
|
249
|
+
let thinkingCount = 0;
|
|
250
|
+
const redrawThinking = () => {
|
|
251
|
+
if (!thinking)
|
|
252
|
+
return;
|
|
253
|
+
clearTimeout(thinking.timer);
|
|
254
|
+
thinking.timer = undefined;
|
|
255
|
+
store.amend(thinking.id, () => { });
|
|
256
|
+
};
|
|
257
|
+
const endThinking = () => {
|
|
258
|
+
if (!thinking)
|
|
259
|
+
return;
|
|
260
|
+
thinking.think.end = Date.now();
|
|
261
|
+
redrawThinking();
|
|
262
|
+
thinking = undefined;
|
|
263
|
+
};
|
|
264
|
+
/** 推进正文:已经完整的行移进对话,只把最后不完整的一行留在底部;all 时全部移进去,连同思考一起结束 */
|
|
265
|
+
const flushLive = (all = false) => {
|
|
266
|
+
if (all)
|
|
267
|
+
endThinking();
|
|
268
|
+
const live = store.state.live;
|
|
269
|
+
if (!live)
|
|
270
|
+
return;
|
|
271
|
+
const lines = live.text.split("\n");
|
|
272
|
+
const rest = all ? "" : lines.pop();
|
|
273
|
+
if (all && lines.at(-1) === "")
|
|
274
|
+
lines.pop();
|
|
275
|
+
store.append(lines);
|
|
276
|
+
store.update({ live: rest || !all ? { text: rest } : undefined });
|
|
277
|
+
};
|
|
278
|
+
const ask = (dialog) => new Promise((resolve) => {
|
|
279
|
+
const d = {
|
|
280
|
+
...dialog,
|
|
281
|
+
resolve: (v) => {
|
|
282
|
+
store.update({ dialogs: store.state.dialogs.filter((x) => x !== d) }, true);
|
|
283
|
+
resolve(v);
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
store.update({ dialogs: [...store.state.dialogs, d] }, true);
|
|
287
|
+
});
|
|
288
|
+
// 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
|
|
289
|
+
// 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
|
|
290
|
+
stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
|
|
291
|
+
const instance = render(_jsx(App, { store: store, version: opts.version, commands: opts.commands, handlers: opts.handlers, history: opts.history ?? [] }), {
|
|
292
|
+
exitOnCtrlC: false,
|
|
293
|
+
alternateScreen: true,
|
|
294
|
+
// 全屏每帧只重写变化的行
|
|
295
|
+
incrementalRendering: true,
|
|
296
|
+
...(opts.io
|
|
297
|
+
? { ...opts.io, interactive: true, patchConsole: false }
|
|
298
|
+
: {}),
|
|
299
|
+
});
|
|
300
|
+
stdout.write(MOUSE_ON);
|
|
301
|
+
// 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
|
|
302
|
+
const restore = () => {
|
|
303
|
+
try {
|
|
304
|
+
writeSync(1, `${MOUSE_OFF}\x1b[?1049l\x1b[?25h`);
|
|
305
|
+
}
|
|
306
|
+
catch { }
|
|
307
|
+
};
|
|
308
|
+
if (!opts.io)
|
|
309
|
+
process.on("exit", restore);
|
|
310
|
+
return {
|
|
311
|
+
interactive: true,
|
|
312
|
+
log(text, o) {
|
|
313
|
+
flushLive(true);
|
|
314
|
+
store.update({ live: undefined });
|
|
315
|
+
// 带名字的项(工具调用)收起时只占一行,结果用 amend 接在后面
|
|
316
|
+
store.append(text.split("\n"), o?.details !== undefined || o?.id !== undefined
|
|
317
|
+
? { details: o.details, id: o.id, oneRow: o.id !== undefined }
|
|
318
|
+
: undefined);
|
|
319
|
+
},
|
|
320
|
+
amend(id, text, o) {
|
|
321
|
+
flushLive(true);
|
|
322
|
+
const found = store.amend(id, (l) => {
|
|
323
|
+
l.text = `${l.text} ${text}`;
|
|
324
|
+
if (o?.details !== undefined)
|
|
325
|
+
l.details = o.details;
|
|
326
|
+
});
|
|
327
|
+
if (!found)
|
|
328
|
+
store.append([` ${text}`], o?.details !== undefined ? { details: o.details } : undefined);
|
|
329
|
+
},
|
|
330
|
+
progress(id, line) {
|
|
331
|
+
const rest = store.state.progress.filter((p) => p.id !== id);
|
|
332
|
+
store.update({
|
|
333
|
+
progress: line === undefined ? rest : [...rest, { id, line }],
|
|
334
|
+
});
|
|
335
|
+
},
|
|
336
|
+
stream(kind, text) {
|
|
337
|
+
if (kind === "thinking") {
|
|
338
|
+
if (store.state.live) {
|
|
339
|
+
flushLive(true);
|
|
340
|
+
store.update({ live: undefined });
|
|
341
|
+
}
|
|
342
|
+
if (!thinking) {
|
|
343
|
+
if (!text.trim())
|
|
344
|
+
return;
|
|
345
|
+
const think = { text: "", start: Date.now() };
|
|
346
|
+
thinking = { id: `\0thinking-${thinkingCount++}`, think };
|
|
347
|
+
store.append([""], { id: thinking.id, think });
|
|
348
|
+
}
|
|
349
|
+
thinking.think.text += text;
|
|
350
|
+
thinking.timer ??= setTimeout(redrawThinking, 50);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
endThinking();
|
|
354
|
+
if (!store.state.live) {
|
|
355
|
+
text = text.replace(/^\n+/, "");
|
|
356
|
+
if (!text)
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
store.update({ live: { text: (store.state.live?.text ?? "") + text } });
|
|
360
|
+
if (text.includes("\n"))
|
|
361
|
+
flushLive();
|
|
362
|
+
},
|
|
363
|
+
endStream() {
|
|
364
|
+
flushLive(true);
|
|
365
|
+
store.update({ live: undefined });
|
|
366
|
+
},
|
|
367
|
+
busy(label) {
|
|
368
|
+
const current = store.state.busy;
|
|
369
|
+
if (label === undefined)
|
|
370
|
+
store.update({ busy: undefined });
|
|
371
|
+
else
|
|
372
|
+
store.update({ busy: { label, since: current?.since ?? Date.now() } });
|
|
373
|
+
},
|
|
374
|
+
status(info) {
|
|
375
|
+
store.update({ status: { ...store.state.status, ...info } });
|
|
376
|
+
},
|
|
377
|
+
queued(items) {
|
|
378
|
+
store.update({ queued: [...items] });
|
|
379
|
+
},
|
|
380
|
+
select: (title, choices, o) => ask({
|
|
381
|
+
kind: "select",
|
|
382
|
+
title,
|
|
383
|
+
body: o?.body,
|
|
384
|
+
choices: choices,
|
|
385
|
+
resolve: () => { },
|
|
386
|
+
}),
|
|
387
|
+
input: (title, o) => ask({
|
|
388
|
+
kind: "input",
|
|
389
|
+
title,
|
|
390
|
+
...o,
|
|
391
|
+
resolve: () => { },
|
|
392
|
+
}),
|
|
393
|
+
clear() {
|
|
394
|
+
clearTimeout(thinking?.timer);
|
|
395
|
+
thinking = undefined;
|
|
396
|
+
store.clear();
|
|
397
|
+
},
|
|
398
|
+
async close() {
|
|
399
|
+
flushLive(true);
|
|
400
|
+
store.update({ live: undefined, busy: undefined, progress: [] }, true);
|
|
401
|
+
// 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
|
|
402
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
403
|
+
stdout.write(MOUSE_OFF);
|
|
404
|
+
instance.unmount();
|
|
405
|
+
await instance.waitUntilExit();
|
|
406
|
+
process.off("exit", restore);
|
|
407
|
+
},
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
// ---------- 组件 ----------
|
|
411
|
+
/**
|
|
412
|
+
* SGR 鼠标事件(Ink 去掉了开头的 ESC):按钮号、列、行(从 1 开始),M 是按下、m 是松开。
|
|
413
|
+
* 按钮号去掉 Shift/Alt/Ctrl 位后 0 是左键,64 是滚轮向上,65 向下
|
|
414
|
+
*/
|
|
415
|
+
const MOUSE = /^\[<(\d+);\d+;(\d+)([Mm])$/;
|
|
416
|
+
const WHEEL_LINES = 3;
|
|
417
|
+
/** 终端矮于这么多行时标题只占一行 */
|
|
418
|
+
const COMPACT_ROWS = 24;
|
|
419
|
+
/**
|
|
420
|
+
* 底部的菜单、选择框、多行输入最多占多少行:终端很矮时整个界面会高过终端,
|
|
421
|
+
* 超出的部分被裁掉,输入框的边框和状态栏就显示不全了
|
|
422
|
+
*/
|
|
423
|
+
const roomFor = (rows, max) => Math.max(3, Math.min(max, Math.floor((rows - 10) / 2)));
|
|
424
|
+
function App({ store, version, commands, handlers, history, }) {
|
|
425
|
+
const state = useSyncExternalStore(store.subscribe, store.get);
|
|
426
|
+
const dialog = state.dialogs[0];
|
|
427
|
+
const { columns, rows } = useScreenSize();
|
|
428
|
+
// 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
|
|
429
|
+
const ref = useRef(null);
|
|
430
|
+
const { height, top } = useBoxMetrics(ref);
|
|
431
|
+
const width = Math.max(10, columns - 2);
|
|
432
|
+
const done = store.lines(width);
|
|
433
|
+
// 还没结束的流式块和正在运行的工具的进度:思考只显示最新的一行,进度每个工具一行
|
|
434
|
+
const live = [
|
|
435
|
+
...(state.live?.text ? wrap(state.live.text, width) : []),
|
|
436
|
+
...state.progress.map((p) => oneRow(p.line, width).row),
|
|
437
|
+
];
|
|
438
|
+
const total = done.length + live.length;
|
|
439
|
+
// 往上翻看时最后一行用来提示
|
|
440
|
+
const scrolled = state.scroll > 0 && total > height;
|
|
441
|
+
const view = Math.max(0, scrolled ? height - 1 : height);
|
|
442
|
+
const max = Math.max(0, total - view);
|
|
443
|
+
const scroll = Math.min(state.scroll, max);
|
|
444
|
+
const end = total - scroll;
|
|
445
|
+
const start = Math.max(0, end - view);
|
|
446
|
+
const shown = [
|
|
447
|
+
...done.slice(start, Math.min(end, done.length)),
|
|
448
|
+
...live.slice(Math.max(0, start - done.length), Math.max(0, end - done.length)),
|
|
449
|
+
];
|
|
450
|
+
const page = Math.max(1, view - 2);
|
|
451
|
+
// Ink 增量渲染只用相对光标移动,第一帧起点一旦偏了(启动时终端尺寸还没稳定、窗口缩放、别的输出插进来),
|
|
452
|
+
// 之后每帧都会画错行。启动后、尺寸变化后和按 Ctrl+L 时让一帧比终端高,Ink 会清屏从左上角整帧重画(包在同步输出里),下一帧再恢复
|
|
453
|
+
const [redraws, setRedraws] = useState(0);
|
|
454
|
+
const [repaint, setRepaint] = useState(false);
|
|
455
|
+
useEffect(() => {
|
|
456
|
+
const t = setTimeout(() => setRepaint(true), 100);
|
|
457
|
+
return () => clearTimeout(t);
|
|
458
|
+
}, [columns, rows, redraws]);
|
|
459
|
+
useEffect(() => {
|
|
460
|
+
if (!repaint)
|
|
461
|
+
return;
|
|
462
|
+
// 要比 Ink 的帧间隔长,否则这一帧会被合并掉
|
|
463
|
+
const t = setTimeout(() => setRepaint(false), 50);
|
|
464
|
+
return () => clearTimeout(t);
|
|
465
|
+
}, [repaint]);
|
|
466
|
+
useInput((input, key) => {
|
|
467
|
+
if (key.ctrl && input === "l")
|
|
468
|
+
return setRedraws((n) => n + 1);
|
|
469
|
+
const mouse = MOUSE.exec(input);
|
|
470
|
+
if (mouse) {
|
|
471
|
+
const button = Number(mouse[1]) & ~0b11100;
|
|
472
|
+
if (button === 64)
|
|
473
|
+
store.scrollBy(WHEEL_LINES, max);
|
|
474
|
+
else if (button === 65)
|
|
475
|
+
store.scrollBy(-WHEEL_LINES, max);
|
|
476
|
+
else if (button === 0 && mouse[3] === "M") {
|
|
477
|
+
// 点在对话区里已经完成的输出上:展开或收起那一项
|
|
478
|
+
const i = Number(mouse[2]) - 1 - top;
|
|
479
|
+
if (i >= 0 && i < shown.length && start + i < done.length)
|
|
480
|
+
store.toggle(start + i, start, view);
|
|
481
|
+
}
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
// 选择框自己用 PgUp/PgDn 翻选项
|
|
485
|
+
if (dialog?.kind === "select")
|
|
486
|
+
return;
|
|
487
|
+
if (key.pageUp)
|
|
488
|
+
store.scrollBy(page, max);
|
|
489
|
+
else if (key.pageDown)
|
|
490
|
+
store.scrollBy(-page, max);
|
|
491
|
+
else if (key.ctrl && key.home)
|
|
492
|
+
store.scrollBy(max, max);
|
|
493
|
+
else if (key.ctrl && key.end)
|
|
494
|
+
store.scrollBy(-max, max);
|
|
495
|
+
});
|
|
496
|
+
// 总高度要比终端少一行,否则 Ink 认为输出占满了屏幕,每帧清屏重画。
|
|
497
|
+
// 重画那一帧上下各垫一行空白:终端把顶上那行滚出去后,看到的和平时逐行一样,所以不会闪。
|
|
498
|
+
// 只做纵向裁剪:每行都已按宽度折好或截断,横向裁剪会让 Ink 每帧对每一行再切一遍 ANSI 字符串
|
|
499
|
+
return (_jsx(Box, { flexDirection: "column", width: columns, height: repaint ? rows + 1 : Math.max(1, rows - 1), paddingY: repaint ? 1 : 0, overflowY: "hidden", children: _jsxs(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden", children: [_jsx(Header, { status: state.status, version: version, compact: rows < COMPACT_ROWS }), _jsxs(Box, { ref: ref, flexDirection: "column", flexGrow: 1, flexShrink: 1, flexBasis: 0, overflowY: "hidden", paddingX: 1, children: [shown.map((l, i) => (_jsx(Text, { wrap: "truncate-end", children: l || " " }, i))), scrolled ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: `── ↓ ${scroll} more lines · wheel / PgDn to scroll · ctrl+end to jump to the bottom ──` })) : null] }), _jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [state.busy && !dialog ? (_jsx(Spinner, { label: state.busy.label, since: state.busy.since })) : null, state.queued.map((q, i) => (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [" ↳ queued: ", q.replace(/\s+/g, " ")] }, i))), dialog ? (dialog.kind === "select" ? (_jsx(SelectDialog, { dialog: dialog }, dialogKey(dialog))) : (_jsx(InputDialog, { dialog: dialog }, dialogKey(dialog)))) : null, _jsx(Prompt, { commands: commands, handlers: handlers, history: history, busy: Boolean(state.busy), active: !dialog, onSubmit: () => store.scrollBy(-max, max) }), _jsx(StatusBar, { status: state.status, width: Math.max(10, columns - 2) })] })] }) }));
|
|
500
|
+
}
|
|
501
|
+
const JADE = "#00a86b";
|
|
502
|
+
const SHINE = "#b6f2d4";
|
|
503
|
+
/**
|
|
504
|
+
* 标题左边的吉祥物:一个玉做的团子,用半格字符画的像素图,三行高,正好和右边三行文字并排。
|
|
505
|
+
* 每个字符上下两个像素;眼睛是玉上挖空的两格,左上角一点高光让它看起来像玉
|
|
506
|
+
*/
|
|
507
|
+
function Bot() {
|
|
508
|
+
return (_jsxs(Box, { flexDirection: "column", flexShrink: 0, marginRight: 2, children: [_jsxs(Text, { color: JADE, children: [" ▄", _jsx(Text, { color: SHINE, backgroundColor: JADE, children: "\u2584" }), "████▄"] }), _jsx(Text, { color: JADE, children: "\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588" }), _jsx(Text, { color: JADE, children: "\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580" })] }));
|
|
509
|
+
}
|
|
510
|
+
function Header({ status, version, compact, }) {
|
|
511
|
+
const { columns } = useScreenSize();
|
|
512
|
+
if (compact)
|
|
513
|
+
return (_jsx(Box, { flexShrink: 0, paddingX: 1, children: _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", bold: true, children: "jade" }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), _jsx(Text, { color: "cyan", children: status.model }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), _jsx(Text, { children: status.cwd }), status.branch ? (_jsxs(Text, { color: "magenta", children: [" (", status.branch, ")"] })) : null] }) }));
|
|
514
|
+
return (_jsxs(Box, { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [columns >= 50 ? _jsx(Bot, {}) : null, _jsxs(Box, { flexDirection: "column", flexGrow: 1, flexShrink: 1, children: [_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", bold: true, children: "jade" }), _jsxs(Text, { dimColor: true, children: [" v", version] }), status.session ? (_jsx(Text, { dimColor: true, children: ` · session ${status.session}` })) : null] }), _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", children: status.model }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), _jsx(Text, { children: status.cwd }), status.branch ? (_jsxs(Text, { color: "magenta", children: [" (", status.branch, ")"] })) : null] }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: "/help for commands \u00B7 @ to attach files" })] })] }));
|
|
515
|
+
}
|
|
516
|
+
const dialogIds = new WeakMap();
|
|
517
|
+
let dialogCounter = 0;
|
|
518
|
+
function dialogKey(d) {
|
|
519
|
+
if (!dialogIds.has(d))
|
|
520
|
+
dialogIds.set(d, dialogCounter++);
|
|
521
|
+
return dialogIds.get(d);
|
|
522
|
+
}
|
|
523
|
+
const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
524
|
+
function Spinner({ label, since }) {
|
|
525
|
+
const [now, setNow] = useState(Date.now());
|
|
526
|
+
useEffect(() => {
|
|
527
|
+
const t = setInterval(() => setNow(Date.now()), 100);
|
|
528
|
+
return () => clearInterval(t);
|
|
529
|
+
}, []);
|
|
530
|
+
const seconds = Math.floor((now - since) / 1000);
|
|
531
|
+
return (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: "cyan", children: [FRAMES[Math.floor(now / 100) % FRAMES.length], " "] }), _jsxs(Text, { children: [label, "\u2026 "] }), _jsxs(Text, { dimColor: true, children: ["(", seconds, "s \u00B7 esc to interrupt)"] })] }) }));
|
|
532
|
+
}
|
|
533
|
+
/** 在 width 列里放下尽量多的内容(保持原来的顺序) */
|
|
534
|
+
export function fitSegments(segments, width) {
|
|
535
|
+
const kept = segments.map((s) => ({ ...s }));
|
|
536
|
+
const total = () => kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
|
|
537
|
+
const steps = kept
|
|
538
|
+
.flatMap((s) => [
|
|
539
|
+
...(s.short !== undefined && s.shortAt !== undefined
|
|
540
|
+
? [{ s, at: s.shortAt, drop: false }]
|
|
541
|
+
: []),
|
|
542
|
+
...(s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []),
|
|
543
|
+
])
|
|
544
|
+
.sort((a, b) => b.at - a.at);
|
|
545
|
+
for (const { s, drop } of steps) {
|
|
546
|
+
if (total() <= width)
|
|
547
|
+
break;
|
|
548
|
+
if (drop)
|
|
549
|
+
kept.splice(kept.indexOf(s), 1);
|
|
550
|
+
else
|
|
551
|
+
s.text = s.short;
|
|
552
|
+
}
|
|
553
|
+
return kept;
|
|
554
|
+
}
|
|
555
|
+
function StatusBar({ status, width }) {
|
|
556
|
+
const ctx = status.context;
|
|
557
|
+
const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
|
|
558
|
+
/** 离自动压缩还有多远:到阈值的 85% 起变黄 */
|
|
559
|
+
const nearCompact = ctx?.compactAt ? ctx.used >= ctx.compactAt * 0.85 : pct >= 80;
|
|
560
|
+
const modeColor = status.mode === "yolo"
|
|
561
|
+
? "red"
|
|
562
|
+
: status.mode === "auto-edit"
|
|
563
|
+
? "yellow"
|
|
564
|
+
: status.mode === "readonly"
|
|
565
|
+
? "blue"
|
|
566
|
+
: status.mode === "plan"
|
|
567
|
+
? "magenta"
|
|
568
|
+
: "green";
|
|
569
|
+
const speed = status.speed;
|
|
570
|
+
// 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
|
|
571
|
+
const segments = [
|
|
572
|
+
{
|
|
573
|
+
text: `${status.mode} (shift+tab)`,
|
|
574
|
+
short: status.mode,
|
|
575
|
+
shortAt: 6,
|
|
576
|
+
color: modeColor,
|
|
577
|
+
},
|
|
578
|
+
ctx
|
|
579
|
+
? {
|
|
580
|
+
text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)${ctx.compactAt ? `, compacts at ${tokens(ctx.compactAt)}` : ""}`,
|
|
581
|
+
short: `ctx ${pct}%`,
|
|
582
|
+
shortAt: 4,
|
|
583
|
+
color: nearCompact ? "yellow" : undefined,
|
|
584
|
+
dim: !nearCompact,
|
|
585
|
+
}
|
|
586
|
+
: { text: "ctx —", dim: true },
|
|
587
|
+
...(speed
|
|
588
|
+
? [
|
|
589
|
+
{
|
|
590
|
+
text: `${speed.live ? "~" : ""}${speed.tps >= 100 ? Math.round(speed.tps) : speed.tps.toFixed(1)} tok/s`,
|
|
591
|
+
dropAt: 3,
|
|
592
|
+
dim: true,
|
|
593
|
+
},
|
|
594
|
+
]
|
|
595
|
+
: []),
|
|
596
|
+
...(status.cache !== undefined
|
|
597
|
+
? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }]
|
|
598
|
+
: []),
|
|
599
|
+
...(status.spent
|
|
600
|
+
? [
|
|
601
|
+
{
|
|
602
|
+
text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
|
|
603
|
+
short: `${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
|
|
604
|
+
shortAt: 8,
|
|
605
|
+
dropAt: 5,
|
|
606
|
+
dim: true,
|
|
607
|
+
},
|
|
608
|
+
]
|
|
609
|
+
: []),
|
|
610
|
+
{
|
|
611
|
+
text: "PgUp/PgDn scroll · click ▸ to expand · shift+drag to select",
|
|
612
|
+
short: "click ▸ to expand",
|
|
613
|
+
shortAt: 10,
|
|
614
|
+
dropAt: 9,
|
|
615
|
+
dim: true,
|
|
616
|
+
},
|
|
617
|
+
];
|
|
618
|
+
const shown = fitSegments(segments, width);
|
|
619
|
+
return (_jsx(Box, { paddingX: 1, children: _jsx(Text, { wrap: "truncate-end", children: shown.map((s, i) => (_jsxs(Text, { children: [i ? _jsx(Text, { dimColor: true, children: " \u00B7 " }) : null, _jsx(Text, { color: s.color, dimColor: s.dim, children: s.text })] }, i))) }) }));
|
|
620
|
+
}
|
|
621
|
+
/** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
|
|
622
|
+
function Hint({ variants, width }) {
|
|
623
|
+
const text = variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1);
|
|
624
|
+
return (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: text }));
|
|
625
|
+
}
|
|
626
|
+
const tokens = (n) => n >= 1_000_000
|
|
627
|
+
? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`
|
|
628
|
+
: n >= 1000
|
|
629
|
+
? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k`
|
|
630
|
+
: String(n);
|
|
631
|
+
/**
|
|
632
|
+
* 同一块输入里的多个按键(按住退格、输入很快时终端会合并)由 Ink 连续交给处理函数,中间不重新渲染,
|
|
633
|
+
* 处理函数里读 useState 的值会是旧的,后面的按键就丢了。这里的值放在 ref 里同步更新:
|
|
634
|
+
* get() 总是最新的,set() 之后安排一次重画(同一块里的多次 set 合并成一次)
|
|
635
|
+
*/
|
|
636
|
+
function useLive(initial) {
|
|
637
|
+
const ref = useRef(initial);
|
|
638
|
+
const [, rerender] = useReducer((n) => n + 1, 0);
|
|
639
|
+
return [
|
|
640
|
+
() => ref.current,
|
|
641
|
+
(v) => {
|
|
642
|
+
ref.current = v;
|
|
643
|
+
rerender();
|
|
644
|
+
},
|
|
645
|
+
];
|
|
646
|
+
}
|
|
647
|
+
/** 编辑按键的通用处理;返回编辑后的状态,不是编辑键时返回 undefined */
|
|
648
|
+
function editKey(s, input, key) {
|
|
649
|
+
if (key.leftArrow)
|
|
650
|
+
return edit.left(s);
|
|
651
|
+
if (key.rightArrow)
|
|
652
|
+
return edit.right(s);
|
|
653
|
+
if (key.home || (key.ctrl && input === "a"))
|
|
654
|
+
return edit.home(s);
|
|
655
|
+
if (key.end || (key.ctrl && input === "e"))
|
|
656
|
+
return edit.end(s);
|
|
657
|
+
if (key.backspace)
|
|
658
|
+
return key.meta ? edit.deleteWord(s) : edit.backspace(s);
|
|
659
|
+
if (key.delete || (key.ctrl && input === "d"))
|
|
660
|
+
return edit.del(s);
|
|
661
|
+
if (key.ctrl && input === "w")
|
|
662
|
+
return edit.deleteWord(s);
|
|
663
|
+
if (key.ctrl && input === "u")
|
|
664
|
+
return edit.killBefore(s);
|
|
665
|
+
if (key.ctrl && input === "k")
|
|
666
|
+
return edit.killAfter(s);
|
|
667
|
+
if (key.ctrl ||
|
|
668
|
+
key.meta ||
|
|
669
|
+
key.escape ||
|
|
670
|
+
key.return ||
|
|
671
|
+
key.tab ||
|
|
672
|
+
key.upArrow ||
|
|
673
|
+
key.downArrow ||
|
|
674
|
+
key.pageUp ||
|
|
675
|
+
key.pageDown)
|
|
676
|
+
return undefined;
|
|
677
|
+
// 鼠标事件由 App 处理
|
|
678
|
+
if (MOUSE.test(input))
|
|
679
|
+
return undefined;
|
|
680
|
+
// 其余是普通输入;快速输入时一次可能有多个字符
|
|
681
|
+
const text = input
|
|
682
|
+
.replace(/\r\n?/g, "\n")
|
|
683
|
+
.replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
|
|
684
|
+
return text ? edit.insert(s, text) : undefined;
|
|
685
|
+
}
|
|
686
|
+
/** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
|
|
687
|
+
function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, }) {
|
|
688
|
+
const ref = useRef(null);
|
|
689
|
+
// 只用来在布局变化后重画一次、重新计算光标位置;它给的是相对父元素的坐标,光标要的是相对整个输出
|
|
690
|
+
const metrics = useBoxMetrics(ref);
|
|
691
|
+
const { setCursorPosition } = useCursor();
|
|
692
|
+
const shown = mask ? "•".repeat([...state.value].length) : state.value;
|
|
693
|
+
const cursor = mask
|
|
694
|
+
? [...state.value.slice(0, state.cursor)].length
|
|
695
|
+
: state.cursor;
|
|
696
|
+
const all = layout(shown, cursor, width - prefix.length);
|
|
697
|
+
const { col } = all;
|
|
698
|
+
// 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
|
|
699
|
+
const first = Math.max(0, Math.min(all.row - maxRows + 1, all.rows.length - maxRows));
|
|
700
|
+
const rows = all.rows.slice(first, first + maxRows);
|
|
701
|
+
const row = all.row - first;
|
|
702
|
+
// 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
|
|
703
|
+
// 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
|
|
704
|
+
// 这里用的是上一次的布局;输入框挪了位置时 useBoxMetrics 会再触发一次渲染来纠正
|
|
705
|
+
const at = active && metrics.hasMeasured && ref.current
|
|
706
|
+
? origin(ref.current)
|
|
707
|
+
: undefined;
|
|
708
|
+
setCursorPosition(at && { x: at.x + prefix.length + col, y: at.y + row });
|
|
709
|
+
return (_jsx(Box, { ref: ref, flexDirection: "column", children: state.value === "" && placeholder ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", children: prefix }), _jsx(Text, { dimColor: true, children: placeholder })] })) : (rows.map((r, i) => (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", children: first + i === 0
|
|
710
|
+
? prefix
|
|
711
|
+
: i === 0
|
|
712
|
+
? "↑".padEnd(prefix.length)
|
|
713
|
+
: " ".repeat(prefix.length) }), r] }, first + i)))) }));
|
|
714
|
+
}
|
|
715
|
+
/** 元素相对整个动态输出(Static 之外的部分)左上角的位置 */
|
|
716
|
+
function origin(node) {
|
|
717
|
+
let x = 0;
|
|
718
|
+
let y = 0;
|
|
719
|
+
for (let n = node; n?.yogaNode; n = n.parentNode) {
|
|
720
|
+
x += n.yogaNode.getComputedLeft();
|
|
721
|
+
y += n.yogaNode.getComputedTop();
|
|
722
|
+
}
|
|
723
|
+
return { x, y };
|
|
724
|
+
}
|
|
725
|
+
function Prompt({ commands, handlers, history: initial, busy, active, onSubmit, }) {
|
|
726
|
+
const [current, setState] = useLive(empty);
|
|
727
|
+
const [getSelected, setSelected] = useLive(0);
|
|
728
|
+
const [getNotice, setNotice] = useLive(undefined);
|
|
729
|
+
const history = useRef(initial);
|
|
730
|
+
/** 正在看的历史条目;-1 表示当前输入 */
|
|
731
|
+
const browsing = useRef(-1);
|
|
732
|
+
const draft = useRef("");
|
|
733
|
+
const lastCtrlC = useRef(0);
|
|
734
|
+
const { columns, rows } = useScreenSize();
|
|
735
|
+
/** 补全菜单、搜索结果最多显示几项;输入框最多几行 */
|
|
736
|
+
const menuRows = roomFor(rows, MENTION_ROWS);
|
|
737
|
+
const inputRows = roomFor(rows, 10);
|
|
738
|
+
const hintWidth = Math.max(10, columns - 3);
|
|
739
|
+
// @ 引用补全用的路径;排好的结果按(路径表,查询)缓存,按键处理和渲染都要用时不重复排
|
|
740
|
+
const [getPaths, setPaths] = useLive([]);
|
|
741
|
+
const ranked = useRef(undefined);
|
|
742
|
+
// Ctrl+R 搜索历史:结果新的在前,index 是选中的那条
|
|
743
|
+
const [getSearch, setSearch] = useLive(undefined);
|
|
744
|
+
const usageOf = (c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`;
|
|
745
|
+
const column = Math.max(...commands.map((c) => usageOf(c).length)) + 2;
|
|
746
|
+
/** 由最新的输入算出补全菜单和搜索结果;渲染和按键处理都用它 */
|
|
747
|
+
const derive = () => {
|
|
748
|
+
const state = current();
|
|
749
|
+
const selected = getSelected();
|
|
750
|
+
const search = getSearch();
|
|
751
|
+
// 翻到的历史条目原样未改时不弹补全菜单,否则菜单会占住 ↑/↓,翻不过 /命令 这样的条目
|
|
752
|
+
const recalled = browsing.current >= 0 &&
|
|
753
|
+
state.value ===
|
|
754
|
+
history.current[history.current.length - 1 - browsing.current];
|
|
755
|
+
const naming = !recalled && state.value.startsWith("/") && !/\s/.test(state.value);
|
|
756
|
+
const matches = naming
|
|
757
|
+
? commands.filter((c) => `/${c.name}`.startsWith(state.value))
|
|
758
|
+
: [];
|
|
759
|
+
const pick = matches[Math.min(selected, matches.length - 1)];
|
|
760
|
+
// @ 引用:光标处正在输入的路径和补全候选
|
|
761
|
+
const mention = naming || recalled ? undefined : mentionAt(state.value, state.cursor);
|
|
762
|
+
let found = [];
|
|
763
|
+
if (mention) {
|
|
764
|
+
const paths = getPaths();
|
|
765
|
+
const r = ranked.current;
|
|
766
|
+
found =
|
|
767
|
+
r && r.paths === paths && r.query === mention.query
|
|
768
|
+
? r.result
|
|
769
|
+
: rankPaths(paths, mention.query, MENTION_ROWS);
|
|
770
|
+
ranked.current = { paths, query: mention.query, result: found };
|
|
771
|
+
}
|
|
772
|
+
const file = found[Math.min(selected, found.length - 1)];
|
|
773
|
+
const menu = matches.length || found.length;
|
|
774
|
+
const results = search
|
|
775
|
+
? history.current
|
|
776
|
+
.toReversed()
|
|
777
|
+
.filter((h) => h.toLowerCase().includes(search.query.toLowerCase()))
|
|
778
|
+
: [];
|
|
779
|
+
const hit = search
|
|
780
|
+
? Math.max(0, Math.min(search.index, results.length - 1))
|
|
781
|
+
: 0;
|
|
782
|
+
return {
|
|
783
|
+
state,
|
|
784
|
+
selected,
|
|
785
|
+
search,
|
|
786
|
+
matches,
|
|
787
|
+
pick,
|
|
788
|
+
mention,
|
|
789
|
+
found,
|
|
790
|
+
file,
|
|
791
|
+
menu,
|
|
792
|
+
results,
|
|
793
|
+
hit,
|
|
794
|
+
};
|
|
795
|
+
};
|
|
796
|
+
const { state, search, matches, pick, mention, found, file, results, hit } = derive();
|
|
797
|
+
const notice = getNotice();
|
|
798
|
+
const mentioning = mention !== undefined;
|
|
799
|
+
// 每次开始输入一个新的 @ 引用时重新取一次:文件可能已经变了
|
|
800
|
+
useEffect(() => {
|
|
801
|
+
if (!mentioning || !handlers.files)
|
|
802
|
+
return;
|
|
803
|
+
let live = true;
|
|
804
|
+
handlers.files().then((p) => void (live && setPaths(p)), () => { });
|
|
805
|
+
return () => {
|
|
806
|
+
live = false;
|
|
807
|
+
};
|
|
808
|
+
}, [mentioning]);
|
|
809
|
+
// 结果多时只显示选中项附近的几条
|
|
810
|
+
const first = around(hit, results.length, menuRows);
|
|
811
|
+
const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);
|
|
812
|
+
const firstFound = around(Math.max(0, found.indexOf(file)), found.length, menuRows);
|
|
813
|
+
const set = (s) => {
|
|
814
|
+
setState(s);
|
|
815
|
+
setSelected(0);
|
|
816
|
+
setNotice(undefined);
|
|
817
|
+
};
|
|
818
|
+
const submit = (text) => {
|
|
819
|
+
if (!text.trim())
|
|
820
|
+
return;
|
|
821
|
+
history.current = [
|
|
822
|
+
...history.current.filter((h) => h !== text),
|
|
823
|
+
text,
|
|
824
|
+
].slice(-100);
|
|
825
|
+
browsing.current = -1;
|
|
826
|
+
set(empty);
|
|
827
|
+
onSubmit();
|
|
828
|
+
handlers.submit(text);
|
|
829
|
+
};
|
|
830
|
+
/** 用选中的路径替换正在输入的 @ 引用;目录不加空格,接着补全里面的文件 */
|
|
831
|
+
const complete = (p) => {
|
|
832
|
+
const { state, mention } = derive();
|
|
833
|
+
const text = mentionText(p) + (p.endsWith("/") ? "" : " ");
|
|
834
|
+
set({
|
|
835
|
+
value: state.value.slice(0, mention.start) +
|
|
836
|
+
text +
|
|
837
|
+
state.value.slice(state.cursor),
|
|
838
|
+
cursor: mention.start + text.length,
|
|
839
|
+
});
|
|
840
|
+
};
|
|
841
|
+
const recall = (i) => {
|
|
842
|
+
browsing.current = i;
|
|
843
|
+
const value = i === -1
|
|
844
|
+
? draft.current
|
|
845
|
+
: history.current[history.current.length - 1 - i];
|
|
846
|
+
set({ value, cursor: value.length });
|
|
847
|
+
};
|
|
848
|
+
usePaste((text) => {
|
|
849
|
+
const search = getSearch();
|
|
850
|
+
if (search)
|
|
851
|
+
setSearch({
|
|
852
|
+
query: search.query + text.replace(/\s+/g, " "),
|
|
853
|
+
index: 0,
|
|
854
|
+
});
|
|
855
|
+
else
|
|
856
|
+
set(edit.insert(current(), text.replace(/\r\n?/g, "\n")));
|
|
857
|
+
}, { isActive: active });
|
|
858
|
+
/** 搜索时的按键:上下(或再按 Ctrl+R)换一条,回车/Tab 放进输入框接着改,Esc 退出 */
|
|
859
|
+
const searchKey = (s, input, key) => {
|
|
860
|
+
const { results, hit } = derive();
|
|
861
|
+
if (key.escape || (key.ctrl && (input === "c" || input === "g")))
|
|
862
|
+
return setSearch(undefined);
|
|
863
|
+
if (key.return || key.tab) {
|
|
864
|
+
setSearch(undefined);
|
|
865
|
+
const picked = results[hit];
|
|
866
|
+
if (picked !== undefined) {
|
|
867
|
+
browsing.current = -1;
|
|
868
|
+
set({ value: picked, cursor: picked.length });
|
|
869
|
+
}
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
if (key.upArrow || (key.ctrl && input === "r"))
|
|
873
|
+
return setSearch({
|
|
874
|
+
...s,
|
|
875
|
+
index: Math.min(hit + 1, Math.max(0, results.length - 1)),
|
|
876
|
+
});
|
|
877
|
+
if (key.downArrow)
|
|
878
|
+
return setSearch({ ...s, index: Math.max(0, hit - 1) });
|
|
879
|
+
if (key.backspace || key.delete)
|
|
880
|
+
return setSearch({ query: [...s.query].slice(0, -1).join(""), index: 0 });
|
|
881
|
+
if (key.ctrl && input === "u")
|
|
882
|
+
return setSearch({ query: "", index: 0 });
|
|
883
|
+
if (key.ctrl || key.meta || MOUSE.test(input))
|
|
884
|
+
return;
|
|
885
|
+
const text = input.replace(/[\x00-\x1f\x7f]/g, "");
|
|
886
|
+
if (text)
|
|
887
|
+
setSearch({ query: s.query + text, index: 0 });
|
|
888
|
+
};
|
|
889
|
+
useInput((input, key) => {
|
|
890
|
+
const search = getSearch();
|
|
891
|
+
if (search)
|
|
892
|
+
return searchKey(search, input, key);
|
|
893
|
+
const state = current();
|
|
894
|
+
if (key.ctrl && input === "r")
|
|
895
|
+
return history.current.length
|
|
896
|
+
? setSearch({ query: "", index: 0 })
|
|
897
|
+
: undefined;
|
|
898
|
+
if (key.ctrl && input === "c") {
|
|
899
|
+
if (busy)
|
|
900
|
+
return handlers.interrupt();
|
|
901
|
+
if (state.value)
|
|
902
|
+
return set(empty);
|
|
903
|
+
if (Date.now() - lastCtrlC.current < 2000)
|
|
904
|
+
return handlers.exit();
|
|
905
|
+
lastCtrlC.current = Date.now();
|
|
906
|
+
return setNotice("Press Ctrl+C again to exit");
|
|
907
|
+
}
|
|
908
|
+
if (key.escape) {
|
|
909
|
+
if (busy)
|
|
910
|
+
return handlers.interrupt();
|
|
911
|
+
return set(empty);
|
|
912
|
+
}
|
|
913
|
+
// 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
|
|
914
|
+
if (!key.ctrl &&
|
|
915
|
+
!key.meta &&
|
|
916
|
+
input.length > 1 &&
|
|
917
|
+
input.indexOf("\r") === input.length - 1) {
|
|
918
|
+
return submit(edit.insert(state, input.slice(0, -1)).value.trim());
|
|
919
|
+
}
|
|
920
|
+
if (key.return) {
|
|
921
|
+
// 行尾的 \ 加回车换行;Alt+Enter 也换行
|
|
922
|
+
if (key.meta)
|
|
923
|
+
return set(edit.insert(state, "\n"));
|
|
924
|
+
if (state.value.slice(0, state.cursor).endsWith("\\"))
|
|
925
|
+
return set(edit.insert(edit.backspace(state), "\n"));
|
|
926
|
+
const { pick, file } = derive();
|
|
927
|
+
if (pick && state.value !== `/${pick.name}`)
|
|
928
|
+
return submit(`/${pick.name}`);
|
|
929
|
+
if (file)
|
|
930
|
+
return complete(file);
|
|
931
|
+
return submit(state.value.trim());
|
|
932
|
+
}
|
|
933
|
+
if (key.tab && key.shift)
|
|
934
|
+
return handlers.cycleMode?.();
|
|
935
|
+
if (key.tab) {
|
|
936
|
+
const { pick, file } = derive();
|
|
937
|
+
if (pick)
|
|
938
|
+
set({
|
|
939
|
+
value: `/${pick.name}${pick.args ? " " : ""}`,
|
|
940
|
+
cursor: pick.name.length + 1 + (pick.args ? 1 : 0),
|
|
941
|
+
});
|
|
942
|
+
else if (file)
|
|
943
|
+
complete(file);
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
if (key.upArrow) {
|
|
947
|
+
const { menu, selected } = derive();
|
|
948
|
+
if (menu)
|
|
949
|
+
return setSelected((selected - 1 + menu) % menu);
|
|
950
|
+
if (!edit.onFirstLine(state))
|
|
951
|
+
return setState(edit.up(state));
|
|
952
|
+
if (browsing.current + 1 < history.current.length) {
|
|
953
|
+
if (browsing.current === -1)
|
|
954
|
+
draft.current = state.value;
|
|
955
|
+
recall(browsing.current + 1);
|
|
956
|
+
}
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (key.downArrow) {
|
|
960
|
+
const { menu, selected } = derive();
|
|
961
|
+
if (menu)
|
|
962
|
+
return setSelected((selected + 1) % menu);
|
|
963
|
+
if (!edit.onLastLine(state))
|
|
964
|
+
return setState(edit.down(state));
|
|
965
|
+
if (browsing.current >= 0)
|
|
966
|
+
recall(browsing.current - 1);
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
const next = editKey(state, input, key);
|
|
970
|
+
if (next)
|
|
971
|
+
set(next);
|
|
972
|
+
}, { isActive: active });
|
|
973
|
+
// 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
|
|
974
|
+
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none", children: [_jsx(Box, { borderStyle: "round", borderColor: busy ? "gray" : "cyan", paddingX: 1, children: search ? (_jsx(EditableText, { state: { value: search.query, cursor: search.query.length }, width: Math.max(10, columns - 5), prefix: "search history\u203A ", placeholder: "type to filter", active: active, maxRows: inputRows })) : (_jsx(EditableText, { state: state, width: Math.max(10, columns - 5), prefix: "\u203A ", placeholder: busy
|
|
975
|
+
? "Type to queue a message · esc to interrupt"
|
|
976
|
+
: columns >= 70
|
|
977
|
+
? "Message jade · / commands · @ files · ↑ or ctrl+r for history"
|
|
978
|
+
: "Message jade · / commands · @ files", active: active, maxRows: inputRows })) }), search ? (_jsxs(Box, { flexDirection: "column", paddingX: 2, children: [results.length ? (results.slice(first, first + menuRows).map((h, i) => {
|
|
979
|
+
const on = first + i === hit;
|
|
980
|
+
return (_jsxs(Text, { wrap: "truncate-end", color: on ? "cyan" : undefined, bold: on, children: [on ? "❯ " : " ", h.replace(/\s*\n\s*/g, " ⏎ ")] }, first + i));
|
|
981
|
+
})) : (_jsx(Text, { dimColor: true, children: " no match" })), _jsx(Hint, { width: hintWidth, variants: [
|
|
982
|
+
" ↑↓ or ctrl+r select · enter/tab put in the input · esc cancel",
|
|
983
|
+
" ↑↓ select · enter use · esc cancel",
|
|
984
|
+
] })] })) : matches.length ? (_jsxs(Box, { flexDirection: "column", paddingX: 2, children: [matches.slice(firstMatch, firstMatch + menuRows).map((c) => {
|
|
985
|
+
const on = c === pick;
|
|
986
|
+
return (_jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: on ? "cyan" : undefined, bold: on, children: [on ? "❯ " : " ", usageOf(c).padEnd(column)] }), _jsx(Text, { dimColor: true, children: c.about })] }, c.name));
|
|
987
|
+
}), _jsx(Hint, { width: hintWidth, variants: [
|
|
988
|
+
` ↑↓ select · enter run · tab complete${matches.length > menuRows ? ` · ${matches.length} commands` : ""}`,
|
|
989
|
+
" ↑↓ · enter run · tab complete",
|
|
990
|
+
] })] })) : found.length ? (_jsxs(Box, { flexDirection: "column", paddingX: 2, children: [found.slice(firstFound, firstFound + menuRows).map((p) => {
|
|
991
|
+
const on = p === file;
|
|
992
|
+
return (_jsxs(Text, { wrap: "truncate-middle", color: on ? "cyan" : p.endsWith("/") ? "blue" : undefined, bold: on, children: [on ? "❯ " : " ", p] }, p));
|
|
993
|
+
}), _jsx(Hint, { width: hintWidth, variants: [
|
|
994
|
+
" ↑↓ select · enter/tab insert the path · the file's content is sent with the message",
|
|
995
|
+
" ↑↓ select · enter/tab insert the path",
|
|
996
|
+
" ↑↓ · enter insert",
|
|
997
|
+
] })] })) : notice ? (_jsxs(Text, { color: "yellow", children: [" ", notice] })) : null] }));
|
|
998
|
+
}
|
|
999
|
+
/** @ 补全最多显示几项 */
|
|
1000
|
+
const MENTION_ROWS = 8;
|
|
1001
|
+
/** 长列表只显示 size 项时,为了让第 selected 项在中间附近,从第几项开始显示 */
|
|
1002
|
+
function around(selected, total, size) {
|
|
1003
|
+
return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
|
|
1004
|
+
}
|
|
1005
|
+
/** 选择框一次最多显示几项 */
|
|
1006
|
+
const VISIBLE = 10;
|
|
1007
|
+
/** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
|
|
1008
|
+
const FILTER_FROM = 10;
|
|
1009
|
+
function SelectDialog({ dialog, }) {
|
|
1010
|
+
const [getSelected, setSelected] = useLive(0);
|
|
1011
|
+
const [getQuery, setQuery] = useLive("");
|
|
1012
|
+
const { rows, columns } = useScreenSize();
|
|
1013
|
+
const filtering = dialog.choices.length > FILTER_FROM;
|
|
1014
|
+
const query = getQuery();
|
|
1015
|
+
/** 筛选后的选项和它们原来的序号 */
|
|
1016
|
+
const filtered = () => {
|
|
1017
|
+
const q = getQuery().toLowerCase();
|
|
1018
|
+
return dialog.choices
|
|
1019
|
+
.map((c, i) => ({ c, i }))
|
|
1020
|
+
.filter(({ c }) => !q || `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(q));
|
|
1021
|
+
};
|
|
1022
|
+
const items = filtered();
|
|
1023
|
+
const n = items.length;
|
|
1024
|
+
const selected = Math.min(getSelected(), Math.max(0, n - 1));
|
|
1025
|
+
// 终端矮时少显示几项,加上预览一起不超过终端的高度
|
|
1026
|
+
const visible = roomFor(rows, VISIBLE);
|
|
1027
|
+
// 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画
|
|
1028
|
+
const lines = dialog.body?.split("\n") ?? [];
|
|
1029
|
+
const room = Math.max(3, rows - Math.min(n, visible) - 16);
|
|
1030
|
+
const body = lines.length > room
|
|
1031
|
+
? [
|
|
1032
|
+
...lines.slice(0, room),
|
|
1033
|
+
dim(`… ${lines.length - room} more lines`),
|
|
1034
|
+
].join("\n")
|
|
1035
|
+
: dialog.body;
|
|
1036
|
+
useInput((input, key) => {
|
|
1037
|
+
const items = filtered();
|
|
1038
|
+
const n = items.length;
|
|
1039
|
+
const selected = Math.min(getSelected(), Math.max(0, n - 1));
|
|
1040
|
+
if (key.upArrow || (!filtering && input === "k"))
|
|
1041
|
+
return n && setSelected((selected - 1 + n) % n);
|
|
1042
|
+
if (key.downArrow || (!filtering && input === "j"))
|
|
1043
|
+
return n && setSelected((selected + 1) % n);
|
|
1044
|
+
if (key.return) {
|
|
1045
|
+
if (n)
|
|
1046
|
+
dialog.resolve(items[selected].c.value);
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
if (key.escape && filtering && getQuery()) {
|
|
1050
|
+
setQuery("");
|
|
1051
|
+
return setSelected(0);
|
|
1052
|
+
}
|
|
1053
|
+
if (key.escape || (key.ctrl && input === "c"))
|
|
1054
|
+
return dialog.resolve(undefined);
|
|
1055
|
+
if (key.pageDown)
|
|
1056
|
+
return setSelected(Math.min(n - 1, selected + visible));
|
|
1057
|
+
if (key.pageUp)
|
|
1058
|
+
return setSelected(Math.max(0, selected - visible));
|
|
1059
|
+
if (filtering) {
|
|
1060
|
+
if (key.backspace || key.delete) {
|
|
1061
|
+
setQuery([...getQuery()].slice(0, -1).join(""));
|
|
1062
|
+
return setSelected(0);
|
|
1063
|
+
}
|
|
1064
|
+
if (key.ctrl || key.meta || key.tab || MOUSE.test(input))
|
|
1065
|
+
return;
|
|
1066
|
+
const text = input.replace(/[\x00-\x1f\x7f]/g, "");
|
|
1067
|
+
if (text) {
|
|
1068
|
+
setQuery(getQuery() + text);
|
|
1069
|
+
setSelected(0);
|
|
1070
|
+
}
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const digit = Number(input);
|
|
1074
|
+
if (Number.isInteger(digit) && digit >= 1 && digit <= Math.min(n, 9))
|
|
1075
|
+
dialog.resolve(items[digit - 1].c.value);
|
|
1076
|
+
});
|
|
1077
|
+
// 选项多时只显示选中项附近的一段
|
|
1078
|
+
const start = around(selected, n, visible);
|
|
1079
|
+
return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsx(Text, { bold: true, wrap: "truncate-end", children: dialog.title }), body ? _jsx(Text, { children: body }) : null, filtering ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: "cyan", children: "filter\u203A " }), query ? (_jsx(Text, { children: query })) : (_jsxs(Text, { dimColor: true, children: ["type to filter ", dialog.choices.length, " items"] }))] })) : null, _jsxs(Box, { flexDirection: "column", marginTop: filtering ? 0 : 1, children: [start > 0 ? _jsxs(Text, { dimColor: true, children: [" \u2191 ", start, " more"] }) : null, n === 0 ? _jsx(Text, { dimColor: true, children: " no match" }) : null, items.slice(start, start + visible).map(({ c, i }, j) => {
|
|
1080
|
+
const on = start + j === selected;
|
|
1081
|
+
return (_jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: on ? "cyan" : undefined, bold: on, children: [on ? "❯ " : " ", filtering ? "" : `${i + 1}. `, c.label] }), c.hint ? _jsxs(Text, { dimColor: true, children: [" ", c.hint] }) : null] }, i));
|
|
1082
|
+
}), start + visible < n ? (_jsxs(Text, { dimColor: true, children: [" \u2193 ", n - start - visible, " more"] })) : null] }), _jsx(Hint, { width: Math.max(10, columns - 4), variants: filtering
|
|
1083
|
+
? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"]
|
|
1084
|
+
: ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"] })] }));
|
|
1085
|
+
}
|
|
1086
|
+
function InputDialog({ dialog, }) {
|
|
1087
|
+
const initial = dialog.initial ?? "";
|
|
1088
|
+
const [current, setState] = useLive({
|
|
1089
|
+
value: initial,
|
|
1090
|
+
cursor: initial.length,
|
|
1091
|
+
});
|
|
1092
|
+
const state = current();
|
|
1093
|
+
const { columns } = useScreenSize();
|
|
1094
|
+
usePaste((text) => setState(edit.insert(current(), text.replace(/\r?\n/g, ""))));
|
|
1095
|
+
useInput((input, key) => {
|
|
1096
|
+
const state = current();
|
|
1097
|
+
if (key.return)
|
|
1098
|
+
return dialog.resolve(state.value.trim());
|
|
1099
|
+
if (key.escape || (key.ctrl && input === "c"))
|
|
1100
|
+
return dialog.resolve(undefined);
|
|
1101
|
+
const next = editKey(state, input, key);
|
|
1102
|
+
if (next)
|
|
1103
|
+
setState(next);
|
|
1104
|
+
});
|
|
1105
|
+
return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsx(Text, { bold: true, children: dialog.title }), _jsx(EditableText, { state: state, width: Math.max(10, columns - 6), prefix: "\u203A ", mask: dialog.mask, placeholder: dialog.placeholder, active: true }), _jsx(Text, { dimColor: true, children: "enter confirm \u00B7 esc cancel" })] }));
|
|
1106
|
+
}
|
|
1107
|
+
//# sourceMappingURL=tui.js.map
|