@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
@@ -5,6 +5,7 @@
5
5
  // 不用 JSX:插件以 .ts 源码加载,Node 的类型剥离不处理 .tsx,所以组件用 createElement(h)写。
6
6
 
7
7
  import { writeSync } from "node:fs";
8
+ import type { DOMElement, Key } from "ink";
8
9
  import {
9
10
  Box,
10
11
  render,
@@ -14,10 +15,6 @@ import {
14
15
  useInput,
15
16
  usePaste,
16
17
  useWindowSize,
17
- type DOMElement,
18
- type Key,
19
- } from "ink";
20
- import {
21
18
  createContext,
22
19
  createElement as h,
23
20
  useContext,
@@ -26,12 +23,12 @@ import {
26
23
  useRef,
27
24
  useState,
28
25
  useSyncExternalStore,
29
- } from "react";
26
+ } from "./vendor.ts";
30
27
  import stringWidth from "string-width";
31
- import wrapAnsi from "wrap-ansi";
32
28
  import { mentionAt, mentionText, rankPaths } from "./mentions.ts";
33
29
  import { charWidth, edit, empty, layout, moveRow, offsetAt, type EditState } from "./editor.ts";
34
- import { expandTabs, markdownStream, type MdLine } from "./markdown.ts";
30
+ import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows, type MdLine } from "./markdown.ts";
31
+ import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.ts";
35
32
  import {
36
33
  dim,
37
34
  type Choice,
@@ -104,6 +101,8 @@ interface UiState {
104
101
  /** 对话区离底部滚上去了多少行;0 表示跟着最新的输出 */
105
102
  scroll: number;
106
103
  busy?: { label: string; since: number };
104
+ /** 上一次正常做完(不是中断)的时间,吉祥物据此笑一会儿 */
105
+ doneAt?: number;
107
106
  /** 正在运行的工具最新的一行进度,显示在对话的最后,工具结束时去掉 */
108
107
  progress: { id: string; line: string }[];
109
108
  queued: string[];
@@ -116,9 +115,8 @@ interface UiState {
116
115
  /** 对话最多保留这么多行(折行前),超出时丢掉最早的一段 */
117
116
  const MAX_LINES = 10_000;
118
117
 
119
- /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行。制表符先换成空格:按 0 列算宽度会对不齐、超宽 */
120
- const wrap = (text: string, width: number) =>
121
- wrapAnsi(expandTabs(text), width, { hard: true, trim: false }).split("\n");
118
+ /** 按显示宽度折行,保留颜色;每一项是屏幕上的一行,自动折出来的续行开头带记号(markdown.ts),显示之前用 visibleRow 去掉 */
119
+ const wrap = wrapRows;
122
120
 
123
121
  /**
124
122
  * 对话里的一项:普通的一行,或者可以点击展开、收起的一段。
@@ -406,15 +404,52 @@ const CURSOR_RESET = "\x1b[0 q";
406
404
 
407
405
  /** 工作超过这么久后结束,或者这时弹出要用户选择的对话框,用户多半去做别的了:提醒一下 */
408
406
  const NOTIFY_AFTER = 10_000;
409
- /** 支持 OSC 9 桌面通知的终端;其他终端只响铃(不认识的 OSC 9 在有的终端里会弹别的东西) */
407
+ /** 支持 OSC 9 桌面通知的终端;其他终端什么都不发(不认识的 OSC 9 在有的终端里会弹别的东西) */
410
408
  const OSC9_TERMINALS = new Set(["iTerm.app", "WezTerm", "ghostty"]);
411
409
 
412
- /** 响铃,支持的终端再发一条桌面通知。JADE_NOTIFY=off 关闭 */
410
+ /**
411
+ * 支持的终端发一条桌面通知。不响铃:铃声在很多终端里(例如 Windows Terminal)是系统的错误提示音,听起来像出错了。
412
+ * JADE_NOTIFY=off 关闭
413
+ */
413
414
  function notifier(stdout: NodeJS.WriteStream, env = process.env): (message: string) => void {
414
- if (env.JADE_NOTIFY === "off") return () => {};
415
- const osc9 = OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "");
416
- return (message) =>
417
- stdout.write(osc9 ? `\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07` : "\x07");
415
+ if (env.JADE_NOTIFY === "off" || !OSC9_TERMINALS.has(env.TERM_PROGRAM ?? "")) return () => {};
416
+ return (message) => stdout.write(`\x1b]9;jade: ${message.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`);
417
+ }
418
+
419
+ /** 终端标题里的控制字符换成空格,免得提前结束转义序列 */
420
+ const osc0 = (text: string) => `\x1b]0;${text.replace(/[\x00-\x1f\x7f]/g, " ")}\x07`;
421
+ /** 先把终端原来的标题存进标题栈(xterm 的 CSI 22 t),退出时取回;不支持的终端(如 Windows Terminal)退出时清空标题,回到默认 */
422
+ const TITLE_PUSH = "\x1b[22;0t";
423
+ const TITLE_POP = `${osc0("")}\x1b[23;0t`;
424
+
425
+ /**
426
+ * 让终端标签页标题跟着 jade 的状态走(见 mascot.ts 的 title):空闲时显示标志,运行中转圈,等用户时加感叹号。
427
+ * JADE_TITLE=off 关闭。返回关闭函数,会把标题还原
428
+ */
429
+ function titleBar(stdout: NodeJS.WriteStream, store: Store, env = process.env): () => void {
430
+ if (env.JADE_TITLE === "off") return () => {};
431
+ let shown = "";
432
+ const update = () => {
433
+ const s = store.state;
434
+ const now = Date.now();
435
+ const mood = moodOf({ busy: s.busy?.label, asking: s.dialogs.length > 0, doneAt: s.doneAt }, now);
436
+ const dir = s.status.cwd.split(/[\\/]/).filter(Boolean).at(-1) ?? s.status.cwd;
437
+ const text = title(mood, dir, now);
438
+ if (text === shown) return;
439
+ shown = text;
440
+ stdout.write(osc0(text));
441
+ };
442
+ stdout.write(TITLE_PUSH);
443
+ update();
444
+ const off = store.subscribe(update);
445
+ // 运行中转圈:状态不变时也要按时间换一帧
446
+ const timer = setInterval(() => store.state.busy && update(), 250);
447
+ timer.unref?.();
448
+ return () => {
449
+ off();
450
+ clearInterval(timer);
451
+ stdout.write(TITLE_POP);
452
+ };
418
453
  }
419
454
 
420
455
  export function tuiScreen(opts: TuiOptions): Screen {
@@ -497,33 +532,41 @@ export function tuiScreen(opts: TuiOptions): Screen {
497
532
 
498
533
  // 切到备用屏幕后光标还停在原来的位置(不少终端不会自动归位),Ink 从那里往下画第一帧会让屏幕滚动,
499
534
  // 之后每帧只重写变化的行,整个界面就错位了。所以先自己切过去、清屏、把光标移到左上角
500
- stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
501
535
  const commands = opts.commands;
502
- const instance = render(
503
- h(App, {
504
- store,
505
- copy: (text: string) => void stdout.write(osc52(text)),
506
- version: opts.version,
507
- commands: typeof commands === "function" ? commands : () => commands,
508
- handlers: opts.handlers,
509
- history: opts.history ?? [],
510
- draft,
511
- }),
512
- {
513
- exitOnCtrlC: false,
514
- alternateScreen: true,
515
- // 全屏每帧只重写变化的行
516
- incrementalRendering: true,
517
- ...(opts.io
518
- ? { ...opts.io, interactive: true, patchConsole: false }
519
- : {}),
520
- },
521
- );
522
- stdout.write(MOUSE_ON + CURSOR_BLINK);
536
+ /** 接管终端、画界面。界面的内容都在 store 里,所以让出终端(suspend)之后可以再画一个新的 */
537
+ const mount = () => {
538
+ stdout.write("\x1b[?1049h\x1b[2J\x1b[H");
539
+ const mounted = render(
540
+ h(App, {
541
+ store,
542
+ copy: (text: string) => void stdout.write(osc52(text)),
543
+ version: opts.version,
544
+ commands: typeof commands === "function" ? commands : () => commands,
545
+ handlers: opts.handlers,
546
+ history: opts.history ?? [],
547
+ draft,
548
+ }),
549
+ {
550
+ exitOnCtrlC: false,
551
+ alternateScreen: true,
552
+ // 全屏每帧只重写变化的行
553
+ incrementalRendering: true,
554
+ ...(opts.io
555
+ ? { ...opts.io, interactive: true, patchConsole: false }
556
+ : {}),
557
+ },
558
+ );
559
+ stdout.write(MOUSE_ON + CURSOR_BLINK);
560
+ return mounted;
561
+ };
562
+ let instance = mount();
563
+ /** 让出终端一次只做一回,后来的排在后面 */
564
+ let yielding: Promise<unknown> = Promise.resolve();
565
+ const closeTitle = titleBar(stdout, store);
523
566
  // 没走 close 就退出(process.exit)时也要把终端还原,否则会留在备用屏幕、鼠标上报也开着
524
567
  const restore = () => {
525
568
  try {
526
- writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}\x1b[?1049l\x1b[?25h`);
569
+ writeSync(1, `${MOUSE_OFF}${CURSOR_RESET}${TITLE_POP}\x1b[?1049l\x1b[?25h`);
527
570
  } catch {}
528
571
  };
529
572
  if (!opts.io) process.on("exit", restore);
@@ -592,7 +635,10 @@ export function tuiScreen(opts: TuiOptions): Screen {
592
635
  if (label === undefined) {
593
636
  // 稍等一下再提醒:排队的消息接着开始时(马上又 busy)不算结束
594
637
  if (longBusy()) doneTimer ??= setTimeout(() => notify("done"), 300);
595
- store.update({ busy: undefined });
638
+ store.update({
639
+ busy: undefined,
640
+ ...(current && current.label !== "Interrupting" ? { doneAt: Date.now() } : {}),
641
+ });
596
642
  return;
597
643
  }
598
644
  clearTimeout(doneTimer);
@@ -614,6 +660,29 @@ export function tuiScreen(opts: TuiOptions): Screen {
614
660
  },
615
661
  hint: (text) => store.update({ hint: text ? text.replace(/\r\n?/g, "\n") : undefined }),
616
662
  },
663
+ copy: (text) => void stdout.write(osc52(text)),
664
+ suspend<T>(fn: () => T | Promise<T>): Promise<T> {
665
+ const run = yielding.then(async () => {
666
+ // 输入框里打了一半的字在组件里,卸载就没了:先记下
667
+ const typed = draft.current?.get();
668
+ stdout.write(MOUSE_OFF + CURSOR_RESET);
669
+ // 卸载时 Ink 退出备用屏幕、关掉 raw mode、不再读 stdin:终端回到普通状态,别的程序可以用
670
+ instance.unmount();
671
+ await instance.waitUntilExit();
672
+ delete draft.current;
673
+ try {
674
+ return await fn();
675
+ } finally {
676
+ instance = mount();
677
+ // 等输入框画出来再返回:调用方接着就可能改输入框(编辑器里写好的内容)
678
+ const input = (): DraftBridge["current"] => draft.current;
679
+ for (let i = 0; i < 100 && !input(); i++) await new Promise((r) => setTimeout(r, 10));
680
+ if (typed) input()?.apply(() => ({ value: typed, cursor: typed.length }));
681
+ }
682
+ });
683
+ yielding = run.catch(() => {});
684
+ return run;
685
+ },
617
686
  select: <T>(title: string, choices: Choice<T>[], o?: { body?: string; signal?: AbortSignal }) => {
618
687
  if (longBusy()) notify(title);
619
688
  return ask<T | undefined>(
@@ -649,6 +718,7 @@ export function tuiScreen(opts: TuiOptions): Screen {
649
718
  store.update({ live: undefined, busy: undefined, progress: [] }, true);
650
719
  // 等最后一帧画完再卸载;卸载时 Ink 退出备用屏幕
651
720
  await new Promise((r) => setTimeout(r, 50));
721
+ closeTitle();
652
722
  stdout.write(MOUSE_OFF + CURSOR_RESET);
653
723
  instance.unmount();
654
724
  await instance.waitUntilExit();
@@ -739,17 +809,25 @@ function highlight(line: string, from: number, to: number): string {
739
809
  return out + (on ? INVERSE_OFF : "");
740
810
  }
741
811
 
742
- /** 选中的纯文字:每行去掉行尾空白,用换行连起来(自动折行的地方也是换行) */
743
- function selectedText(s: Selection, row: (i: number) => string | undefined): string {
812
+ /**
813
+ * 选中的纯文字:每行去掉行尾空白,用换行连起来。自动折行出来的续行接回上一行(补上折行时去掉的空格、
814
+ * 跳过排版加的缩进),所以一行很长的命令复制出来还是一行。row 给的是带续行记号的行
815
+ */
816
+ export function selectedText(s: Selection, row: (i: number) => string | undefined): string {
744
817
  const lines: string[] = [];
745
818
  const { anchor: a, focus: f } = s;
746
- for (let r = Math.min(a.row, f.row); r <= Math.max(a.row, f.row); r++) {
819
+ const first = Math.min(a.row, f.row);
820
+ for (let r = first; r <= Math.max(a.row, f.row); r++) {
747
821
  const [from, to] = selectedCols(s, r)!;
822
+ const { text: line, soft, gap, indent } = softInfo(row(r) ?? "");
748
823
  let text = "";
749
- walk(row(r) ?? "", from, to, (ch, inside) => void (inside && (text += ch)));
750
- lines.push(text.trimEnd());
824
+ // 续行开头的缩进、竖线是排版加的
825
+ walk(line, Math.max(from, soft ? indent : 0), to, (ch, inside) => void (inside && (text += ch)));
826
+ if (soft && r > first) lines[lines.length - 1] += " ".repeat(gap) + text;
827
+ // 代码块左边的竖线是排版加的,不是代码的一部分
828
+ else lines.push(text.replace(/^┃ ?/, ""));
751
829
  }
752
- return lines.join("\n");
830
+ return lines.map((l) => l.trimEnd()).join("\n");
753
831
  }
754
832
 
755
833
  /** OSC 52:让终端把文字放进系统剪贴板(Windows Terminal、iTerm2、kitty、WezTerm 等支持) */
@@ -790,16 +868,30 @@ function App({
790
868
  }) {
791
869
  const state = useSyncExternalStore(store.subscribe, store.get);
792
870
  const dialog = state.dialogs[0];
793
- // 运行中每 100ms 整体重画一次,推动转圈动画。不能让 Spinner 自己重画:
871
+ const { columns, rows } = useScreenSize();
872
+ const compact = rows < COMPACT_ROWS;
873
+ // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
794
874
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了
795
- const [, tick] = useReducer((n: number) => n + 1, 0);
875
+ const [ticks, tick] = useReducer((n: number) => n + 1, 0);
796
876
  const busy = state.busy !== undefined;
797
877
  useEffect(() => {
798
878
  if (!busy) return;
799
- const t = setInterval(tick, 100);
879
+ const t = setInterval(tick, FRAME_MS);
800
880
  return () => clearInterval(t);
801
881
  }, [busy]);
802
- const { columns, rows } = useScreenSize();
882
+ const now = Date.now();
883
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
884
+ const mascot = useRef<Mascot>(undefined);
885
+ mascot.current ??= new Mascot();
886
+ const showBot = !compact && columns >= 50;
887
+ const bot = showBot ? mascot.current.frame(mood, now) : undefined;
888
+ // 不在运行时吉祥物也会眨眼、瞟一眼、从上一个表情缓过来:只在它要动的时候按帧重画,其余时间不画
889
+ const moving = showBot && mascot.current.moving(mood, now);
890
+ useEffect(() => {
891
+ if (busy || !showBot) return;
892
+ const t = setTimeout(tick, nextChange(mood, Date.now(), state.doneAt, moving));
893
+ return () => clearTimeout(t);
894
+ }, [busy, showBot, ticks, mood, moving, state.doneAt]);
803
895
 
804
896
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
805
897
  const ref = useRef<DOMElement>(null);
@@ -846,8 +938,10 @@ function App({
846
938
  const [copied, setCopied] = useState<string>();
847
939
  const copiedTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
848
940
  useEffect(() => () => clearTimeout(copiedTimer.current), []);
849
- const copySelection = (s: Selection) => {
850
- const text = selectedText(s, rowAt);
941
+ /** 输入框文字在屏幕上的位置(Prompt 里的 EditableText 每次渲染时写入) */
942
+ const inputPlace = useRef<Placement>(undefined);
943
+ const copySelection = (s: Selection) => copyText(selectedText(s, rowAt));
944
+ const copyText = (text: string) => {
851
945
  copy(text);
852
946
  clearTimeout(copiedTimer.current);
853
947
  setCopied(`Copied ${[...text].length} characters to the clipboard`);
@@ -887,6 +981,10 @@ function App({
887
981
  if (!clamp && (i < 0 || i >= shown.length)) return undefined;
888
982
  return { row: start + Math.min(Math.max(i, 0), shown.length - 1), col: Math.max(0, mouse.x - 1) };
889
983
  };
984
+ // 滚轮在放不下全部文字的输入框上(含上下边框)时由输入框自己翻
985
+ const input = inputPlace.current;
986
+ const overInput = input && input.total > input.rows && mouse.y >= input.y - 1 && mouse.y <= input.y + input.rows;
987
+ if ((mouse.button === 64 || mouse.button === 65) && overInput) return;
890
988
  if (mouse.button === 64) store.scrollBy(WHEEL_LINES, max);
891
989
  else if (mouse.button === 65) store.scrollBy(-WHEEL_LINES, max);
892
990
  else if (mouse.button === 0 && mouse.press) {
@@ -936,7 +1034,7 @@ function App({
936
1034
  h(
937
1035
  Box,
938
1036
  { flexDirection: "column", flexGrow: 1, overflowY: "hidden" },
939
- h(Header, { status: state.status, version, compact: rows < COMPACT_ROWS }),
1037
+ h(Header, { status: state.status, version, compact, bot }),
940
1038
  h(
941
1039
  Box,
942
1040
  {
@@ -948,7 +1046,9 @@ function App({
948
1046
  overflowY: "hidden",
949
1047
  paddingX: 1,
950
1048
  },
951
- shown.map((l, i) => {
1049
+ shown.map((raw, i) => {
1050
+ // 续行的记号不显示
1051
+ const l = visibleRow(raw);
952
1052
  const cols = selection && selectedCols(selection, start + i);
953
1053
  return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
954
1054
  }),
@@ -984,6 +1084,8 @@ function App({
984
1084
  active: !dialog,
985
1085
  onSubmit: () => store.scrollBy(-max, max),
986
1086
  flash: copied,
1087
+ place: inputPlace,
1088
+ onCopy: copyText,
987
1089
  }),
988
1090
  h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) }),
989
1091
  ),
@@ -992,20 +1094,20 @@ function App({
992
1094
  );
993
1095
  }
994
1096
 
995
- const JADE = "#00a86b";
996
- const SHINE = "#b6f2d4";
997
-
998
1097
  /**
999
- * 标题左边的吉祥物:一个玉做的团子,用半格字符画的像素图,三行高,正好和右边三行文字并排。
1000
- * 每个字符上下两个像素;眼睛是玉上挖空的两格,左上角一点高光让它看起来像玉
1098
+ * 标题左边的吉祥物(见 mascot.ts):玉做的团子,按 mood 换表情和动画,三行高,正好和右边三行文字并排
1001
1099
  */
1002
- function Bot() {
1100
+ function Bot({ pixels }: { pixels: (string | undefined)[][] }) {
1003
1101
  return h(
1004
1102
  Box,
1005
- { flexDirection: "column", flexShrink: 0, marginRight: 2 },
1006
- h(Text, { color: JADE }, " ▄", h(Text, { color: SHINE, backgroundColor: JADE }, "▄"), "████▄"),
1007
- h(Text, { color: JADE }, "██ ███ ██"),
1008
- h(Text, { color: JADE }, "▀███████▀"),
1103
+ { flexDirection: "column", flexShrink: 0, marginRight: 1 },
1104
+ ...cells(pixels).map((row, i) =>
1105
+ h(
1106
+ Text,
1107
+ { key: i },
1108
+ ...row.map((r, j) => h(Text, { key: j, color: r.fg, backgroundColor: r.bg }, r.text)),
1109
+ ),
1110
+ ),
1009
1111
  );
1010
1112
  }
1011
1113
 
@@ -1013,13 +1115,15 @@ function Header({
1013
1115
  status,
1014
1116
  version,
1015
1117
  compact,
1118
+ bot,
1016
1119
  }: {
1017
1120
  status: StatusInfo;
1018
1121
  version: string;
1122
+ /** 吉祥物这一帧的像素(见 mascot.ts);放不下时 undefined */
1123
+ bot?: (string | undefined)[][];
1019
1124
  /** 终端很矮时只占一行,把高度留给对话和输入框 */
1020
1125
  compact: boolean;
1021
1126
  }) {
1022
- const { columns } = useScreenSize();
1023
1127
  // 模型 · 目录 (分支)
1024
1128
  const where = [
1025
1129
  h(Text, { key: "model", color: "cyan" }, status.model),
@@ -1037,7 +1141,7 @@ function Header({
1037
1141
  return h(
1038
1142
  Box,
1039
1143
  { flexShrink: 0, borderStyle: "round", borderColor: "cyan", paddingX: 1 },
1040
- columns >= 50 ? h(Bot) : null,
1144
+ bot ? h(Bot, { pixels: bot }) : null,
1041
1145
  h(
1042
1146
  Box,
1043
1147
  { flexDirection: "column", flexGrow: 1, flexShrink: 1 },
@@ -1257,8 +1361,19 @@ function editKey(s: EditState, input: string, key: Key): EditState | undefined {
1257
1361
  return text ? edit.insert(s, text) : undefined;
1258
1362
  }
1259
1363
 
1260
- /** 可编辑文本在屏幕上的位置:第一个字符的列 x、第一行可见行的行 y、可见的是折行后的第 first 行起的 rows 行 */
1261
- type Placement = { x: number; y: number; first: number; rows: number } | undefined;
1364
+ /**
1365
+ * 可编辑文本在屏幕上的位置:第一个字符的列 x、第一行可见行的行 y、可见的是折行后的第 first 行起的 rows 行,
1366
+ * 折行后一共 total 行
1367
+ */
1368
+ type Placement = { x: number; y: number; first: number; rows: number; total: number } | undefined;
1369
+
1370
+ /** 一行文字里下标 [from, to)(相对这一行)反色显示,和对话区的选中一样 */
1371
+ function inverseRange(row: string, from: number, to: number): string {
1372
+ from = Math.max(0, Math.min(row.length, from));
1373
+ to = Math.max(from, Math.min(row.length, to));
1374
+ if (from === to) return row;
1375
+ return `${row.slice(0, from)}${INVERSE}${row.slice(from, to)}${INVERSE_OFF}${row.slice(to)}`;
1376
+ }
1262
1377
 
1263
1378
  /** 渲染可编辑文本并把终端光标放到输入位置(输入法的候选框跟着它) */
1264
1379
  function EditableText({
@@ -1270,9 +1385,15 @@ function EditableText({
1270
1385
  active,
1271
1386
  maxRows = Infinity,
1272
1387
  place,
1388
+ top,
1389
+ selected,
1273
1390
  }: {
1274
1391
  /** 每次渲染时写入文字的位置,点击换算光标用 */
1275
1392
  place?: { current: Placement };
1393
+ /** 用滚轮翻到的第一行可见行;undefined 时跟着光标 */
1394
+ top?: number;
1395
+ /** 选中的文字:value 里的下标 [from, to) */
1396
+ selected?: [number, number];
1276
1397
  state: EditState;
1277
1398
  width: number;
1278
1399
  prefix: string;
@@ -1291,13 +1412,15 @@ function EditableText({
1291
1412
  : state.cursor;
1292
1413
  const all = layout(shown, cursor, width - prefix.length);
1293
1414
  const { col } = all;
1294
- // 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
1295
- const first = Math.max(
1296
- 0,
1297
- Math.min(all.row - maxRows + 1, all.rows.length - maxRows),
1298
- );
1415
+ // 行数超过 maxRows 时滚动:平时光标所在的行总在可见范围里,用滚轮翻过时停在翻到的地方(光标可能不在里面)
1416
+ const last = Math.max(0, all.rows.length - maxRows);
1417
+ const first =
1418
+ top === undefined
1419
+ ? Math.max(0, Math.min(all.row - maxRows + 1, last))
1420
+ : Math.max(0, Math.min(top, last));
1299
1421
  const rows = all.rows.slice(first, first + maxRows);
1300
1422
  const row = all.row - first;
1423
+ const cursorShown = row >= 0 && row < rows.length;
1301
1424
 
1302
1425
  // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
1303
1426
  // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
@@ -1309,8 +1432,8 @@ function EditableText({
1309
1432
  active && metrics.hasMeasured && ref.current
1310
1433
  ? origin(ref.current)
1311
1434
  : undefined;
1312
- const position = at && { x: at.x + prefix.length + col, y: at.y + row };
1313
- if (place) place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length };
1435
+ const position = at && cursorShown ? { x: at.x + prefix.length + col, y: at.y + row } : undefined;
1436
+ if (place) place.current = at && { x: at.x + prefix.length, y: at.y, first, rows: rows.length, total: all.rows.length };
1314
1437
  const [, recheck] = useReducer((n: number) => n + 1, 0);
1315
1438
  useEffect(() => {
1316
1439
  if (!at || !ref.current) return;
@@ -1331,9 +1454,15 @@ function EditableText({
1331
1454
  h(
1332
1455
  Text,
1333
1456
  { color: "cyan" },
1334
- first + i === 0 ? prefix : i === 0 ? "↑".padEnd(prefix.length) : " ".repeat(prefix.length),
1457
+ first + i === 0
1458
+ ? prefix
1459
+ : i === 0
1460
+ ? "↑".padEnd(prefix.length)
1461
+ : i === rows.length - 1 && first + rows.length < all.rows.length
1462
+ ? "↓".padEnd(prefix.length)
1463
+ : " ".repeat(prefix.length),
1335
1464
  ),
1336
- r,
1465
+ selected && !mask ? inverseRange(r, selected[0] - all.starts[first + i]!, selected[1] - all.starts[first + i]!) : r,
1337
1466
  ),
1338
1467
  ),
1339
1468
  );
@@ -1372,7 +1501,13 @@ function Prompt({
1372
1501
  active,
1373
1502
  onSubmit,
1374
1503
  flash,
1504
+ place,
1505
+ onCopy,
1375
1506
  }: {
1507
+ /** 输入框文字在屏幕上的位置(见 EditableText 的 place);App 用它判断滚轮是不是在输入框上 */
1508
+ place: { current: Placement };
1509
+ /** 在输入框里拖动选中了文字:复制它 */
1510
+ onCopy(text: string): void;
1376
1511
  /** 当前的命令(随会话的插件增减),每次算菜单时取 */
1377
1512
  commands: () => CommandInfo[];
1378
1513
  handlers: TuiHandlers;
@@ -1402,8 +1537,12 @@ function Prompt({
1402
1537
  const draft = useRef("");
1403
1538
  const lastCtrlC = useRef(0);
1404
1539
  const lastEsc = useRef(0);
1405
- /** 输入框文字在屏幕上的位置,点击时换算光标位置用(见 EditableText 的 place) */
1406
- const place = useRef<Placement>(undefined);
1540
+ /**
1541
+ * 用滚轮翻过输入框时翻到的第一行可见行。只对翻的时候的那份文字和光标有效:打字、移动光标后又跟着光标
1542
+ */
1543
+ const scrolled = useRef<{ top: number; value: string; cursor: number }>(undefined);
1544
+ /** 在输入框里按住左键拖动选中的文字:anchor 是按下的位置,focus 是拖到的位置(value 里的下标);文字改了就作废 */
1545
+ const [getDrag, setDrag] = useLive<{ anchor: number; focus: number; value: string } | undefined>(undefined);
1407
1546
  const { columns, rows } = useScreenSize();
1408
1547
  /** 输入框里文字的宽度:边框、内边距和前面的 "› " 之外 */
1409
1548
  const textWidth = Math.max(10, columns - 5) - 2;
@@ -1520,6 +1659,8 @@ function Prompt({
1520
1659
  if (!text.trim()) return;
1521
1660
  remember(text);
1522
1661
  set(empty);
1662
+ // 发出去之后弹出的对话框是用户自己要的(/mode、/model),马上就能回答
1663
+ typedAt = 0;
1523
1664
  onSubmit();
1524
1665
  handlers.submit(text);
1525
1666
  };
@@ -1602,6 +1743,49 @@ function Prompt({
1602
1743
  const search = getSearch();
1603
1744
  if (search) return searchKey(search, input, key);
1604
1745
  const state = current();
1746
+ // 输入框里的鼠标:点击移动光标,按住拖动选中、松开时复制,滚轮翻看放不下的文字
1747
+ const mouse = mouseEvent(input);
1748
+ if (mouse) {
1749
+ const at = place.current;
1750
+ if (!at) return;
1751
+ const row = mouse.y - at.y;
1752
+ // 拖出输入框时停在第一行或最后一行
1753
+ const offset = (r: number) => offsetAt(state.value, textWidth, at.first + Math.max(0, Math.min(at.rows - 1, r)), mouse.x - at.x);
1754
+ // 滚轮:上下边框也算在输入框上
1755
+ if ((mouse.button === 64 || mouse.button === 65) && row >= -1 && row <= at.rows && at.total > at.rows) {
1756
+ const top = Math.max(0, Math.min(at.total - at.rows, at.first + (mouse.button === 64 ? -WHEEL_LINES : WHEEL_LINES)));
1757
+ scrolled.current = { top, value: state.value, cursor: state.cursor };
1758
+ return setState({ ...state });
1759
+ }
1760
+ if (mouse.button === 0 && mouse.press) {
1761
+ if (row < 0 || row >= at.rows) return setDrag(undefined);
1762
+ const cursor = offset(row);
1763
+ if (cursor === undefined) return;
1764
+ setDrag({ anchor: cursor, focus: cursor, value: state.value });
1765
+ // 点在翻过的地方时保持翻到的位置
1766
+ if (scrolled.current) scrolled.current = { ...scrolled.current, cursor };
1767
+ return setState({ ...state, cursor });
1768
+ }
1769
+ const drag = getDrag();
1770
+ if (!drag || drag.value !== state.value) return;
1771
+ if (mouse.button === DRAG) {
1772
+ const focus = offset(row);
1773
+ if (focus === undefined) return;
1774
+ setDrag({ ...drag, focus });
1775
+ if (scrolled.current) scrolled.current = { ...scrolled.current, cursor: focus };
1776
+ return setState({ ...state, cursor: focus });
1777
+ }
1778
+ if (mouse.button === 0 && !mouse.press && drag.anchor !== drag.focus) {
1779
+ onCopy(state.value.slice(Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)));
1780
+ }
1781
+ return;
1782
+ }
1783
+ // 别的键取消输入框里的选中;Ctrl+C 只取消选中(已经在松开时复制过了)
1784
+ const drag = getDrag();
1785
+ if (drag) {
1786
+ setDrag(undefined);
1787
+ if (key.ctrl && input === "c" && drag.anchor !== drag.focus && drag.value === state.value) return;
1788
+ }
1605
1789
  if (key.ctrl && input === "r")
1606
1790
  return history.current.length
1607
1791
  ? setSearch({ query: "", index: 0 })
@@ -1622,17 +1806,6 @@ function Prompt({
1622
1806
  lastEsc.current = Date.now();
1623
1807
  return;
1624
1808
  }
1625
- // 点击输入框里的文字:光标移到点的位置
1626
- const mouse = mouseEvent(input);
1627
- if (mouse) {
1628
- const at = place.current;
1629
- if (!at || mouse.button !== 0 || !mouse.press) return;
1630
- const row = mouse.y - at.y;
1631
- if (row < 0 || row >= at.rows) return;
1632
- const cursor = offsetAt(state.value, textWidth, at.first + row, mouse.x - at.x);
1633
- if (cursor !== undefined) setState({ ...state, cursor });
1634
- return;
1635
- }
1636
1809
  // 文字和回车在同一块里到达(输入很快时终端可能合并):插入文字后发送
1637
1810
  if (
1638
1811
  !key.ctrl &&
@@ -1643,8 +1816,9 @@ function Prompt({
1643
1816
  return submit(edit.insert(state, input.slice(0, -1)).value.trim());
1644
1817
  }
1645
1818
  if (key.return) {
1646
- // 行尾的 \ 加回车换行;Alt+Enter 也换行
1647
- if (key.meta) return set(edit.insert(state, "\n"));
1819
+ // 行尾的 \ 加回车换行;Alt+Enter 也换行;终端把 Shift+Enter 单独报上来时(kitty 键盘协议、modifyOtherKeys)也换行。
1820
+ // Ctrl+J(Windows Terminal 里 Ctrl+Enter 也是它)发的是 LF,不算回车,在 editKey 里当普通换行插入
1821
+ if (key.meta || key.shift) return set(edit.insert(state, "\n"));
1648
1822
  if (state.value.slice(0, state.cursor).endsWith("\\"))
1649
1823
  return set(edit.insert(edit.backspace(state), "\n"));
1650
1824
  const { pick, file } = derive();
@@ -1698,11 +1872,22 @@ function Prompt({
1698
1872
  const spec = keySpec(input, key);
1699
1873
  if (spec && handlers.key?.(spec)) return;
1700
1874
  const next = editKey(state, input, key);
1701
- if (next) set(next);
1875
+ if (next) {
1876
+ if (next.value !== state.value) typedAt = Date.now();
1877
+ set(next);
1878
+ }
1702
1879
  },
1703
1880
  { isActive: active },
1704
1881
  );
1705
1882
 
1883
+ const view = scrolled.current;
1884
+ const viewTop = view && view.value === state.value && view.cursor === state.cursor ? view.top : undefined;
1885
+ const drag = getDrag();
1886
+ const dragged: [number, number] | undefined =
1887
+ drag && drag.value === state.value && drag.anchor !== drag.focus
1888
+ ? [Math.min(drag.anchor, drag.focus), Math.max(drag.anchor, drag.focus)]
1889
+ : undefined;
1890
+
1706
1891
  // 对话框打开时隐藏但不卸载,输入到一半的内容和历史都保留
1707
1892
  return h(
1708
1893
  Box,
@@ -1735,6 +1920,8 @@ function Prompt({
1735
1920
  active,
1736
1921
  maxRows: inputRows,
1737
1922
  place,
1923
+ top: viewTop,
1924
+ selected: dragged,
1738
1925
  }),
1739
1926
  ),
1740
1927
  search
@@ -1822,6 +2009,25 @@ function around(selected: number, total: number, size: number): number {
1822
2009
  return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1823
2010
  }
1824
2011
 
2012
+ /** 用户上一次在输入框里打字的时间;发送之后清零 */
2013
+ let typedAt = 0;
2014
+ /** 打字停下这么久之后,对话框才把回车和字符当成回答 */
2015
+ const TYPING_GRACE = 500;
2016
+
2017
+ /**
2018
+ * 对话框弹出时用户正在输入框里打字(例如在排下一条消息时弹出审批):接着打出来的回车、数字不能当成回答。
2019
+ * 返回 true 表示这个键要丢掉。方向键、Esc 说明用户已经看到对话框了,不再拦
2020
+ */
2021
+ function typedThrough(input: string, key: Key): boolean {
2022
+ if (Date.now() - typedAt >= TYPING_GRACE) return false;
2023
+ if (key.escape || key.upArrow || key.downArrow || key.pageUp || key.pageDown || (key.ctrl && input === "c") || MOUSE.test(input)) {
2024
+ typedAt = 0;
2025
+ return false;
2026
+ }
2027
+ typedAt = Date.now();
2028
+ return true;
2029
+ }
2030
+
1825
2031
  /** 选择框一次最多显示几项 */
1826
2032
  const VISIBLE = 10;
1827
2033
  /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
@@ -1835,6 +2041,9 @@ function SelectDialog({
1835
2041
  const selection = useContext(SelectionContext);
1836
2042
  const [getSelected, setSelected] = useLive(0);
1837
2043
  const [getQuery, setQuery] = useLive("");
2044
+ /** 预览从第几行开始显示,以及它能翻到哪里、一页几行(放得下时 maxTop 是 0) */
2045
+ const [getTop, setTop] = useLive(0);
2046
+ const scrolling = useRef({ maxTop: 0, page: 1 });
1838
2047
  const { rows, columns } = useScreenSize();
1839
2048
  const filtering = dialog.choices.length > FILTER_FROM;
1840
2049
  const query = getQuery();
@@ -1852,14 +2061,27 @@ function SelectDialog({
1852
2061
  const visible = roomFor(rows, VISIBLE);
1853
2062
  // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画,底部的选项和提示也会被裁掉。
1854
2063
  // 按折行后的屏幕行数截断(一行长代码会占好几行),每一行单独显示、不再折行
1855
- const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4));
2064
+ const lines = !dialog.body ? [] : wrap(dialog.body, Math.max(1, columns - 4)).map(visibleRow);
1856
2065
  const room = Math.max(3, rows - Math.min(n, visible) - 16);
2066
+ // 放不下时 PgUp/PgDn 翻看预览(批准之前要能看完整个 diff),最后一行说明还有多少
2067
+ const page = room - 1;
2068
+ const maxTop = Math.max(0, lines.length - page);
2069
+ const top = Math.min(getTop(), maxTop);
2070
+ scrolling.current = { maxTop, page };
1857
2071
  const body =
1858
2072
  lines.length > room
1859
- ? [...lines.slice(0, room - 1), dim(`… ${lines.length - room + 1} more lines`)]
2073
+ ? [
2074
+ ...lines.slice(top, top + page),
2075
+ dim(
2076
+ top < maxTop
2077
+ ? `… ${lines.length - top - page} more lines · PgDn/PgUp to scroll`
2078
+ : `end of ${lines.length} lines · PgUp to scroll back`,
2079
+ ),
2080
+ ]
1860
2081
  : lines;
1861
2082
  useInput((input, key) => {
1862
2083
  if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2084
+ if (typedThrough(input, key)) return;
1863
2085
  const items = filtered();
1864
2086
  const n = items.length;
1865
2087
  const selected = Math.min(getSelected(), Math.max(0, n - 1));
@@ -1877,6 +2099,11 @@ function SelectDialog({
1877
2099
  }
1878
2100
  if (key.escape || (key.ctrl && input === "c"))
1879
2101
  return dialog.resolve(undefined);
2102
+ // 预览放不下时翻预览,否则翻选项
2103
+ const { maxTop, page } = scrolling.current;
2104
+ if (maxTop > 0 && (key.pageDown || key.pageUp)) {
2105
+ return setTop(Math.max(0, Math.min(maxTop, Math.min(getTop(), maxTop) + (key.pageDown ? page : -page))));
2106
+ }
1880
2107
  if (key.pageDown) return setSelected(Math.min(n - 1, selected + visible));
1881
2108
  if (key.pageUp) return setSelected(Math.max(0, selected - visible));
1882
2109
  if (filtering) {
@@ -1954,6 +2181,7 @@ function InputDialog({
1954
2181
  );
1955
2182
  useInput((input, key) => {
1956
2183
  if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2184
+ if (typedThrough(input, key)) return;
1957
2185
  const state = current();
1958
2186
  if (key.return) return dialog.resolve(state.value.trim());
1959
2187
  if (key.escape || (key.ctrl && input === "c"))