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