@uncarved/jade 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +6 -2
  2. package/dist/distro.d.ts +4 -0
  3. package/dist/distro.js +36 -2
  4. package/dist/distro.js.map +1 -1
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/main.js +110 -20
  9. package/dist/main.js.map +1 -1
  10. package/dist/plugins/policy.d.ts +21 -5
  11. package/dist/plugins/policy.js +325 -53
  12. package/dist/plugins/policy.js.map +1 -1
  13. package/dist/plugins/prompts.d.ts +2 -0
  14. package/dist/plugins/prompts.js +13 -0
  15. package/dist/plugins/prompts.js.map +1 -1
  16. package/dist/plugins/repeats.js +42 -7
  17. package/dist/plugins/repeats.js.map +1 -1
  18. package/dist/provider.d.ts +62 -3
  19. package/dist/provider.js +145 -6
  20. package/dist/provider.js.map +1 -1
  21. package/dist/sessions.d.ts +9 -0
  22. package/dist/sessions.js +14 -1
  23. package/dist/sessions.js.map +1 -1
  24. package/dist/sys.d.ts +5 -1
  25. package/dist/sys.js +3 -2
  26. package/dist/sys.js.map +1 -1
  27. package/dist/tools/screenshot.d.ts +15 -0
  28. package/dist/tools/screenshot.js +162 -0
  29. package/dist/tools/screenshot.js.map +1 -0
  30. package/dist/tools/shell.d.ts +6 -0
  31. package/dist/tools/shell.js +26 -7
  32. package/dist/tools/shell.js.map +1 -1
  33. package/dist/ui/configure.js +89 -5
  34. package/dist/ui/configure.js.map +1 -1
  35. package/dist/ui/screen.d.ts +5 -0
  36. package/dist/ui/screen.js.map +1 -1
  37. package/dist/ui/transcript.js +36 -0
  38. package/dist/ui/transcript.js.map +1 -1
  39. package/dist/ui/tui.d.ts +17 -0
  40. package/dist/ui/tui.js +298 -75
  41. package/dist/ui/tui.js.map +1 -1
  42. package/package.json +3 -3
  43. package/src/distro.ts +40 -3
  44. package/src/index.ts +1 -0
  45. package/src/main.ts +106 -19
  46. package/src/plugins/policy.ts +317 -43
  47. package/src/plugins/prompts.ts +15 -0
  48. package/src/plugins/repeats.ts +42 -8
  49. package/src/provider.ts +165 -10
  50. package/src/sessions.ts +14 -1
  51. package/src/sys.ts +5 -2
  52. package/src/tools/screenshot.ts +171 -0
  53. package/src/tools/shell.ts +25 -7
  54. package/src/ui/configure.ts +95 -8
  55. package/src/ui/screen.ts +2 -0
  56. package/src/ui/transcript.ts +32 -0
  57. package/src/ui/tui.tsx +410 -122
package/src/ui/tui.tsx CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  useState,
23
23
  useSyncExternalStore,
24
24
  } from "react";
25
+ import stringWidth from "string-width";
25
26
  import wrapAnsi from "wrap-ansi";
26
27
  import { mentionAt, mentionText, rankPaths } from "../mentions.ts";
27
28
  import { edit, empty, layout, type EditState } from "./editor.ts";
@@ -33,6 +34,16 @@ import {
33
34
  type StatusInfo,
34
35
  } from "./screen.ts";
35
36
 
37
+ /**
38
+ * 界面可用的尺寸:宽度比终端少一列。
39
+ * Ink 增量重画时每行写成「内容 + ESC[K」;一行正好占满终端宽度时光标停在最后一列(等待换行),
40
+ * 紧跟的 ESC[K 会把最后一个字符擦掉,输入框之类的右边框就缺了一块。留出最后一列就不会这样
41
+ */
42
+ function useScreenSize(): { columns: number; rows: number } {
43
+ const { columns, rows } = useWindowSize();
44
+ return { columns: Math.max(1, columns - 1), rows };
45
+ }
46
+
36
47
  export interface TuiHandlers {
37
48
  /** 用户在输入框里提交了一行(消息或命令) */
38
49
  submit(text: string): void;
@@ -66,7 +77,8 @@ type Dialog =
66
77
  interface UiState {
67
78
  /** 对话内容变化时递增,让界面重画 */
68
79
  version: number;
69
- live?: { kind: "text" | "thinking"; text: string };
80
+ /** 还没结束的正文:完整的行已经移进对话,这里只有最后不完整的一行(思考是对话里的一项,见 Thinking) */
81
+ live?: { text: string };
70
82
  /** 对话区离底部滚上去了多少行;0 表示跟着最新的输出 */
71
83
  scroll: number;
72
84
  busy?: { label: string; since: number };
@@ -88,10 +100,12 @@ const wrap = (text: string, width: number) =>
88
100
  * 对话里的一项:普通的一行,或者可以点击展开、收起的一段。
89
101
  * - details:折叠起来的完整内容
90
102
  * - oneRow:收起时只占一行,放不下的部分截掉,展开时完整显示
91
- * - title:展开时代替 text 显示的标题(例如思考收起时显示最新的一行,展开时显示"thinking")
103
+ * - title:展开时代替 text 显示的标题
104
+ * - think:思考;收起时按宽度现排一行(思考中显示最新的进展,结束后显示用了多久),展开时显示全文
92
105
  */
93
106
  interface Line {
94
107
  text: string;
108
+ think?: Thinking;
95
109
  details?: string;
96
110
  oneRow?: boolean;
97
111
  title?: string;
@@ -109,14 +123,65 @@ function oneRow(text: string, width: number): { row: string; cut: boolean } {
109
123
 
110
124
  /** 这一项能不能展开:有折叠的内容,或者收起时被截掉了一部分 */
111
125
  function foldable(l: Line, width: number): boolean {
126
+ if (l.think) return l.think.text.trim() !== "";
112
127
  return l.details !== undefined || (Boolean(l.oneRow) && oneRow(l.text, width).cut);
113
128
  }
114
129
 
115
- /** 思考收起时显示的一行:最新的非空行 */
116
- const thinkingHead = (text: string) =>
117
- dim(`✻ ${text.split("\n").findLast((l) => l.trim())?.trim() ?? "thinking"}`);
130
+ /** 一段思考:start、end 是开始和结束的时间(毫秒),没有 end 表示还在思考 */
131
+ interface Thinking {
132
+ text: string;
133
+ start: number;
134
+ end?: number;
135
+ }
136
+
137
+ const elapsed = (t: Thinking) =>
138
+ `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
139
+
140
+ /** 按显示宽度取 text 末尾最多 cols 列;截掉了开头时以 … 开头 */
141
+ export function tail(text: string, cols: number): string {
142
+ if (stringWidth(text) <= cols) return text;
143
+ const chars = [...text];
144
+ let out = "";
145
+ let w = 1;
146
+ for (let i = chars.length - 1; i >= 0; i--) {
147
+ const cw = stringWidth(chars[i]!);
148
+ if (w + cw > cols) break;
149
+ out = chars[i] + out;
150
+ w += cw;
151
+ }
152
+ return `…${out}`;
153
+ }
154
+
155
+ /**
156
+ * 思考收起时的一行(不含展开标记):思考中显示"✻ Thinking 12s · "加上最新一行的末尾,跟着模型实时往前走;
157
+ * 结束后显示"✻ Thought for 12s"
158
+ */
159
+ function thinkingRow(t: Thinking, width: number): string {
160
+ if (t.end !== undefined) return dim(`✻ Thought for ${elapsed(t)}`);
161
+ const label = `✻ Thinking ${elapsed(t)}`;
162
+ const latest = t.text
163
+ .split("\n")
164
+ .findLast((l) => l.trim())
165
+ ?.trim()
166
+ .replace(/\s+/g, " ");
167
+ // 留出 " · "、" ▸" 和一列余量
168
+ const room = width - stringWidth(label) - 6;
169
+ return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
170
+ }
118
171
 
119
172
  function wrapLine(l: Line, width: number): string[] {
173
+ if (l.think) {
174
+ if (!foldable(l, width)) return [thinkingRow(l.think, width)];
175
+ if (!l.open) return [`${thinkingRow(l.think, width)}${dim(" ▸")}`];
176
+ const t = l.think;
177
+ const title = dim(t.end === undefined ? `✻ Thinking ${elapsed(t)}` : `✻ Thought for ${elapsed(t)}`);
178
+ const body = t.text
179
+ .replace(/\s+$/, "")
180
+ .split("\n")
181
+ .map((r) => (r ? dim(` ${r}`) : r))
182
+ .join("\n");
183
+ return [...wrap(`${title}${dim(" ▾")}`, width), ...wrap(body, width)];
184
+ }
120
185
  if (!foldable(l, width)) return wrap(l.text, width);
121
186
  if (!l.open) {
122
187
  const head = l.oneRow ? oneRow(l.text, width).row : l.text;
@@ -296,34 +361,36 @@ export function tuiScreen(opts: TuiOptions): Screen {
296
361
  const store = new Store(opts.status);
297
362
 
298
363
  /**
299
- * 结束或推进流式块。正文:已经完整的行移进对话,只把最后不完整的一行留在底部;
300
- * 思考:整块留在底部只显示最新的一行,结束时(all)合成一个可展开的项,收起时也只显示最新的一行
364
+ * 正在进行的思考:一开始就作为一项放进对话(可以点击展开),之后的增量攒起来,每隔一小段时间改写一次那一项。
365
+ * 收起时只占一行,显示模型最新想到了哪里;结束时换成用了多久
301
366
  */
367
+ let thinking:
368
+ | { id: string; think: Thinking; timer?: ReturnType<typeof setTimeout> }
369
+ | undefined;
370
+ let thinkingCount = 0;
371
+ const redrawThinking = () => {
372
+ if (!thinking) return;
373
+ clearTimeout(thinking.timer);
374
+ thinking.timer = undefined;
375
+ store.amend(thinking.id, () => {});
376
+ };
377
+ const endThinking = () => {
378
+ if (!thinking) return;
379
+ thinking.think.end = Date.now();
380
+ redrawThinking();
381
+ thinking = undefined;
382
+ };
383
+
384
+ /** 推进正文:已经完整的行移进对话,只把最后不完整的一行留在底部;all 时全部移进去,连同思考一起结束 */
302
385
  const flushLive = (all = false) => {
386
+ if (all) endThinking();
303
387
  const live = store.state.live;
304
388
  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
389
  const lines = live.text.split("\n");
321
390
  const rest = all ? "" : lines.pop()!;
322
391
  if (all && lines.at(-1) === "") lines.pop();
323
392
  store.append(lines);
324
- store.update({
325
- live: rest || !all ? { kind: live.kind, text: rest } : undefined,
326
- });
393
+ store.update({ live: rest || !all ? { text: rest } : undefined });
327
394
  };
328
395
 
329
396
  const ask = <T,>(dialog: Dialog) =>
@@ -403,18 +470,27 @@ export function tuiScreen(opts: TuiOptions): Screen {
403
470
  });
404
471
  },
405
472
  stream(kind, text) {
406
- const live = store.state.live;
407
- if (live && live.kind !== kind) {
408
- flushLive(true);
409
- store.update({ live: undefined });
473
+ if (kind === "thinking") {
474
+ if (store.state.live) {
475
+ flushLive(true);
476
+ store.update({ live: undefined });
477
+ }
478
+ if (!thinking) {
479
+ if (!text.trim()) return;
480
+ const think: Thinking = { text: "", start: Date.now() };
481
+ thinking = { id: `\0thinking-${thinkingCount++}`, think };
482
+ store.append([""], { id: thinking.id, think });
483
+ }
484
+ thinking.think.text += text;
485
+ thinking.timer ??= setTimeout(redrawThinking, 50);
486
+ return;
410
487
  }
488
+ endThinking();
411
489
  if (!store.state.live) {
412
- if (kind === "text") text = text.replace(/^\n+/, "");
490
+ text = text.replace(/^\n+/, "");
413
491
  if (!text) return;
414
492
  }
415
- store.update({
416
- live: { kind, text: (store.state.live?.text ?? "") + text },
417
- });
493
+ store.update({ live: { text: (store.state.live?.text ?? "") + text } });
418
494
  if (text.includes("\n")) flushLive();
419
495
  },
420
496
  endStream() {
@@ -449,6 +525,8 @@ export function tuiScreen(opts: TuiOptions): Screen {
449
525
  resolve: () => {},
450
526
  }),
451
527
  clear() {
528
+ clearTimeout(thinking?.timer);
529
+ thinking = undefined;
452
530
  store.clear();
453
531
  },
454
532
  async close() {
@@ -472,6 +550,15 @@ export function tuiScreen(opts: TuiOptions): Screen {
472
550
  */
473
551
  const MOUSE = /^\[<(\d+);\d+;(\d+)([Mm])$/;
474
552
  const WHEEL_LINES = 3;
553
+ /** 终端矮于这么多行时标题只占一行 */
554
+ const COMPACT_ROWS = 24;
555
+
556
+ /**
557
+ * 底部的菜单、选择框、多行输入最多占多少行:终端很矮时整个界面会高过终端,
558
+ * 超出的部分被裁掉,输入框的边框和状态栏就显示不全了
559
+ */
560
+ const roomFor = (rows: number, max: number) =>
561
+ Math.max(3, Math.min(max, Math.floor((rows - 10) / 2)));
475
562
 
476
563
  function App({
477
564
  store,
@@ -488,7 +575,7 @@ function App({
488
575
  }) {
489
576
  const state = useSyncExternalStore(store.subscribe, store.get);
490
577
  const dialog = state.dialogs[0];
491
- const { columns, rows } = useWindowSize();
578
+ const { columns, rows } = useScreenSize();
492
579
 
493
580
  // 对话区占掉标题和底部之外的全部高度,只画能看见的那几行
494
581
  const ref = useRef<DOMElement>(null);
@@ -497,11 +584,7 @@ function App({
497
584
  const done = store.lines(width);
498
585
  // 还没结束的流式块和正在运行的工具的进度:思考只显示最新的一行,进度每个工具一行
499
586
  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
- : []),
587
+ ...(state.live?.text ? wrap(state.live.text, width) : []),
505
588
  ...state.progress.map((p) => oneRow(p.line, width).row),
506
589
  ];
507
590
  const total = done.length + live.length;
@@ -572,7 +655,11 @@ function App({
572
655
  >
573
656
  {/* 垫的空白放在外层:里面这层在重画那一帧和平时一样高,对话区的 top(相对父节点)不变,点击换算的行号不会差一行 */}
574
657
  <Box flexDirection="column" flexGrow={1} overflowY="hidden">
575
- <Header status={state.status} version={version} />
658
+ <Header
659
+ status={state.status}
660
+ version={version}
661
+ compact={rows < COMPACT_ROWS}
662
+ />
576
663
  <Box
577
664
  ref={ref}
578
665
  flexDirection="column"
@@ -618,7 +705,7 @@ function App({
618
705
  active={!dialog}
619
706
  onSubmit={() => store.scrollBy(-max, max)}
620
707
  />
621
- <StatusBar status={state.status} />
708
+ <StatusBar status={state.status} width={Math.max(10, columns - 2)} />
622
709
  </Box>
623
710
  </Box>
624
711
  </Box>
@@ -648,10 +735,37 @@ function Bot() {
648
735
  );
649
736
  }
650
737
 
651
- function Header({ status, version }: { status: StatusInfo; version: string }) {
738
+ function Header({
739
+ status,
740
+ version,
741
+ compact,
742
+ }: {
743
+ status: StatusInfo;
744
+ version: string;
745
+ /** 终端很矮时只占一行,把高度留给对话和输入框 */
746
+ compact: boolean;
747
+ }) {
748
+ const { columns } = useScreenSize();
749
+ if (compact)
750
+ return (
751
+ <Box flexShrink={0} paddingX={1}>
752
+ <Text wrap="truncate-end">
753
+ <Text color="cyan" bold>
754
+ jade
755
+ </Text>
756
+ <Text dimColor> · </Text>
757
+ <Text color="cyan">{status.model}</Text>
758
+ <Text dimColor> · </Text>
759
+ <Text>{status.cwd}</Text>
760
+ {status.branch ? (
761
+ <Text color="magenta"> ({status.branch})</Text>
762
+ ) : null}
763
+ </Text>
764
+ </Box>
765
+ );
652
766
  return (
653
767
  <Box flexShrink={0} borderStyle="round" borderColor="cyan" paddingX={1}>
654
- <Bot />
768
+ {columns >= 50 ? <Bot /> : null}
655
769
  <Box flexDirection="column" flexGrow={1} flexShrink={1}>
656
770
  <Text wrap="truncate-end">
657
771
  <Text color="cyan" bold>
@@ -696,14 +810,50 @@ function Spinner({ label, since }: { label: string; since: number }) {
696
810
  const seconds = Math.floor((now - since) / 1000);
697
811
  return (
698
812
  <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>
813
+ <Text wrap="truncate-end">
814
+ <Text color="cyan">{FRAMES[Math.floor(now / 100) % FRAMES.length]} </Text>
815
+ <Text>{label}… </Text>
816
+ <Text dimColor>({seconds}s · esc to interrupt)</Text>
817
+ </Text>
702
818
  </Box>
703
819
  );
704
820
  }
705
821
 
706
- function StatusBar({ status }: { status: StatusInfo }) {
822
+ /**
823
+ * 状态栏的一段,段之间用 " · " 隔开。放不下时按步骤缩短:shortAt 是换成短写法 short 的那一步,
824
+ * dropAt 是去掉整段的那一步;数字大的先做,没有 dropAt 的段一直保留
825
+ */
826
+ interface Segment {
827
+ text: string;
828
+ short?: string;
829
+ shortAt?: number;
830
+ dropAt?: number;
831
+ color?: string;
832
+ dim?: boolean;
833
+ }
834
+
835
+ /** 在 width 列里放下尽量多的内容(保持原来的顺序) */
836
+ export function fitSegments(segments: Segment[], width: number): Segment[] {
837
+ const kept = segments.map((s) => ({ ...s }));
838
+ const total = () =>
839
+ kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
840
+ const steps = kept
841
+ .flatMap((s) => [
842
+ ...(s.short !== undefined && s.shortAt !== undefined
843
+ ? [{ s, at: s.shortAt, drop: false }]
844
+ : []),
845
+ ...(s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []),
846
+ ])
847
+ .sort((a, b) => b.at - a.at);
848
+ for (const { s, drop } of steps) {
849
+ if (total() <= width) break;
850
+ if (drop) kept.splice(kept.indexOf(s), 1);
851
+ else s.text = s.short!;
852
+ }
853
+ return kept;
854
+ }
855
+
856
+ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
707
857
  const ctx = status.context;
708
858
  const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
709
859
  /** 离自动压缩还有多远:到阈值的 85% 起变黄 */
@@ -718,37 +868,83 @@ function StatusBar({ status }: { status: StatusInfo }) {
718
868
  : status.mode === "plan"
719
869
  ? "magenta"
720
870
  : "green";
871
+ const speed = status.speed;
872
+ // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
873
+ const segments: Segment[] = [
874
+ {
875
+ text: `${status.mode} (shift+tab)`,
876
+ short: status.mode,
877
+ shortAt: 6,
878
+ color: modeColor,
879
+ },
880
+ ctx
881
+ ? {
882
+ text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)${ctx.compactAt ? `, compacts at ${tokens(ctx.compactAt)}` : ""}`,
883
+ short: `ctx ${pct}%`,
884
+ shortAt: 4,
885
+ color: nearCompact ? "yellow" : undefined,
886
+ dim: !nearCompact,
887
+ }
888
+ : { text: "ctx —", dim: true },
889
+ ...(speed
890
+ ? [
891
+ {
892
+ text: `${speed.live ? "~" : ""}${speed.tps >= 100 ? Math.round(speed.tps) : speed.tps.toFixed(1)} tok/s`,
893
+ dropAt: 3,
894
+ dim: true,
895
+ },
896
+ ]
897
+ : []),
898
+ ...(status.cache !== undefined
899
+ ? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }]
900
+ : []),
901
+ ...(status.spent
902
+ ? [
903
+ {
904
+ text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
905
+ short: `${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
906
+ shortAt: 8,
907
+ dropAt: 5,
908
+ dim: true,
909
+ },
910
+ ]
911
+ : []),
912
+ {
913
+ text: "PgUp/PgDn scroll · click ▸ to expand · shift+drag to select",
914
+ short: "click ▸ to expand",
915
+ shortAt: 10,
916
+ dropAt: 9,
917
+ dim: true,
918
+ },
919
+ ];
920
+ const shown = fitSegments(segments, width);
721
921
  return (
722
922
  <Box paddingX={1}>
723
923
  <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
924
+ {shown.map((s, i) => (
925
+ <Text key={i}>
926
+ {i ? <Text dimColor> · </Text> : null}
927
+ <Text color={s.color} dimColor={s.dim}>
928
+ {s.text}
929
+ </Text>
741
930
  </Text>
742
- )}
743
- <Text dimColor>
744
- {" "}
745
- · PgUp/PgDn scroll · click ▸ to expand · shift+drag to select
746
- </Text>
931
+ ))}
747
932
  </Text>
748
933
  </Box>
749
934
  );
750
935
  }
751
936
 
937
+ /** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
938
+ function Hint({ variants, width }: { variants: string[]; width: number }) {
939
+ const text =
940
+ variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1)!;
941
+ return (
942
+ <Text dimColor wrap="truncate-end">
943
+ {text}
944
+ </Text>
945
+ );
946
+ }
947
+
752
948
  const tokens = (n: number) =>
753
949
  n >= 1_000_000
754
950
  ? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M`
@@ -813,6 +1009,7 @@ function EditableText({
813
1009
  mask,
814
1010
  placeholder,
815
1011
  active,
1012
+ maxRows = Infinity,
816
1013
  }: {
817
1014
  state: EditState;
818
1015
  width: number;
@@ -820,6 +1017,8 @@ function EditableText({
820
1017
  mask?: boolean;
821
1018
  placeholder?: string;
822
1019
  active: boolean;
1020
+ /** 最多显示几行;输入更长时只显示光标附近的几行 */
1021
+ maxRows?: number;
823
1022
  }) {
824
1023
  const ref = useRef<DOMElement>(null);
825
1024
  // 只用来在布局变化后重画一次、重新计算光标位置;它给的是相对父元素的坐标,光标要的是相对整个输出
@@ -829,7 +1028,15 @@ function EditableText({
829
1028
  const cursor = mask
830
1029
  ? [...state.value.slice(0, state.cursor)].length
831
1030
  : state.cursor;
832
- const { rows, row, col } = layout(shown, cursor, width - prefix.length);
1031
+ const all = layout(shown, cursor, width - prefix.length);
1032
+ const { col } = all;
1033
+ // 行数超过 maxRows 时滚动,光标所在的行总在可见范围里
1034
+ const first = Math.max(
1035
+ 0,
1036
+ Math.min(all.row - maxRows + 1, all.rows.length - maxRows),
1037
+ );
1038
+ const rows = all.rows.slice(first, first + maxRows);
1039
+ const row = all.row - first;
833
1040
 
834
1041
  // 光标位置要在渲染时设:useCursor 在这次提交时交给 Ink,跟这一帧一起画出来。
835
1042
  // 放在 useEffect 里会晚一帧,光标总是停在上一次按键的位置(只移动光标时最明显)。
@@ -845,15 +1052,19 @@ function EditableText({
845
1052
  return (
846
1053
  <Box ref={ref} flexDirection="column">
847
1054
  {state.value === "" && placeholder ? (
848
- <Text>
1055
+ <Text wrap="truncate-end">
849
1056
  <Text color="cyan">{prefix}</Text>
850
1057
  <Text dimColor>{placeholder}</Text>
851
1058
  </Text>
852
1059
  ) : (
853
1060
  rows.map((r, i) => (
854
- <Text key={i} wrap="truncate-end">
1061
+ <Text key={first + i} wrap="truncate-end">
855
1062
  <Text color="cyan">
856
- {i === 0 ? prefix : " ".repeat(prefix.length)}
1063
+ {first + i === 0
1064
+ ? prefix
1065
+ : i === 0
1066
+ ? "↑".padEnd(prefix.length)
1067
+ : " ".repeat(prefix.length)}
857
1068
  </Text>
858
1069
  {r}
859
1070
  </Text>
@@ -898,7 +1109,11 @@ function Prompt({
898
1109
  const browsing = useRef(-1);
899
1110
  const draft = useRef("");
900
1111
  const lastCtrlC = useRef(0);
901
- const { columns } = useWindowSize();
1112
+ const { columns, rows } = useScreenSize();
1113
+ /** 补全菜单、搜索结果最多显示几项;输入框最多几行 */
1114
+ const menuRows = roomFor(rows, MENTION_ROWS);
1115
+ const inputRows = roomFor(rows, 10);
1116
+ const hintWidth = Math.max(10, columns - 3);
902
1117
  // @ 引用补全用的路径;排好的结果按(路径表,查询)缓存,按键处理和渲染都要用时不重复排
903
1118
  const [getPaths, setPaths] = useLive<string[]>([]);
904
1119
  const ranked = useRef<{ paths: string[]; query: string; result: string[] }>(
@@ -983,10 +1198,9 @@ function Prompt({
983
1198
  };
984
1199
  }, [mentioning]);
985
1200
  // 结果多时只显示选中项附近的几条
986
- const first = Math.max(
987
- 0,
988
- Math.min(hit - Math.floor(MENTION_ROWS / 2), results.length - MENTION_ROWS),
989
- );
1201
+ const first = around(hit, results.length, menuRows);
1202
+ const firstMatch = around(Math.max(0, matches.indexOf(pick!)), matches.length, menuRows);
1203
+ const firstFound = around(Math.max(0, found.indexOf(file!)), found.length, menuRows);
990
1204
 
991
1205
  const set = (s: EditState) => {
992
1206
  setState(s);
@@ -1163,6 +1377,7 @@ function Prompt({
1163
1377
  prefix="search history› "
1164
1378
  placeholder="type to filter"
1165
1379
  active={active}
1380
+ maxRows={inputRows}
1166
1381
  />
1167
1382
  ) : (
1168
1383
  <EditableText
@@ -1172,16 +1387,19 @@ function Prompt({
1172
1387
  placeholder={
1173
1388
  busy
1174
1389
  ? "Type to queue a message · esc to interrupt"
1175
- : "Message jade · / commands · @ files · ↑ or ctrl+r for history"
1390
+ : columns >= 70
1391
+ ? "Message jade · / commands · @ files · ↑ or ctrl+r for history"
1392
+ : "Message jade · / commands · @ files"
1176
1393
  }
1177
1394
  active={active}
1395
+ maxRows={inputRows}
1178
1396
  />
1179
1397
  )}
1180
1398
  </Box>
1181
1399
  {search ? (
1182
1400
  <Box flexDirection="column" paddingX={2}>
1183
1401
  {results.length ? (
1184
- results.slice(first, first + MENTION_ROWS).map((h, i) => {
1402
+ results.slice(first, first + menuRows).map((h, i) => {
1185
1403
  const on = first + i === hit;
1186
1404
  return (
1187
1405
  <Text
@@ -1198,14 +1416,17 @@ function Prompt({
1198
1416
  ) : (
1199
1417
  <Text dimColor> no match</Text>
1200
1418
  )}
1201
- <Text dimColor>
1202
- {" "}
1203
- ↑↓ or ctrl+r select · enter/tab put in the input · esc cancel
1204
- </Text>
1419
+ <Hint
1420
+ width={hintWidth}
1421
+ variants={[
1422
+ " ↑↓ or ctrl+r select · enter/tab put in the input · esc cancel",
1423
+ " ↑↓ select · enter use · esc cancel",
1424
+ ]}
1425
+ />
1205
1426
  </Box>
1206
1427
  ) : matches.length ? (
1207
1428
  <Box flexDirection="column" paddingX={2}>
1208
- {matches.map((c) => {
1429
+ {matches.slice(firstMatch, firstMatch + menuRows).map((c) => {
1209
1430
  const on = c === pick;
1210
1431
  return (
1211
1432
  <Text key={c.name} wrap="truncate-end">
@@ -1217,11 +1438,17 @@ function Prompt({
1217
1438
  </Text>
1218
1439
  );
1219
1440
  })}
1220
- <Text dimColor> ↑↓ select · enter run · tab complete</Text>
1441
+ <Hint
1442
+ width={hintWidth}
1443
+ variants={[
1444
+ ` ↑↓ select · enter run · tab complete${matches.length > menuRows ? ` · ${matches.length} commands` : ""}`,
1445
+ " ↑↓ · enter run · tab complete",
1446
+ ]}
1447
+ />
1221
1448
  </Box>
1222
1449
  ) : found.length ? (
1223
1450
  <Box flexDirection="column" paddingX={2}>
1224
- {found.map((p) => {
1451
+ {found.slice(firstFound, firstFound + menuRows).map((p) => {
1225
1452
  const on = p === file;
1226
1453
  return (
1227
1454
  <Text
@@ -1235,11 +1462,14 @@ function Prompt({
1235
1462
  </Text>
1236
1463
  );
1237
1464
  })}
1238
- <Text dimColor>
1239
- {" "}
1240
- ↑↓ select · enter/tab insert the path · the file's content is sent
1241
- with the message
1242
- </Text>
1465
+ <Hint
1466
+ width={hintWidth}
1467
+ variants={[
1468
+ " ↑↓ select · enter/tab insert the path · the file's content is sent with the message",
1469
+ " ↑↓ select · enter/tab insert the path",
1470
+ " ↑↓ · enter insert",
1471
+ ]}
1472
+ />
1243
1473
  </Box>
1244
1474
  ) : notice ? (
1245
1475
  <Text color="yellow"> {notice}</Text>
@@ -1251,8 +1481,15 @@ function Prompt({
1251
1481
  /** @ 补全最多显示几项 */
1252
1482
  const MENTION_ROWS = 8;
1253
1483
 
1484
+ /** 长列表只显示 size 项时,为了让第 selected 项在中间附近,从第几项开始显示 */
1485
+ function around(selected: number, total: number, size: number): number {
1486
+ return Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
1487
+ }
1488
+
1254
1489
  /** 选择框一次最多显示几项 */
1255
1490
  const VISIBLE = 10;
1491
+ /** 选项多于这么多时可以打字筛选(这时 j/k 和数字键不再是快捷键) */
1492
+ const FILTER_FROM = 10;
1256
1493
 
1257
1494
  function SelectDialog({
1258
1495
  dialog,
@@ -1260,12 +1497,25 @@ function SelectDialog({
1260
1497
  dialog: Extract<Dialog, { kind: "select" }>;
1261
1498
  }) {
1262
1499
  const [getSelected, setSelected] = useLive(0);
1263
- const selected = getSelected();
1264
- const n = dialog.choices.length;
1265
- const { rows } = useWindowSize();
1500
+ const [getQuery, setQuery] = useLive("");
1501
+ const { rows, columns } = useScreenSize();
1502
+ const filtering = dialog.choices.length > FILTER_FROM;
1503
+ const query = getQuery();
1504
+ /** 筛选后的选项和它们原来的序号 */
1505
+ const filtered = () => {
1506
+ const q = getQuery().toLowerCase();
1507
+ return dialog.choices
1508
+ .map((c, i) => ({ c, i }))
1509
+ .filter(({ c }) => !q || `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(q));
1510
+ };
1511
+ const items = filtered();
1512
+ const n = items.length;
1513
+ const selected = Math.min(getSelected(), Math.max(0, n - 1));
1514
+ // 终端矮时少显示几项,加上预览一起不超过终端的高度
1515
+ const visible = roomFor(rows, VISIBLE);
1266
1516
  // 预览(例如要写入的文件)过长时截断:整个界面高过终端时 Ink 会每帧清屏重画
1267
1517
  const lines = dialog.body?.split("\n") ?? [];
1268
- const room = Math.max(3, rows - Math.min(n, VISIBLE) - 16);
1518
+ const room = Math.max(3, rows - Math.min(n, visible) - 16);
1269
1519
  const body =
1270
1520
  lines.length > room
1271
1521
  ? [
@@ -1274,24 +1524,44 @@ function SelectDialog({
1274
1524
  ].join("\n")
1275
1525
  : dialog.body;
1276
1526
  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);
1527
+ const items = filtered();
1528
+ const n = items.length;
1529
+ const selected = Math.min(getSelected(), Math.max(0, n - 1));
1530
+ if (key.upArrow || (!filtering && input === "k"))
1531
+ return n && setSelected((selected - 1 + n) % n);
1532
+ if (key.downArrow || (!filtering && input === "j"))
1533
+ return n && setSelected((selected + 1) % n);
1534
+ if (key.return) {
1535
+ if (n) dialog.resolve(items[selected]!.c.value);
1536
+ return;
1537
+ }
1538
+ if (key.escape && filtering && getQuery()) {
1539
+ setQuery("");
1540
+ return setSelected(0);
1541
+ }
1282
1542
  if (key.escape || (key.ctrl && input === "c"))
1283
1543
  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));
1544
+ if (key.pageDown) return setSelected(Math.min(n - 1, selected + visible));
1545
+ if (key.pageUp) return setSelected(Math.max(0, selected - visible));
1546
+ if (filtering) {
1547
+ if (key.backspace || key.delete) {
1548
+ setQuery([...getQuery()].slice(0, -1).join(""));
1549
+ return setSelected(0);
1550
+ }
1551
+ if (key.ctrl || key.meta || key.tab || MOUSE.test(input)) return;
1552
+ const text = input.replace(/[\x00-\x1f\x7f]/g, "");
1553
+ if (text) {
1554
+ setQuery(getQuery() + text);
1555
+ setSelected(0);
1556
+ }
1557
+ return;
1558
+ }
1286
1559
  const digit = Number(input);
1287
1560
  if (Number.isInteger(digit) && digit >= 1 && digit <= Math.min(n, 9))
1288
- dialog.resolve(dialog.choices[digit - 1]!.value);
1561
+ dialog.resolve(items[digit - 1]!.c.value);
1289
1562
  });
1290
1563
  // 选项多时只显示选中项附近的一段
1291
- const start = Math.max(
1292
- 0,
1293
- Math.min(selected - Math.floor(VISIBLE / 2), n - VISIBLE),
1294
- );
1564
+ const start = around(selected, n, visible);
1295
1565
  return (
1296
1566
  <Box
1297
1567
  flexDirection="column"
@@ -1300,30 +1570,48 @@ function SelectDialog({
1300
1570
  paddingX={1}
1301
1571
  marginTop={1}
1302
1572
  >
1303
- <Text bold>{dialog.title}</Text>
1573
+ <Text bold wrap="truncate-end">
1574
+ {dialog.title}
1575
+ </Text>
1304
1576
  {body ? <Text>{body}</Text> : null}
1305
- <Box flexDirection="column" marginTop={1}>
1577
+ {filtering ? (
1578
+ <Text wrap="truncate-end">
1579
+ <Text color="cyan">filter› </Text>
1580
+ {query ? (
1581
+ <Text>{query}</Text>
1582
+ ) : (
1583
+ <Text dimColor>type to filter {dialog.choices.length} items</Text>
1584
+ )}
1585
+ </Text>
1586
+ ) : null}
1587
+ <Box flexDirection="column" marginTop={filtering ? 0 : 1}>
1306
1588
  {start > 0 ? <Text dimColor> ↑ {start} more</Text> : null}
1307
- {dialog.choices.slice(start, start + VISIBLE).map((c, j) => {
1308
- const i = start + j;
1589
+ {n === 0 ? <Text dimColor> no match</Text> : null}
1590
+ {items.slice(start, start + visible).map(({ c, i }, j) => {
1591
+ const on = start + j === selected;
1309
1592
  return (
1310
1593
  <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}
1594
+ <Text color={on ? "cyan" : undefined} bold={on}>
1595
+ {on ? "❯ " : " "}
1596
+ {filtering ? "" : `${i + 1}. `}
1597
+ {c.label}
1317
1598
  </Text>
1318
1599
  {c.hint ? <Text dimColor> {c.hint}</Text> : null}
1319
1600
  </Text>
1320
1601
  );
1321
1602
  })}
1322
- {start + VISIBLE < n ? (
1323
- <Text dimColor> ↓ {n - start - VISIBLE} more</Text>
1603
+ {start + visible < n ? (
1604
+ <Text dimColor> ↓ {n - start - visible} more</Text>
1324
1605
  ) : null}
1325
1606
  </Box>
1326
- <Text dimColor>↑↓ select · enter confirm · esc cancel</Text>
1607
+ <Hint
1608
+ width={Math.max(10, columns - 4)}
1609
+ variants={
1610
+ filtering
1611
+ ? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"]
1612
+ : ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"]
1613
+ }
1614
+ />
1327
1615
  </Box>
1328
1616
  );
1329
1617
  }
@@ -1339,7 +1627,7 @@ function InputDialog({
1339
1627
  cursor: initial.length,
1340
1628
  });
1341
1629
  const state = current();
1342
- const { columns } = useWindowSize();
1630
+ const { columns } = useScreenSize();
1343
1631
  usePaste((text) =>
1344
1632
  setState(edit.insert(current(), text.replace(/\r?\n/g, ""))),
1345
1633
  );