@uncarved/jade 0.2.0 → 0.3.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.
Files changed (224) hide show
  1. package/README.md +277 -0
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +15 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +28 -5
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +6 -4
  29. package/plugins/approval/index.ts +246 -84
  30. package/plugins/approval/plugin.json +5 -1
  31. package/plugins/approval/policy.ts +27 -6
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +15 -4
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +110 -17
  48. package/plugins/fs/grep.ts +41 -11
  49. package/plugins/fs/index.ts +9 -7
  50. package/plugins/fs/renderers.ts +1 -1
  51. package/plugins/hooks/index.ts +152 -0
  52. package/plugins/hooks/plugin.json +14 -0
  53. package/plugins/keys/index.ts +2 -18
  54. package/plugins/mcp/index.ts +40 -12
  55. package/plugins/mcp/install.ts +139 -0
  56. package/plugins/mcp/mcp.ts +2 -1
  57. package/plugins/mcp/plugin.json +1 -1
  58. package/plugins/mcp/project.ts +37 -1
  59. package/plugins/memory/index.ts +4 -9
  60. package/plugins/memory/plugin.json +1 -1
  61. package/plugins/mentions/index.ts +33 -13
  62. package/plugins/models/configure.ts +258 -150
  63. package/plugins/models/context.ts +2 -2
  64. package/plugins/models/index.ts +50 -42
  65. package/plugins/models/plugin.json +1 -1
  66. package/plugins/models/provider.ts +22 -4
  67. package/plugins/models/saved.ts +8 -4
  68. package/plugins/modes/index.ts +2 -17
  69. package/plugins/plugins/index.ts +2 -2
  70. package/plugins/print/index.ts +60 -12
  71. package/plugins/print/plugin.json +1 -0
  72. package/plugins/prompts/index.ts +50 -14
  73. package/plugins/{memory → prompts}/notes.ts +21 -9
  74. package/plugins/prompts/plugin.json +8 -2
  75. package/plugins/prompts/prompts.ts +14 -8
  76. package/plugins/prompts/results.ts +63 -0
  77. package/plugins/prompts/sys.ts +16 -4
  78. package/plugins/renderers/index.ts +2 -43
  79. package/plugins/repeats/index.ts +1 -1
  80. package/plugins/schedule/index.ts +2 -2
  81. package/plugins/scratch/index.ts +2 -3
  82. package/plugins/screenshot/index.ts +26 -13
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/sessions/index.ts +2 -17
  85. package/plugins/shell/index.ts +56 -6
  86. package/plugins/shell/plugin.json +3 -1
  87. package/plugins/shell/renderers.ts +1 -1
  88. package/plugins/shell/service.ts +2 -13
  89. package/plugins/shell/shell.ts +31 -16
  90. package/plugins/skills/index.ts +172 -37
  91. package/plugins/skills/install.ts +212 -0
  92. package/plugins/skills/plugin.json +3 -2
  93. package/plugins/skills/project.ts +38 -1
  94. package/plugins/skills/skills.ts +28 -9
  95. package/plugins/steer/index.ts +142 -0
  96. package/plugins/steer/plugin.json +8 -0
  97. package/plugins/suggest/index.ts +16 -11
  98. package/plugins/suggest/plugin.json +1 -1
  99. package/plugins/task/index.ts +8 -16
  100. package/plugins/task/plugin.json +9 -2
  101. package/plugins/task/subagent.ts +119 -15
  102. package/plugins/todo/index.ts +4 -4
  103. package/plugins/tui/editor.ts +10 -2
  104. package/plugins/tui/frontend.ts +130 -25
  105. package/plugins/tui/index.ts +3 -8
  106. package/plugins/tui/markdown.ts +51 -6
  107. package/plugins/tui/mascot.ts +505 -0
  108. package/plugins/tui/mentions.ts +48 -8
  109. package/plugins/tui/plugin.json +2 -2
  110. package/plugins/tui/screen.ts +6 -0
  111. package/plugins/tui/transcript.ts +22 -3
  112. package/plugins/tui/tui.ts +323 -95
  113. package/plugins/tui/vendor.ts +16 -0
  114. package/plugins/undo/checkpoint.ts +26 -2
  115. package/plugins/undo/index.ts +86 -24
  116. package/plugins/undo/plugin.json +8 -2
  117. package/plugins/undo/snapshot.ts +129 -0
  118. package/plugins/update/index.ts +11 -15
  119. package/plugins/update/plugin.json +2 -1
  120. package/plugins/web/index.ts +2 -5
  121. package/plugins/web/renderers.ts +1 -1
  122. package/plugins/web/web.ts +6 -5
  123. package/plugins-dist/approval/index.js +232 -50
  124. package/plugins-dist/approval/plugin.json +5 -1
  125. package/plugins-dist/approval/policy.js +27 -5
  126. package/plugins-dist/ask/index.js +1 -1
  127. package/plugins-dist/budget/index.js +1 -1
  128. package/plugins-dist/checks/checks.js +2 -1
  129. package/plugins-dist/checks/index.js +1 -1
  130. package/plugins-dist/commands/index.js +1 -1
  131. package/plugins-dist/compact/compact.js +13 -2
  132. package/plugins-dist/compact/index.js +12 -8
  133. package/plugins-dist/continue/index.js +1 -1
  134. package/plugins-dist/cost/index.js +135 -0
  135. package/plugins-dist/cost/plugin.json +16 -0
  136. package/plugins-dist/custom-commands/index.js +86 -0
  137. package/plugins-dist/custom-commands/plugin.json +12 -0
  138. package/plugins-dist/editor/index.js +89 -0
  139. package/plugins-dist/editor/plugin.json +21 -0
  140. package/plugins-dist/fs/fs.js +106 -17
  141. package/plugins-dist/fs/grep.js +40 -12
  142. package/plugins-dist/fs/index.js +8 -5
  143. package/plugins-dist/hooks/index.js +145 -0
  144. package/plugins-dist/hooks/plugin.json +19 -0
  145. package/plugins-dist/keys/index.js +1 -1
  146. package/plugins-dist/mcp/index.js +41 -9
  147. package/plugins-dist/mcp/install.js +160 -0
  148. package/plugins-dist/mcp/mcp.js +2 -1
  149. package/plugins-dist/mcp/plugin.json +2 -1
  150. package/plugins-dist/mcp/project.js +42 -1
  151. package/plugins-dist/memory/index.js +3 -5
  152. package/plugins-dist/memory/plugin.json +1 -1
  153. package/plugins-dist/mentions/index.js +29 -11
  154. package/plugins-dist/models/configure.js +252 -151
  155. package/plugins-dist/models/context.js +2 -2
  156. package/plugins-dist/models/index.js +53 -16
  157. package/plugins-dist/models/plugin.json +1 -1
  158. package/plugins-dist/models/provider.js +4 -2
  159. package/plugins-dist/models/saved.js +9 -4
  160. package/plugins-dist/modes/index.js +1 -1
  161. package/plugins-dist/plugins/index.js +1 -1
  162. package/plugins-dist/print/index.js +62 -9
  163. package/plugins-dist/print/plugin.json +3 -0
  164. package/plugins-dist/prompts/index.js +49 -2
  165. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  166. package/plugins-dist/prompts/plugin.json +8 -2
  167. package/plugins-dist/prompts/prompts.js +13 -8
  168. package/plugins-dist/prompts/results.js +60 -0
  169. package/plugins-dist/prompts/sys.js +15 -3
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +1 -1
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/index.js +25 -11
  175. package/plugins-dist/screenshot/plugin.json +1 -1
  176. package/plugins-dist/sessions/index.js +1 -1
  177. package/plugins-dist/shell/index.js +55 -3
  178. package/plugins-dist/shell/plugin.json +3 -1
  179. package/plugins-dist/shell/shell.js +26 -8
  180. package/plugins-dist/skills/index.js +184 -35
  181. package/plugins-dist/skills/install.js +178 -0
  182. package/plugins-dist/skills/plugin.json +6 -2
  183. package/plugins-dist/skills/project.js +43 -1
  184. package/plugins-dist/skills/skills.js +27 -10
  185. package/plugins-dist/steer/index.js +135 -0
  186. package/plugins-dist/steer/plugin.json +12 -0
  187. package/plugins-dist/suggest/index.js +15 -9
  188. package/plugins-dist/suggest/plugin.json +1 -1
  189. package/plugins-dist/task/index.js +7 -4
  190. package/plugins-dist/task/plugin.json +10 -2
  191. package/plugins-dist/task/subagent.js +106 -15
  192. package/plugins-dist/todo/index.js +3 -3
  193. package/plugins-dist/tui/editor.js +7 -2
  194. package/plugins-dist/tui/frontend.js +135 -18
  195. package/plugins-dist/tui/index.js +2 -1
  196. package/plugins-dist/tui/markdown.js +48 -6
  197. package/plugins-dist/tui/mascot.js +439 -0
  198. package/plugins-dist/tui/mentions.js +44 -6
  199. package/plugins-dist/tui/plugin.json +3 -2
  200. package/plugins-dist/tui/screen.js +2 -0
  201. package/plugins-dist/tui/transcript.js +19 -2
  202. package/plugins-dist/tui/tui.js +303 -83
  203. package/plugins-dist/tui/vendor.js +13822 -0
  204. package/plugins-dist/undo/checkpoint.js +28 -1
  205. package/plugins-dist/undo/index.js +92 -22
  206. package/plugins-dist/undo/plugin.json +10 -3
  207. package/plugins-dist/undo/snapshot.js +111 -0
  208. package/plugins-dist/update/index.js +9 -10
  209. package/plugins-dist/update/plugin.json +4 -1
  210. package/plugins-dist/web/index.js +1 -1
  211. package/plugins-dist/web/web.js +6 -5
  212. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  213. package/sdk/python/jade_plugin.py +8 -0
  214. package/src/api.ts +7 -262
  215. package/src/fetch.ts +18 -16
  216. package/src/host.ts +49 -1
  217. package/src/index.ts +1 -1
  218. package/src/main.ts +25 -6
  219. package/src/remote.ts +2 -0
  220. package/src/session.ts +134 -15
  221. package/src/source.ts +2 -11
  222. package/src/update.ts +16 -10
  223. package/plugins/undo/notes.ts +0 -43
  224. package/plugins-dist/undo/notes.js +0 -36
@@ -4,13 +4,12 @@
4
4
  //
5
5
  // 不用 JSX:插件以 .ts 源码加载,Node 的类型剥离不处理 .tsx,所以组件用 createElement(h)写。
6
6
  import { writeSync } from "node:fs";
7
- import { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize, } from "ink";
8
- import { createContext, createElement as h, useContext, useEffect, useReducer, useRef, useState, useSyncExternalStore, } from "react";
7
+ import { Box, render, Text, useBoxMetrics, useCursor, useInput, usePaste, useWindowSize, createContext, createElement as h, useContext, useEffect, useReducer, useRef, useState, useSyncExternalStore, } from "./vendor.js";
9
8
  import stringWidth from "string-width";
10
- import wrapAnsi from "wrap-ansi";
11
9
  import { mentionAt, mentionText, rankPaths } from "./mentions.js";
12
10
  import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
13
- import { expandTabs, markdownStream } from "./markdown.js";
11
+ import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
12
+ import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
14
13
  import { dim, } from "./screen.js";
15
14
  /**
16
15
  * 界面可用的尺寸:宽度比终端少一列。
@@ -34,8 +33,8 @@ function keySpec(input, key) {
34
33
  }
35
34
  /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
36
35
  const MAX_LINES = 10_000;
37
- /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行。制表符先换成空格:按 0 列算宽度会对不齐、超宽 */
38
- const wrap = (text, width) => wrapAnsi(expandTabs(text), width, { hard: true, trim: false }).split("\n");
36
+ /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行,自动折出来的续行开头带记号(markdown.ts),显示之前用 visibleRow 去掉 */
37
+ const wrap = wrapRows;
39
38
  /** Markdown 排好的一行折成屏幕上的行 */
40
39
  const mdRows = (l, width) => typeof l === "string" ? wrap(l, width) : l.render(width);
41
40
  /** 按宽度截成一行,截掉了内容时以 … 结尾;留出两列给 … 和展开标记 */
@@ -273,14 +272,52 @@ const CURSOR_BLINK = "\x1b[5 q\x1b[?12h";
273
272
  const CURSOR_RESET = "\x1b[0 q";
274
273
  /** 工作超过这么久后结束,或者这时弹出要用户选择的对话框,用户多半去做别的了:提醒一下 */
275
274
  const NOTIFY_AFTER = 10_000;
276
- /** 支持 OSC 9 桌面通知的终端;其他终端只响铃(不认识的 OSC 9 在有的终端里会弹别的东西) */
275
+ /** 支持 OSC 9 桌面通知的终端;其他终端什么都不发(不认识的 OSC 9 在有的终端里会弹别的东西) */
277
276
  const OSC9_TERMINALS = new Set(["iTerm.app", "WezTerm", "ghostty"]);
278
- /** 响铃,支持的终端再发一条桌面通知。JADE_NOTIFY=off 关闭 */
277
+ /**
278
+ * 支持的终端发一条桌面通知。不响铃:铃声在很多终端里(例如 Windows Terminal)是系统的错误提示音,听起来像出错了。
279
+ * JADE_NOTIFY=off 关闭
280
+ */
279
281
  function notifier(stdout, env = process.env) {
280
- if (env.JADE_NOTIFY === "off")
282
+ if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? ""))
281
283
  return () => { };
282
- const osc9 = OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "");
283
- return (message) => stdout.write(osc9 ? `\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07` : "\x07");
284
+ return (message) => stdout.write(`\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
285
+ }
286
+ /** 终端标题里的控制字符换成空格,免得提前结束转义序列 */
287
+ const osc0 = (text) => `\x1b]0;${text.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`;
288
+ /** 先把终端原来的标题存进标题栈(xterm 的 CSI 22 t),退出时取回;不支持的终端(如 Windows Terminal)退出时清空标题,回到默认 */
289
+ const TITLE_PUSH = "\x1b[22;0t";
290
+ const TITLE_POP = `${osc0("")}\x1b[23;0t`;
291
+ /**
292
+ * 让终端标签页标题跟着 jade 的状态走(见 mascot.ts 的 title):空闲时显示标志,运行中转圈,等用户时加感叹号。
293
+ * JADE_TITLE=off 关闭。返回关闭函数,会把标题还原
294
+ */
295
+ function titleBar(stdout, store, env = process.env) {
296
+ if (env.JADE_TITLE === "off")
297
+ return () => { };
298
+ let shown = "";
299
+ const update = () => {
300
+ const s = store.state;
301
+ const now = Date.now();
302
+ const mood = moodOf({ busy: s.busy?.label, asking: s.dialogs.length > 0, doneAt: s.doneAt }, now);
303
+ const dir = s.status.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? s.status.cwd;
304
+ const text = title(mood, dir, now);
305
+ if (text === shown)
306
+ return;
307
+ shown = text;
308
+ stdout.write(osc0(text));
309
+ };
310
+ stdout.write(TITLE_PUSH);
311
+ update();
312
+ const off = store.subscribe(update);
313
+ // 运行中转圈:状态不变时也要按时间换一帧
314
+ const timer = setInterval(() => store.state.busy && update(), 250);
315
+ timer.unref?.();
316
+ return () => {
317
+ off();
318
+ clearInterval(timer);
319
+ stdout.write(TITLE_POP);
320
+ };
284
321
  }
285
322
  export function tuiScreen(opts) {
286
323
  const stdout = opts.io?.stdout ?? process.stdout;
@@ -359,30 +396,38 @@ export function tuiScreen(opts) {
359
396
  });
360
397
  // 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
361
398
  // 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
362
- stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
363
399
  const commands = opts.commands;
364
- const instance = render(h(App, {
365
- store,
366
- copy: (text) => void stdout.write(osc52(text)),
367
- version: opts.version,
368
- commands: typeof commands === "function" ? commands : () => commands,
369
- handlers: opts.handlers,
370
- history: opts.history ?? [],
371
- draft,
372
- }), {
373
- exitOnCtrlC: false,
374
- alternateScreen: true,
375
- // 全屏每帧只重写变化的行
376
- incrementalRendering: true,
377
- ...(opts.io
378
- ? { ...opts.io, interactive: true, patchConsole: false }
379
- : {}),
380
- });
381
- stdout.write(MOUSE_ON + CURSOR_BLINK);
400
+ /** 接管终端、画界面。界面的内容都在 store 里,所以让出终端(suspend)之后可以再画一个新的 */
401
+ const mount = () => {
402
+ stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
403
+ const mounted = render(h(App, {
404
+ store,
405
+ copy: (text) => void stdout.write(osc52(text)),
406
+ version: opts.version,
407
+ commands: typeof commands === "function" ? commands : () => commands,
408
+ handlers: opts.handlers,
409
+ history: opts.history ?? [],
410
+ draft,
411
+ }), {
412
+ exitOnCtrlC: false,
413
+ alternateScreen: true,
414
+ // 全屏每帧只重写变化的行
415
+ incrementalRendering: true,
416
+ ...(opts.io
417
+ ? { ...opts.io, interactive: true, patchConsole: false }
418
+ : {}),
419
+ });
420
+ stdout.write(MOUSE_ON + CURSOR_BLINK);
421
+ return mounted;
422
+ };
423
+ let instance = mount();
424
+ /** 让出终端一次只做一回,后来的排在后面 */
425
+ let yielding = Promise.resolve();
426
+ const closeTitle = titleBar(stdout, store);
382
427
  // 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
383
428
  const restore = () => {
384
429
  try {
385
- writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}\x1b[?1049l\x1b[?25h`);
430
+ writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1b[?1049l\x1b[?25h`);
386
431
  }
387
432
  catch { }
388
433
  };
@@ -451,7 +496,10 @@ export function tuiScreen(opts) {
451
496
  // 稍等一下再提醒:排队的消息接着开始时(马上又 busy)不算结束
452
497
  if (longBusy())
453
498
  doneTimer ??= setTimeout(() => notify("done"), 300);
454
- store.update({ busy: undefined });
499
+ store.update({
500
+ busy: undefined,
501
+ ...(current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}),
502
+ });
455
503
  return;
456
504
  }
457
505
  clearTimeout(doneTimer);
@@ -473,6 +521,32 @@ export function tuiScreen(opts) {
473
521
  },
474
522
  hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, "\n") : undefined }),
475
523
  },
524
+ copy: (text) => void stdout.write(osc52(text)),
525
+ suspend(fn) {
526
+ const run = yielding.then(async () => {
527
+ // 输入框里打了一半的字在组件里,卸载就没了:先记下
528
+ const typed = draft.current?.get();
529
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
530
+ // 卸载时 Ink 退出备用屏幕、关掉 raw mode、不再读 stdin:终端回到普通状态,别的程序可以用
531
+ instance.unmount();
532
+ await instance.waitUntilExit();
533
+ delete draft.current;
534
+ try {
535
+ return await fn();
536
+ }
537
+ finally {
538
+ instance = mount();
539
+ // 等输入框画出来再返回:调用方接着就可能改输入框(编辑器里写好的内容)
540
+ const input = () => draft.current;
541
+ for (let i = 0; i < 100 && !input(); i++)
542
+ await new Promise((r) => setTimeout(r, 10));
543
+ if (typed)
544
+ input()?.apply(() => ({ value: typed, cursor: typed.length }));
545
+ }
546
+ });
547
+ yielding = run.catch(() => { });
548
+ return run;
549
+ },
476
550
  select: (title, choices, o) => {
477
551
  if (longBusy())
478
552
  notify(title);
@@ -502,6 +576,7 @@ export function tuiScreen(opts) {
502
576
  store.update({ live: undefined, busy: undefined, progress: [] }, true);
503
577
  // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
504
578
  await new Promise((r) => setTimeout(r, 50));
579
+ closeTitle();
505
580
  stdout.write(MOUSE_OFF + CURSOR_RESET);
506
581
  instance.unmount();
507
582
  await instance.waitUntilExit();
@@ -573,17 +648,27 @@ function highlight(line, from, to) {
573
648
  }, (seq) => (out += seq + (on ? INVERSE : "")));
574
649
  return out + (on ? INVERSE_OFF : "");
575
650
  }
576
- /** 选中的纯文字:每行去掉行尾空白,用换行连起来(自动折行的地方也是换行) */
577
- function selectedText(s, row) {
651
+ /**
652
+ * 选中的纯文字:每行去掉行尾空白,用换行连起来。自动折行出来的续行接回上一行(补上折行时去掉的空格、
653
+ * 跳过排版加的缩进),所以一行很长的命令复制出来还是一行。row 给的是带续行记号的行
654
+ */
655
+ export function selectedText(s, row) {
578
656
  const lines = [];
579
657
  const { anchor: a, focus: f } = s;
580
- for (let r = Math.min(a.row, f.row); r <= Math.max(a.row, f.row); r++) {
658
+ const first = Math.min(a.row, f.row);
659
+ for (let r = first; r <= Math.max(a.row, f.row); r++) {
581
660
  const [from, to] = selectedCols(s, r);
661
+ const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
582
662
  let text = "";
583
- walk(row(r) ?? "", from, to, (ch, inside) => void (inside && (text += ch)));
584
- lines.push(text.trimEnd());
663
+ // 续行开头的缩进、竖线是排版加的
664
+ walk(line, Math.max(from, soft ? indent : 0), to, (ch, inside) => void (inside && (text += ch)));
665
+ if (soft && r > first)
666
+ lines[lines.length - 1] += " ".repeat(gap) + text;
667
+ // 代码块左边的竖线是排版加的,不是代码的一部分
668
+ else
669
+ lines.push(text.replace(/^┃ ?/, ""));
585
670
  }
586
- return lines.join("\n");
671
+ return lines.map((l) => l.trimEnd()).join("\n");
587
672
  }
588
673
  /** OSC 52:让终端把文字放进系统剪贴板(Windows Terminal、iTerm2、kitty、WezTerm 等支持) */
589
674
  const osc52 = (text) => `\x1b]52;c;${Buffer.from(text, "utf8").toString("base64")}\x07`;
@@ -602,17 +687,32 @@ const roomFor = (rows, max) => Math.max(3, Math.min(max, Math.floor((rows - 10)
602
687
  function App({ store, copy, version, commands, handlers, history, draft, }) {
603
688
  const state = useSyncExternalStore(store.subscribe, store.get);
604
689
  const dialog = state.dialogs[0];
605
- // 运行中每 100ms 整体重画一次,推动转圈动画。不能让 Spinner 自己重画:
690
+ const { columns, rows } = useScreenSize();
691
+ const compact = rows < COMPACT_ROWS;
692
+ // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
606
693
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
607
- const [, tick] = useReducer((n) => n + 1, 0);
694
+ const [ticks, tick] = useReducer((n) => n + 1, 0);
608
695
  const busy = state.busy !== undefined;
609
696
  useEffect(() => {
610
697
  if (!busy)
611
698
  return;
612
- const t = setInterval(tick, 100);
699
+ const t = setInterval(tick, FRAME_MS);
613
700
  return () => clearInterval(t);
614
701
  }, [busy]);
615
- const { columns, rows } = useScreenSize();
702
+ const now = Date.now();
703
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
704
+ const mascot = useRef(undefined);
705
+ mascot.current ??= new Mascot();
706
+ const showBot = !compact && columns >= 50;
707
+ const bot = showBot ? mascot.current.frame(mood, now) : undefined;
708
+ // 不在运行时吉祥物也会眨眼、瞟一眼、从上一个表情缓过来:只在它要动的时候按帧重画,其余时间不画
709
+ const moving = showBot && mascot.current.moving(mood, now);
710
+ useEffect(() => {
711
+ if (busy || !showBot)
712
+ return;
713
+ const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
714
+ return () => clearTimeout(t);
715
+ }, [busy, showBot, ticks, mood, moving, state.doneAt]);
616
716
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
617
717
  const ref = useRef(null);
618
718
  const { height, top } = useBoxMetrics(ref);
@@ -654,8 +754,10 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
654
754
  const [copied, setCopied] = useState();
655
755
  const copiedTimer = useRef(undefined);
656
756
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
657
- const copySelection = (s) => {
658
- const text = selectedText(s, rowAt);
757
+ /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
758
+ const inputPlace = useRef(undefined);
759
+ const copySelection = (s) => copyText(selectedText(s, rowAt));
760
+ const copyText = (text) => {
659
761
  copy(text);
660
762
  clearTimeout(copiedTimer.current);
661
763
  setCopied(`Copied ${[...text].length} characters to the clipboard`);
@@ -697,6 +799,11 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
697
799
  return undefined;
698
800
  return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
699
801
  };
802
+ // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
803
+ const input = inputPlace.current;
804
+ const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
805
+ if ((mouse.button === 64 || mouse.button === 65) && overInput)
806
+ return;
700
807
  if (mouse.button === 64)
701
808
  store.scrollBy(WHEEL_LINES, max);
702
809
  else if (mouse.button === 65)
@@ -751,7 +858,7 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
751
858
  overflowY: "hidden",
752
859
  },
753
860
  // 垫的空白放在外层:里面这层在重画那一帧和平时一样高,对话区的 top(相对父节点)不变,点击换算的行号不会差一行
754
- h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact: rows < COMPACT_ROWS }), h(Box, {
861
+ h(Box, { flexDirection: "column", flexGrow: 1, overflowY: "hidden" }, h(Header, { status: state.status, version, compact, bot }), h(Box, {
755
862
  ref,
756
863
  flexDirection: "column",
757
864
  flexGrow: 1,
@@ -759,7 +866,9 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
759
866
  flexBasis: 0,
760
867
  overflowY: "hidden",
761
868
  paddingX: 1,
762
- }, shown.map((l, i) => {
869
+ }, shown.map((raw, i) => {
870
+ // 续行的记号不显示
871
+ const l = visibleRow(raw);
763
872
  const cols = selection && selectedCols(selection, start + i);
764
873
  return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
765
874
  }), scrolled
@@ -780,19 +889,17 @@ function App({ store, copy, version, commands, handlers, history, draft, }) {
780
889
  active: !dialog,
781
890
  onSubmit: () => store.scrollBy(-max, max),
782
891
  flash: copied,
892
+ place: inputPlace,
893
+ onCopy: copyText,
783
894
  }), h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) })))));
784
895
  }
785
- const JADE = "#00a86b";
786
- const SHINE = "#b6f2d4";
787
896
  /**
788
- * 标题左边的吉祥物:一个玉做的团子,用半格字符画的像素图,三行高,正好和右边三行文字并排。
789
- * 每个字符上下两个像素;眼睛是玉上挖空的两格,左上角一点高光让它看起来像玉
897
+ * 标题左边的吉祥物(见 mascot.ts):玉做的团子,按 mood 换表情和动画,三行高,正好和右边三行文字并排
790
898
  */
791
- function Bot() {
792
- return h(Box, { flexDirection: "column", flexShrink: 0, marginRight: 2 }, h(Text, { color: JADE }, " ▄", h(Text, { color: SHINE, backgroundColor: JADE }, "▄"), "████▄"), h(Text, { color: JADE }, "██ ███ ██"), h(Text, { color: JADE }, "▀███████▀"));
899
+ function Bot({ pixels }) {
900
+ return h(Box, { flexDirection: "column", flexShrink: 0, marginRight: 1 }, ...cells(pixels).map((row, i) => h(Text, { key: i }, ...row.map((r, j) => h(Text, { key: j, color: r.fg, backgroundColor: r.bg }, r.text)))));
793
901
  }
794
- function Header({ status, version, compact, }) {
795
- const { columns } = useScreenSize();
902
+ function Header({ status, version, compact, bot, }) {
796
903
  // 模型 · 目录 (分支)
797
904
  const where = [
798
905
  h(Text, { key: "model", color: "cyan" }, status.model),
@@ -803,7 +910,7 @@ function Header({ status, version, compact, }) {
803
910
  const name = h(Text, { key: "name", color: "cyan", bold: true }, "jade");
804
911
  if (compact)
805
912
  return h(Box, { flexShrink: 0, paddingX: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { key: "dot", dimColor: true }, " · "), ...where));
806
- return h(Box, { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 }, columns >= 50 ? h(Bot) : null, h(Box, { flexDirection: "column", flexGrow: 1, flexShrink: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { dimColor: true }, ` v${version}`), status.session ? h(Text, { dimColor: true }, ` · session ${status.session}`) : null), h(Text, { wrap: "truncate-end" }, ...where), h(Text, { dimColor: true, wrap: "truncate-end" }, "/help for commands · @ to attach files")));
913
+ return h(Box, { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 }, bot ? h(Bot, { pixels: bot }) : null, h(Box, { flexDirection: "column", flexGrow: 1, flexShrink: 1 }, h(Text, { wrap: "truncate-end" }, name, h(Text, { dimColor: true }, ` v${version}`), status.session ? h(Text, { dimColor: true }, ` · session ${status.session}`) : null), h(Text, { wrap: "truncate-end" }, ...where), h(Text, { dimColor: true, wrap: "truncate-end" }, "/help for commands · @ to attach files")));
807
914
  }
808
915
  const dialogIds = new WeakMap();
809
916
  let dialogCounter = 0;
@@ -976,8 +1083,16 @@ function editKey(s, input, key) {
976
1083
  .replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
977
1084
  return text ? edit.insert(s, text) : undefined;
978
1085
  }
1086
+ /** 一行文字里下标 [from, to)(相对这一行)反色显示,和对话区的选中一样 */
1087
+ function inverseRange(row, from, to) {
1088
+ from = Math.max(0, Math.min(row.length, from));
1089
+ to = Math.max(from, Math.min(row.length, to));
1090
+ if (from === to)
1091
+ return row;
1092
+ return `${row.slice(0, from)}${INVERSE}${row.slice(from, to)}${INVERSE_OFF}${row.slice(to)}`;
1093
+ }
979
1094
  /** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
980
- function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, place, }) {
1095
+ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows = Infinity, place, top, selected, }) {
981
1096
  const ref = useRef(null);
982
1097
  // 只用来在布局变化后重画一次、重新计算光标位置;它给的是相对父元素的坐标,光标要的是相对整个输出
983
1098
  const metrics = useBoxMetrics(ref);
@@ -987,10 +1102,14 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
987
1102
  : state.cursor;
988
1103
  const all = layout(shown, cursor, width - prefix.length);
989
1104
  const { col } = all;
990
- // 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
991
- const first = Math.max(0, Math.min(all.row - maxRows + 1, all.rows.length - maxRows));
1105
+ // 行数超过 maxRows 时滚动:平时光标所在的行总在可见范围里,用滚轮翻过时停在翻到的地方(光标可能不在里面)
1106
+ const last = Math.max(0, all.rows.length - maxRows);
1107
+ const first = top === undefined
1108
+ ? Math.max(0, Math.min(all.row - maxRows + 1, last))
1109
+ : Math.max(0, Math.min(top, last));
992
1110
  const rows = all.rows.slice(first, first + maxRows);
993
1111
  const row = all.row - first;
1112
+ const cursorShown = row >= 0 && row < rows.length;
994
1113
  // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
995
1114
  // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
996
1115
  // 这里用的是上一次的布局,提交后要核对一遍:
@@ -1000,9 +1119,9 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
1000
1119
  const at = active && metrics.hasMeasured && ref.current
1001
1120
  ? origin(ref.current)
1002
1121
  : undefined;
1003
- const position = at && { x: at.x + prefix.length + col, y: at.y + row };
1122
+ const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1004
1123
  if (place)
1005
- place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length };
1124
+ place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1006
1125
  const [, recheck] = useReducer((n) => n + 1, 0);
1007
1126
  useEffect(() => {
1008
1127
  if (!at || !ref.current)
@@ -1013,7 +1132,13 @@ function EditableText({ state, width, prefix, mask, placeholder, active, maxRows
1013
1132
  });
1014
1133
  return h(Box, { ref, flexDirection: "column" }, active ? h(CursorAt, { position }) : null, state.value === "" && placeholder
1015
1134
  ? h(Text, { wrap: "truncate-end" }, h(Text, { color: "cyan" }, prefix), h(Text, { dimColor: true }, placeholder))
1016
- : rows.map((r, i) => h(Text, { key: first + i, wrap: "truncate-end" }, h(Text, { color: "cyan" }, first + i === 0 ? prefix : i === 0 ? "↑".padEnd(prefix.length) : " ".repeat(prefix.length)), r)));
1135
+ : rows.map((r, i) => h(Text, { key: first + i, wrap: "truncate-end" }, h(Text, { color: "cyan" }, first + i === 0
1136
+ ? prefix
1137
+ : i === 0
1138
+ ? "↑".padEnd(prefix.length)
1139
+ : i === rows.length - 1 && first + rows.length < all.rows.length
1140
+ ? "↓".padEnd(prefix.length)
1141
+ : " ".repeat(prefix.length)), selected && !mask ? inverseRange(r, selected[0] - all.starts[first + i], selected[1] - all.starts[first + i]) : r)));
1017
1142
  }
1018
1143
  /**
1019
1144
  * 终端光标只有一个,每个 useCursor 每次提交都会设一遍。没有焦点的输入框(弹出输入框时下面的主输入框)
@@ -1034,7 +1159,7 @@ function origin(node) {
1034
1159
  }
1035
1160
  return { x, y };
1036
1161
  }
1037
- function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone, busy, queued, active, onSubmit, flash, }) {
1162
+ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone, busy, queued, active, onSubmit, flash, place, onCopy, }) {
1038
1163
  const selection = useContext(SelectionContext);
1039
1164
  const [current, setState] = useLive(empty);
1040
1165
  const [getSelected, setSelected] = useLive(0);
@@ -1045,8 +1170,12 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1045
1170
  const draft = useRef("");
1046
1171
  const lastCtrlC = useRef(0);
1047
1172
  const lastEsc = useRef(0);
1048
- /** 输入框文字在屏幕上的位置,点击时换算光标位置用(见 EditableText 的 place) */
1049
- const place = useRef(undefined);
1173
+ /**
1174
+ * 用滚轮翻过输入框时翻到的第一行可见行。只对翻的时候的那份文字和光标有效:打字、移动光标后又跟着光标
1175
+ */
1176
+ const scrolled = useRef(undefined);
1177
+ /** 在输入框里按住左键拖动选中的文字:anchor 是按下的位置,focus 是拖到的位置(value 里的下标);文字改了就作废 */
1178
+ const [getDrag, setDrag] = useLive(undefined);
1050
1179
  const { columns, rows } = useScreenSize();
1051
1180
  /** 输入框里文字的宽度:边框、内边距和前面的 "› " 之外 */
1052
1181
  const textWidth = Math.max(10, columns - 5) - 2;
@@ -1151,6 +1280,8 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1151
1280
  return;
1152
1281
  remember(text);
1153
1282
  set(empty);
1283
+ // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
1284
+ typedAt = 0;
1154
1285
  onSubmit();
1155
1286
  handlers.submit(text);
1156
1287
  };
@@ -1228,6 +1359,57 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1228
1359
  if (search)
1229
1360
  return searchKey(search, input, key);
1230
1361
  const state = current();
1362
+ // 输入框里的鼠标:点击移动光标,按住拖动选中、松开时复制,滚轮翻看放不下的文字
1363
+ const mouse = mouseEvent(input);
1364
+ if (mouse) {
1365
+ const at = place.current;
1366
+ if (!at)
1367
+ return;
1368
+ const row = mouse.y - at.y;
1369
+ // 拖出输入框时停在第一行或最后一行
1370
+ const offset = (r) => offsetAt(state.value, textWidth, at.first + Math.max(0, Math.min(at.rows - 1, r)), mouse.x - at.x);
1371
+ // 滚轮:上下边框也算在输入框上
1372
+ if ((mouse.button === 64 || mouse.button === 65) && row >= -1 && row <= at.rows && at.total > at.rows) {
1373
+ const top = Math.max(0, Math.min(at.total - at.rows, at.first + (mouse.button === 64 ? -WHEEL_LINES : WHEEL_LINES)));
1374
+ scrolled.current = { top, value: state.value, cursor: state.cursor };
1375
+ return setState({ ...state });
1376
+ }
1377
+ if (mouse.button === 0 && mouse.press) {
1378
+ if (row < 0 || row >= at.rows)
1379
+ return setDrag(undefined);
1380
+ const cursor = offset(row);
1381
+ if (cursor === undefined)
1382
+ return;
1383
+ setDrag({ anchor: cursor, focus: cursor, value: state.value });
1384
+ // 点在翻过的地方时保持翻到的位置
1385
+ if (scrolled.current)
1386
+ scrolled.current = { ...scrolled.current, cursor };
1387
+ return setState({ ...state, cursor });
1388
+ }
1389
+ const drag = getDrag();
1390
+ if (!drag || drag.value !== state.value)
1391
+ return;
1392
+ if (mouse.button === DRAG) {
1393
+ const focus = offset(row);
1394
+ if (focus === undefined)
1395
+ return;
1396
+ setDrag({ ...drag, focus });
1397
+ if (scrolled.current)
1398
+ scrolled.current = { ...scrolled.current, cursor: focus };
1399
+ return setState({ ...state, cursor: focus });
1400
+ }
1401
+ if (mouse.button === 0 && !mouse.press && drag.anchor !== drag.focus) {
1402
+ onCopy(state.value.slice(Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)));
1403
+ }
1404
+ return;
1405
+ }
1406
+ // 别的键取消输入框里的选中;Ctrl+C 只取消选中(已经在松开时复制过了)
1407
+ const drag = getDrag();
1408
+ if (drag) {
1409
+ setDrag(undefined);
1410
+ if (key.ctrl && input === "c" && drag.anchor !== drag.focus && drag.value === state.value)
1411
+ return;
1412
+ }
1231
1413
  if (key.ctrl && input === "r")
1232
1414
  return history.current.length
1233
1415
  ? setSearch({ query: "", index: 0 })
@@ -1254,20 +1436,6 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1254
1436
  lastEsc.current = Date.now();
1255
1437
  return;
1256
1438
  }
1257
- // 点击输入框里的文字:光标移到点的位置
1258
- const mouse = mouseEvent(input);
1259
- if (mouse) {
1260
- const at = place.current;
1261
- if (!at || mouse.button !== 0 || !mouse.press)
1262
- return;
1263
- const row = mouse.y - at.y;
1264
- if (row < 0 || row >= at.rows)
1265
- return;
1266
- const cursor = offsetAt(state.value, textWidth, at.first + row, mouse.x - at.x);
1267
- if (cursor !== undefined)
1268
- setState({ ...state, cursor });
1269
- return;
1270
- }
1271
1439
  // 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
1272
1440
  if (!key.ctrl &&
1273
1441
  !key.meta &&
@@ -1276,8 +1444,9 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1276
1444
  return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1277
1445
  }
1278
1446
  if (key.return) {
1279
- // 行尾的 \ 加回车换行;Alt+Enter 也换行
1280
- if (key.meta)
1447
+ // 行尾的 \ 加回车换行;Alt+Enter 也换行;终端把 Shift+Enter 单独报上来时(kitty 键盘协议、modifyOtherKeys)也换行。
1448
+ // Ctrl+J(Windows Terminal 里 Ctrl+Enter 也是它)发的是 LF,不算回车,在 editKey 里当普通换行插入
1449
+ if (key.meta || key.shift)
1281
1450
  return set(edit.insert(state, "\n"));
1282
1451
  if (state.value.slice(0, state.cursor).endsWith("\\"))
1283
1452
  return set(edit.insert(edit.backspace(state), "\n"));
@@ -1342,9 +1511,18 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1342
1511
  if (spec && handlers.key?.(spec))
1343
1512
  return;
1344
1513
  const next = editKey(state, input, key);
1345
- if (next)
1514
+ if (next) {
1515
+ if (next.value !== state.value)
1516
+ typedAt = Date.now();
1346
1517
  set(next);
1518
+ }
1347
1519
  }, { isActive: active });
1520
+ const view = scrolled.current;
1521
+ const viewTop = view && view.value === state.value && view.cursor === state.cursor ? view.top : undefined;
1522
+ const drag = getDrag();
1523
+ const dragged = drag && drag.value === state.value && drag.anchor !== drag.focus
1524
+ ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1525
+ : undefined;
1348
1526
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1349
1527
  return h(Box, { flexDirection: "column", marginTop: 1, display: active ? "flex" : "none" }, h(Box, { borderStyle: "round", borderColor: busy ? "gray" : "cyan", paddingX: 1 }, search
1350
1528
  ? h(EditableText, {
@@ -1371,6 +1549,8 @@ function Prompt({ commands, handlers, history: initial, bridge, hint, onHintDone
1371
1549
  active,
1372
1550
  maxRows: inputRows,
1373
1551
  place,
1552
+ top: viewTop,
1553
+ selected: dragged,
1374
1554
  })), search
1375
1555
  ? h(Box, { flexDirection: "column", paddingX: 2 }, results.length
1376
1556
  ? results.slice(first, first + menuRows).map((item, i) => {
@@ -1421,6 +1601,24 @@ const MENTION_ROWS = 8;
1421
1601
  function around(selected, total, size) {
1422
1602
  return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1423
1603
  }
1604
+ /** 用户上一次在输入框里打字的时间;发送之后清零 */
1605
+ let typedAt = 0;
1606
+ /** 打字停下这么久之后,对话框才把回车和字符当成回答 */
1607
+ const TYPING_GRACE = 500;
1608
+ /**
1609
+ * 对话框弹出时用户正在输入框里打字(例如在排下一条消息时弹出审批):接着打出来的回车、数字不能当成回答。
1610
+ * 返回 true 表示这个键要丢掉。方向键、Esc 说明用户已经看到对话框了,不再拦
1611
+ */
1612
+ function typedThrough(input, key) {
1613
+ if (Date.now() - typedAt >= TYPING_GRACE)
1614
+ return false;
1615
+ if (key.escape || key.upArrow || key.downArrow || key.pageUp || key.pageDown || (key.ctrl && input === "c") || MOUSE.test(input)) {
1616
+ typedAt = 0;
1617
+ return false;
1618
+ }
1619
+ typedAt = Date.now();
1620
+ return true;
1621
+ }
1424
1622
  /** 选择框一次最多显示几项 */
1425
1623
  const VISIBLE = 10;
1426
1624
  /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
@@ -1429,6 +1627,9 @@ function SelectDialog({ dialog, }) {
1429
1627
  const selection = useContext(SelectionContext);
1430
1628
  const [getSelected, setSelected] = useLive(0);
1431
1629
  const [getQuery, setQuery] = useLive("");
1630
+ /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
1631
+ const [getTop, setTop] = useLive(0);
1632
+ const scrolling = useRef({ maxTop: 0, page: 1 });
1432
1633
  const { rows, columns } = useScreenSize();
1433
1634
  const filtering = dialog.choices.length > FILTER_FROM;
1434
1635
  const query = getQuery();
@@ -1446,14 +1647,26 @@ function SelectDialog({ dialog, }) {
1446
1647
  const visible = roomFor(rows, VISIBLE);
1447
1648
  // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画,底部的选项和提示也会被裁掉。
1448
1649
  // 按折行后的屏幕行数截断(一行长代码会占好几行),每一行单独显示、不再折行
1449
- const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4));
1650
+ const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
1450
1651
  const room = Math.max(3, rows - Math.min(n, visible) - 16);
1652
+ // 放不下时 PgUp/PgDn 翻看预览(批准之前要能看完整个 diff),最后一行说明还有多少
1653
+ const page = room - 1;
1654
+ const maxTop = Math.max(0, lines.length - page);
1655
+ const top = Math.min(getTop(), maxTop);
1656
+ scrolling.current = { maxTop, page };
1451
1657
  const body = lines.length > room
1452
- ? [...lines.slice(0, room - 1), dim(`… ${lines.length - room + 1} more lines`)]
1658
+ ? [
1659
+ ...lines.slice(top, top + page),
1660
+ dim(top < maxTop
1661
+ ? `… ${lines.length - top - page} more lines · PgDn/PgUp to scroll`
1662
+ : `end of ${lines.length} lines · PgUp to scroll back`),
1663
+ ]
1453
1664
  : lines;
1454
1665
  useInput((input, key) => {
1455
1666
  if (key.ctrl && input === "c" && selection.active())
1456
1667
  return selection.clear();
1668
+ if (typedThrough(input, key))
1669
+ return;
1457
1670
  const items = filtered();
1458
1671
  const n = items.length;
1459
1672
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
@@ -1472,6 +1685,11 @@ function SelectDialog({ dialog, }) {
1472
1685
  }
1473
1686
  if (key.escape || (key.ctrl && input === "c"))
1474
1687
  return dialog.resolve(undefined);
1688
+ // 预览放不下时翻预览,否则翻选项
1689
+ const { maxTop, page } = scrolling.current;
1690
+ if (maxTop > 0 && (key.pageDown || key.pageUp)) {
1691
+ return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + (key.pageDown ? page : -page))));
1692
+ }
1475
1693
  if (key.pageDown)
1476
1694
  return setSelected(Math.min(n - 1, selected + visible));
1477
1695
  if (key.pageUp)
@@ -1521,6 +1739,8 @@ function InputDialog({ dialog, }) {
1521
1739
  useInput((input, key) => {
1522
1740
  if (key.ctrl && input === "c" && selection.active())
1523
1741
  return selection.clear();
1742
+ if (typedThrough(input, key))
1743
+ return;
1524
1744
  const state = current();
1525
1745
  if (key.return)
1526
1746
  return dialog.resolve(state.value.trim());