@hit-sudomaker/ccw 0.4.0 → 0.5.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.
@@ -1,390 +1,36 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import os from 'node:os';
3
- import { Box, Text, render, useAnimation, useApp, useInput, usePaste, useWindowSize } from 'ink';
4
- import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
5
- import stringWidth from 'string-width';
3
+ import { Box, Text, render, useInput, usePaste, useWindowSize, useApp } from 'ink';
4
+ import { useState, useRef, useLayoutEffect } from 'react';
6
5
  import wrapAnsi from 'wrap-ansi';
7
- import { BRAND, HOME_TITLE, safeText } from './render.js';
6
+ import stringWidth from 'string-width';
7
+ import { BACK_TO_HOME, BRAND, safeText, statusLine } from './render.js';
8
8
  const ACCENT = '#D97757';
9
- function isExit({ input, key }) {
10
- return key.ctrl && input === 'c';
11
- }
12
- function HomeHeader({ size }) {
13
- const platform = process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux';
14
- const system = `${platform} (${os.arch()})`;
15
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: ACCENT, children: '═'.repeat(Math.min(62, size.columns)) }), size.rows >= 28 && _jsx(Text, { children: " " }), size.rows >= 20 && size.columns >= 30 ? (BRAND.logo.map((line, index) => _jsx(Text, { color: ACCENT, bold: true, children: ` ${line}` }, index))) : (_jsxs(Text, { color: ACCENT, bold: true, children: [' ', "CCW"] })), size.rows >= 28 && _jsx(Text, { children: " " }), _jsxs(Text, { bold: true, wrap: "truncate-end", children: [' ', BRAND.title, " ", _jsx(Text, { dimColor: true, children: BRAND.version })] }), _jsxs(Text, { dimColor: true, children: [" ", BRAND.credit] }), size.rows >= 24 ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: ACCENT, children: '─'.repeat(Math.min(62, size.columns)) }), _jsx(Text, { bold: true, children: " \u5F53\u524D\u73AF\u5883\u72B6\u6001" }), _jsxs(Text, { children: [" 1. \u7CFB\u7EDF ", system] }), _jsxs(Text, { children: [" 2. Node ", process.version] }), _jsxs(Text, { wrap: "truncate-end", children: [" 3. \u4E3B\u76EE\u5F55 ", safeText(os.homedir())] })] })) : (_jsxs(_Fragment, { children: [_jsx(Text, { dimColor: true, children: ` ${system} · Node ${process.version}` }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [' ', safeText(os.homedir())] })] })), _jsx(Text, { color: ACCENT, children: '═'.repeat(Math.min(62, size.columns)) }), _jsx(Text, { bold: true, children: "\u8BF7\u9009\u62E9\uFF1A" })] }));
16
- }
17
- function Frame({ title, footer, page = 0, children }) {
18
- const terminalSize = useWindowSize();
19
- const size = { columns: Math.max(8, terminalSize.columns - 1), rows: Math.max(10, terminalSize.rows) };
20
- const [name = '', ...body] = safeText(title).split('\n');
21
- const details = useMemo(() => wrapAnsi(body.join('\n'), size.columns, { hard: true, trim: false }).split('\n').filter(Boolean), [title, size.columns]);
22
- const detailHeight = Math.min(Math.max(3, Math.floor(size.rows / 3) - 1), details.length);
23
- const offset = Math.min(page * Math.max(1, detailHeight), Math.max(0, details.length - detailHeight));
24
- const hasPages = details.length > detailHeight;
25
- const isHome = title === HOME_TITLE;
26
- const headerHeight = isHome
27
- ? 5 + (size.rows >= 28 ? 2 : 0) + (size.rows >= 20 && size.columns >= 30 ? 6 : 1) + (size.rows >= 24 ? 5 : 2)
28
- : 3 + detailHeight + (hasPages ? 1 : 0);
29
- const height = Math.max(1, size.rows - headerHeight - 4);
30
- return (_jsxs(Box, { flexDirection: "column", width: size.columns, height: size.rows - 1, children: [isHome ? (_jsx(HomeHeader, { size: size })) : (_jsxs(_Fragment, { children: [_jsx(Box, { borderStyle: "double", borderColor: ACCENT, width: Math.min(62, size.columns), paddingX: 1, flexShrink: 0, children: _jsxs(Text, { bold: true, color: ACCENT, wrap: "truncate-end", children: ["CCW \u00B7 ", name] }) }), details.slice(offset, offset + detailHeight).map((line, index) => (_jsx(Text, { children: line }, index))), hasPages && (_jsxs(Text, { dimColor: true, children: ["PgUp/PgDn \u00B7 ", offset + 1, "\u2013", offset + detailHeight, "/", details.length] }))] })), _jsx(Box, { flexDirection: "column", height: height, marginTop: 1, flexShrink: 0, children: children(height, size.columns) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, wrap: "truncate-end", children: footer }) })] }));
31
- }
32
- function Menu({ title, choices, focus, selection, change, interrupt, done }) {
33
- const initialCount = selection ? selection.rows.length + 2 : choices.length;
34
- const live = useRef({
35
- index: Math.max(0, Math.min(focus, initialCount - 1)),
36
- page: 0,
37
- ...(selection ? { selection } : {}),
38
- });
39
- const [state, setState] = useState(live.current);
40
- useInput((input, key) => {
41
- const prior = live.current;
42
- if (prior.result)
43
- return;
44
- const event = { input, key };
45
- let next = prior;
46
- const current = prior.selection;
47
- const row = current?.rows[prior.index];
48
- const count = current ? current.rows.length + 2 : choices.length;
49
- const toggle = () => (change ? { ...prior, selection: change({ kind: 'toggle', index: prior.index }) } : prior);
50
- if (isExit(event))
51
- interrupt();
52
- if (key.escape || isExit(event))
53
- next = { ...prior, result: { kind: 'cancel', index: prior.index } };
54
- else if (key.upArrow || key.downArrow)
55
- next = { ...prior, index: (prior.index + count + (key.upArrow ? -1 : 1)) % count };
56
- else if (key.pageDown || key.pageUp)
57
- next = { ...prior, page: Math.max(0, prior.page + (key.pageUp ? -1 : 1)) };
58
- else if (key.return)
59
- next =
60
- row?.enter === 'toggle'
61
- ? toggle()
62
- : {
63
- ...prior,
64
- result: {
65
- kind: !current || row ? 'open' : prior.index === current.rows.length ? 'submit' : 'cancel',
66
- index: prior.index,
67
- },
68
- };
69
- else if (current && input.toLowerCase() === 'r')
70
- next = { ...prior, result: { kind: 'refresh', index: prior.index } };
71
- else if (current && change && input.toLowerCase() === 'a')
72
- next = { ...prior, selection: change({ kind: 'all' }) };
73
- else if (row && input === ' ')
74
- next = toggle();
75
- if (next.selection && !next.result)
76
- next = { ...next, index: Math.min(next.index, next.selection.rows.length + 1) };
77
- live.current = next;
78
- setState(next);
79
- });
80
- useEffect(() => {
81
- if (state.result)
82
- done(state.result);
83
- }, [state.result, done]);
84
- const rows = useMemo(() => {
85
- const result = [];
86
- const labels = state.selection?.rows ?? choices.map(choice => (typeof choice === 'string' ? { label: choice } : choice));
87
- const labelWidth = Math.max(0, ...labels.filter(row => row.detail).map(row => stringWidth(row.label)));
88
- let previous;
89
- for (const [index, choice] of labels.entries()) {
90
- const group = choice.group;
91
- if (group && group !== previous)
92
- result.push({ label: group, detail: '', index: null, labelWidth: 0 });
93
- previous = group;
94
- result.push({
95
- label: choice.label,
96
- detail: choice.detail ?? '',
97
- index,
98
- labelWidth: choice.detail ? labelWidth : 0,
99
- });
100
- }
101
- if (state.selection)
102
- result.push({ label: state.selection.submitLabel, detail: '', index: labels.length, labelWidth: 0 }, { label: '返回主菜单', detail: '', index: labels.length + 1, labelWidth: 0 });
103
- return result;
104
- }, [choices, state.selection]);
105
- const currentRow = state.selection?.rows[state.index];
106
- const enter = currentRow?.enter === 'toggle'
107
- ? '勾选'
108
- : currentRow?.enter === 'edit'
109
- ? '编辑'
110
- : currentRow
111
- ? '详情'
112
- : state.index === state.selection?.rows.length
113
- ? '提交'
114
- : '返回';
115
- const footer = state.selection
116
- ? `空格勾选 · A 全选普通项 · R 刷新 · Enter ${enter} · Esc 返回`
117
- : '↑↓ 移动 · Enter 选择 · Esc 返回';
118
- return (_jsx(Frame, { title: state.selection?.title ?? title, page: state.page, footer: footer, children: (height, width) => {
119
- const activeRow = Math.max(0, rows.findIndex(row => row.index === state.index));
120
- const start = Math.max(0, Math.min(activeRow - Math.floor(height / 2), rows.length - height));
121
- return rows.slice(start, start + height).map((row, position) => {
122
- if (row.index === null) {
123
- const label = ` ── ${safeText(row.label)} `;
124
- return (_jsxs(Text, { color: ACCENT, dimColor: true, wrap: "truncate-end", children: [label, '─'.repeat(Math.max(0, Math.min(62, width) - stringWidth(label)))] }, `heading-${start + position}`));
125
- }
126
- const active = row.index === state.index;
127
- const selectedRow = state.selection?.rows[row.index];
128
- const prefix = `${active ? '›' : ' '} ${selectedRow ? (selectedRow.checked ? '[x] ' : '[ ] ') : ''}`;
129
- return (_jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { ...(active ? { color: ACCENT } : {}), bold: active, children: prefix }), _jsx(Box, { width: row.detail ? Math.min(row.labelWidth + 2, Math.max(10, width - 24)) : width - stringWidth(prefix), flexShrink: 0, children: _jsx(Text, { ...(active ? { color: ACCENT } : {}), bold: active, wrap: "truncate-end", children: safeText(row.label).replaceAll('\n', ' ') }) }), row.detail && (_jsx(Text, { ...(active ? { color: ACCENT } : {}), dimColor: !active, wrap: "truncate-end", children: safeText(row.detail) }))] }, row.index));
130
- });
131
- } }));
132
- }
133
- const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
134
- const characters = (text) => Array.from(segmenter.segment(text), part => part.segment);
135
- function editText(prior, event) {
136
- if ('key' in event) {
137
- const { key, input } = event;
138
- if (key.ctrl && input === 'u')
139
- return { text: [], cursor: 0 };
140
- if (key.leftArrow || key.rightArrow)
141
- return { ...prior, cursor: Math.max(0, Math.min(prior.text.length, prior.cursor + (key.leftArrow ? -1 : 1))) };
142
- if (key.home || key.end)
143
- return { ...prior, cursor: key.home ? 0 : prior.text.length };
144
- if (key.backspace && prior.cursor > 0)
145
- return { text: prior.text.filter((_part, index) => index !== prior.cursor - 1), cursor: prior.cursor - 1 };
146
- if (key.delete)
147
- return { ...prior, text: prior.text.filter((_part, index) => index !== prior.cursor) };
148
- if (key.ctrl || key.meta || key.tab)
149
- return prior;
150
- }
151
- const added = characters(safeText('paste' in event ? event.paste : event.input).replaceAll('\n', ' '));
152
- if (!added.length)
153
- return prior;
154
- return {
155
- text: [...prior.text.slice(0, prior.cursor), ...added, ...prior.text.slice(prior.cursor)],
156
- cursor: prior.cursor + added.length,
157
- };
158
- }
159
- function InlineForm({ title, fields, validate, interrupt, done, }) {
160
- const live = useRef({
161
- index: 0,
162
- edits: fields.map(field => ({ text: characters(field.value), cursor: characters(field.value).length })),
163
- problem: null,
164
- details: false,
165
- page: 0,
166
- finished: false,
167
- });
168
- const [state, setState] = useState(live.current);
169
- const dispatch = (event) => {
170
- const prior = live.current;
171
- if (prior.finished)
172
- return;
173
- if (prior.details) {
174
- let next = prior;
175
- if ('key' in event && (event.key.escape || event.key.return))
176
- next = { ...prior, details: false };
177
- else if ('key' in event && (event.key.pageUp || event.key.pageDown))
178
- next = { ...prior, page: Math.max(0, prior.page + (event.key.pageUp ? -1 : 1)) };
179
- else if ('key' in event && isExit(event)) {
180
- live.current = { ...prior, finished: true };
181
- interrupt();
182
- done(null);
183
- return;
184
- }
185
- live.current = next;
186
- setState(next);
187
- return;
188
- }
189
- let next = prior;
190
- if ('key' in event && (event.key.escape || isExit(event))) {
191
- live.current = { ...prior, finished: true };
192
- if (isExit(event))
193
- interrupt();
194
- done(null);
195
- return;
196
- }
197
- if ('key' in event &&
198
- (event.key.upArrow || event.key.downArrow || event.key.tab || (event.key.return && prior.index < fields.length))) {
199
- const direction = event.key.upArrow || (event.key.tab && event.key.shift) ? -1 : 1;
200
- const count = fields.length + 2 + Number(Boolean(prior.problem?.detail));
201
- next = { ...prior, index: (prior.index + count + direction) % count };
202
- }
203
- else if ('key' in event && event.key.return) {
204
- if (prior.index === fields.length + 2 && prior.problem?.detail) {
205
- live.current = { ...prior, details: true, page: 0 };
206
- setState(live.current);
207
- return;
208
- }
209
- if (prior.index === fields.length + 1) {
210
- live.current = { ...prior, finished: true };
211
- done(null);
212
- return;
213
- }
214
- const values = Object.fromEntries(fields.map((field, index) => [field.key, prior.edits[index]?.text.join('') ?? '']));
215
- const problem = validate(values);
216
- if (!problem) {
217
- live.current = { ...prior, finished: true };
218
- done(values);
219
- return;
220
- }
221
- next = {
222
- ...prior,
223
- problem,
224
- index: Math.max(0, fields.findIndex(field => field.key === problem.field)),
225
- };
226
- }
227
- else if (prior.index < fields.length) {
228
- next = {
229
- ...prior,
230
- problem: null,
231
- edits: prior.edits.map((edit, index) => (index === prior.index ? editText(edit, event) : edit)),
232
- };
233
- }
234
- live.current = next;
235
- setState(next);
236
- };
237
- useInput((input, key) => dispatch({ input, key }));
238
- usePaste(paste => dispatch({ paste }));
239
- if (state.details)
240
- return (_jsx(Frame, { title: `填写说明\n${state.problem?.detail ?? ''}`, page: state.page, footer: "PgUp/PgDn \u7FFB\u9875 \u00B7 Enter/Esc \u8FD4\u56DE", children: () => _jsx(Text, { color: ACCENT, children: "\u203A \u8FD4\u56DE\u7F16\u8F91" }) }));
241
- return (_jsx(Frame, { title: `${title}${state.problem ? `\n! ${state.problem.message}` : ''}`, footer: state.index < fields.length ? '输入/粘贴 · ↑↓/Tab 切换 · Esc 取消' : '↑↓ 选择 · Enter 确认 · Esc 取消', children: (height, width) => {
242
- const labels = [
243
- ...fields.map(field => field.label),
244
- '保存配置',
245
- '返回',
246
- ...(state.problem?.detail ? ['查看详情'] : []),
247
- ];
248
- const start = Math.max(0, Math.min(state.index - Math.floor(height / 2), labels.length - height));
249
- return labels.slice(start, start + height).map((label, offset) => {
250
- const index = start + offset;
251
- const active = index === state.index;
252
- const field = fields[index];
253
- const edit = state.edits[index];
254
- const value = field && edit ? (field.secret ? '•'.repeat(edit.text.length) : edit.text.join('')) : '';
255
- let display = value || field?.placeholder || '';
256
- if (active && edit) {
257
- const before = field?.secret ? '•'.repeat(edit.cursor) : edit.text.slice(0, edit.cursor).join('');
258
- const after = field?.secret
259
- ? '•'.repeat(edit.text.length - edit.cursor)
260
- : edit.text.slice(edit.cursor).join('');
261
- display = `${wrapAnsi(before, Math.max(1, width - 20), { hard: true, trim: false })
262
- .split('\n')
263
- .at(-1) ?? ''}▏${after || (!value ? (field?.placeholder ?? '') : '')}`;
264
- }
265
- return (_jsxs(Text, { ...(active ? { color: ACCENT } : {}), wrap: "truncate-end", children: [active ? '› ' : ' ', label.padEnd(15), safeText(display)] }, label));
266
- });
267
- } }));
268
- }
269
- function Waiting({ title, message = '检查环境', cancel, interrupt, }) {
270
- const { frame } = useAnimation({ interval: 120 });
271
- useInput((input, key) => {
272
- if (key.escape || isExit({ input, key })) {
273
- cancel();
274
- if (isExit({ input, key }))
275
- interrupt();
276
- }
277
- });
278
- return (_jsx(Frame, { title: title, footer: "Esc \u53D6\u6D88 \u00B7 Ctrl+C \u9000\u51FA", children: () => (_jsxs(Text, { color: ACCENT, children: [['⠋', '⠙', '⠹', '⠸'][frame % 4], " ", safeText(message)] })) }));
279
- }
280
- function toneColor(tone) {
281
- if (tone === 'accent')
282
- return ACCENT;
283
- if (tone === 'success')
284
- return 'green';
285
- if (tone === 'danger')
286
- return 'red';
287
- if (tone === 'warning')
288
- return 'yellow';
289
- return undefined;
290
- }
291
- function StatusRow({ row, text }) {
292
- const color = toneColor(row.tone);
293
- const name = safeText(row.title).replaceAll('\n', ' ');
294
- if (text !== undefined)
295
- return (_jsx(Text, { ...(color ? { color } : {}), dimColor: row.tone === 'muted', children: text }));
296
- return (_jsxs(Box, { children: [_jsx(Box, { width: 2, flexShrink: 0, children: _jsx(Text, { ...(color ? { color } : {}), dimColor: row.tone === 'muted', children: row.symbol }) }), _jsx(Box, { width: 10, flexShrink: 0, children: _jsx(Text, { ...(color ? { color } : {}), dimColor: row.tone === 'muted', children: row.status }) }), _jsx(Text, { wrap: "truncate-end", children: name })] }));
297
- }
298
- function DetailRow({ detail, width }) {
299
- const color = toneColor(detail.tone);
300
- const indent = width < 24 ? 2 : 12;
301
- return (_jsxs(Box, { marginLeft: indent, children: [detail.symbol && (_jsx(Box, { width: 2, flexShrink: 0, children: _jsx(Text, { ...(color ? { color } : {}), dimColor: detail.tone === 'muted', children: detail.symbol }) })), _jsx(Text, { dimColor: detail.tone === 'muted', wrap: "truncate-end", children: safeText(detail.text) })] }));
302
- }
303
- function runLines(view, width) {
304
- return view.rows.flatMap(row => {
305
- const status = width < 24
306
- ? wrapAnsi(`${row.symbol} ${row.status} ${safeText(row.title)}`, width, { hard: true, trim: false })
307
- .split('\n')
308
- .map(text => ({ kind: 'status', row, text }))
309
- : [{ kind: 'status', row }];
310
- return [
311
- ...status,
312
- ...row.details.flatMap(detail => {
313
- const { symbol, ...appearance } = detail;
314
- const indent = width < 24 ? 2 : 12;
315
- return wrapAnsi(safeText(detail.text), Math.max(1, width - indent - (symbol ? 2 : 0)), {
316
- hard: true,
317
- trim: false,
318
- })
319
- .split('\n')
320
- .map((text, index) => ({
321
- kind: 'detail',
322
- id: row.id,
323
- detail: { ...appearance, text, ...(symbol ? { symbol: index === 0 ? symbol : ' ' } : {}) },
324
- }));
325
- }),
326
- ];
327
- });
328
- }
329
- function RunScreen({ view, choices = [], focus = 0, cancelIndex = choices.length - 1, interrupt, done, }) {
330
- const [offset, setOffset] = useState(null);
331
- const [action, setAction] = useState(Math.max(0, Math.min(focus, choices.length - 1)));
332
- const finished = useRef(false);
333
- const viewport = useRef({ offset: 0, height: 1, total: 1 });
334
- useInput((input, key) => {
335
- const exit = isExit({ input, key });
336
- if (exit)
337
- interrupt();
338
- if (choices.length && (key.escape || exit) && !finished.current) {
339
- finished.current = true;
340
- done?.(cancelIndex);
341
- return;
342
- }
343
- if (choices.length && (key.upArrow || key.downArrow))
344
- setAction(previous => (previous + choices.length + (key.upArrow ? -1 : 1)) % choices.length);
345
- if (choices.length && key.return && !finished.current) {
346
- finished.current = true;
347
- done?.(action);
348
- return;
349
- }
350
- if (key.pageUp)
351
- setOffset(previous => Math.max(0, (previous ?? viewport.current.offset) - viewport.current.height));
352
- if (key.pageDown)
353
- setOffset(previous => Math.min(Math.max(0, viewport.current.total - viewport.current.height), (previous ?? viewport.current.offset) + viewport.current.height));
354
- if (key.end)
355
- setOffset(null);
356
- });
357
- const footer = choices.length
358
- ? '↑↓ 选择 · Enter 确认 · PgUp/PgDn 翻页 · Esc 返回'
359
- : 'PgUp/PgDn 翻页 · End 跟随 · Ctrl+C 停止';
360
- return (_jsx(Frame, { title: view.title, footer: footer, children: (height, width) => {
361
- const lines = runLines(view, width);
362
- const actionHeight = choices.length ? choices.length + 1 : 0;
363
- const available = Math.max(1, height - 1 - actionHeight);
364
- const visible = Math.max(1, available - (lines.length > available ? 1 : 0));
365
- const current = Math.max(0, lines.findIndex(line => line.kind === 'status' && line.row.id === view.activeId));
366
- const automatic = view.phase === 'result' ? 0 : Math.max(0, current - Math.floor(visible / 2));
367
- const start = Math.min(Math.max(0, lines.length - visible), offset ?? automatic);
368
- viewport.current = { offset: start, height: visible, total: lines.length };
369
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, wrap: "truncate-end", children: safeText(view.summary) }), lines
370
- .slice(start, start + visible)
371
- .map((line, index) => line.kind === 'status' ? (_jsx(StatusRow, { row: line.row, ...(line.text !== undefined ? { text: line.text } : {}) }, `${line.row.id}-status-${start + index}`)) : (_jsx(DetailRow, { detail: line.detail, width: width }, `${line.id}-detail-${start + index}`))), lines.length > visible && (_jsxs(Text, { dimColor: true, children: [start + 1, "\u2013", Math.min(start + visible, lines.length), "/", lines.length] })), choices.length > 0 && (_jsx(Box, { flexDirection: "column", marginTop: 1, children: choices.map((choice, index) => (_jsxs(Text, { ...(index === action ? { color: ACCENT } : {}), bold: index === action, children: [index === action ? '› ' : ' ', safeText(typeof choice === 'string' ? choice : `${choice.label} ${choice.detail ?? ''}`)] }, index))) }))] }));
372
- } }));
373
- }
374
- function Host({ children, ready, }) {
375
- const { suspendTerminal } = useApp();
376
- useLayoutEffect(() => {
377
- ready(suspendTerminal);
378
- }, [ready, suspendTerminal]);
379
- return children;
380
- }
381
- async function pauseReading() {
382
- // Ink 使用 readable 模式,pause() 可能不发事件;通知 Node 停止底层读取后再交接
383
- process.stdin.pause();
384
- process.stdin.emit('pause');
385
- await new Promise(resolve => process.nextTick(resolve));
386
- }
387
- /** 复用一个 Ink 实例切换页面,关闭时恢复终端;交接期间由外部命令使用终端 */
9
+ const BANNER_WIDTH = 62;
10
+ const MAX_RENDER_FPS = 30;
11
+ const LAYOUT = {
12
+ minimumColumns: 8,
13
+ minimumRows: 10,
14
+ defaultContentRows: 8,
15
+ menuPageOverheadRows: 10,
16
+ labelMinimumColumns: 10,
17
+ formDecorationColumns: 5,
18
+ groupHeadingPaddingColumns: 3,
19
+ headerRows: 3,
20
+ footerRows: 3,
21
+ sectionGapRows: 1,
22
+ homeCreditRows: 18,
23
+ homeExpandedRows: 24,
24
+ homeLogoColumns: 32,
25
+ homeFixedRows: 5,
26
+ homeEnvironmentRows: 5,
27
+ };
28
+ /**
29
+ * 装配复用单个 Ink 实例的终端适配器,首次显示页面时才接管终端
30
+ *
31
+ * @param interrupt - 用户按 Ctrl+C 时调用的中断通知,不由适配器直接退出进程
32
+ * @returns Terminal 实现及关闭方法;输入、取消与交接合同见 Terminal
33
+ */
388
34
  export function createTerminal(interrupt = () => { }) {
389
35
  let instance;
390
36
  let suspension;
@@ -406,7 +52,7 @@ export function createTerminal(interrupt = () => { }) {
406
52
  instance = render(tree, {
407
53
  alternateScreen: true,
408
54
  incrementalRendering: true,
409
- maxFps: 30,
55
+ maxFps: MAX_RENDER_FPS,
410
56
  exitOnCtrlC: false,
411
57
  patchConsole: false,
412
58
  });
@@ -415,7 +61,7 @@ export function createTerminal(interrupt = () => { }) {
415
61
  rejectPending?.(new Error('terminal-closed'));
416
62
  }, (error) => {
417
63
  closed = true;
418
- rejectPending?.(error instanceof Error ? error : new Error('terminal-failed', { cause: error }));
64
+ rejectPending?.(asError(error, 'terminal-failed'));
419
65
  });
420
66
  }
421
67
  };
@@ -442,23 +88,25 @@ export function createTerminal(interrupt = () => { }) {
442
88
  display(view(done));
443
89
  }
444
90
  catch (error) {
445
- rejectPending(error instanceof Error ? error : new Error('terminal-failed', { cause: error }));
91
+ rejectPending(asError(error, 'terminal-failed'));
446
92
  }
447
93
  });
448
94
  };
449
95
  return {
450
- choose(title, choices, focus = 0, cancelIndex = choices.length - 1) {
451
- return typeof title === 'string'
452
- ? prompt(done => (_jsx(Menu, { title: title, choices: choices, focus: focus, interrupt: interrupt, done: result => done(result.kind === 'cancel' ? cancelIndex : result.index) }, ++sequence)))
453
- : prompt(done => (_jsx(RunScreen, { view: title, choices: choices, focus: focus, cancelIndex: cancelIndex, interrupt: interrupt, done: done }, ++sequence)));
96
+ choose(title, choices, focus = 0, options) {
97
+ return prompt(done => (_jsx(Menu, { title: title, choices: choices, focus: focus, home: options?.home ?? false, interrupt: interrupt, done: result => done(result.kind === 'cancel' ? choices.length - 1 : result.index) }, ++sequence)));
454
98
  },
455
- select(page, change, focus = 0) {
456
- return prompt(done => (_jsx(Menu, { title: page.title, choices: [], selection: page, change: change, focus: focus, interrupt: interrupt, done: done }, ++sequence)));
99
+ select(page, change) {
100
+ return prompt(done => (_jsx(Menu, { title: page.title, choices: [], selection: page, change: change, focus: page.focus ?? 0, interrupt: interrupt, done: result => done(result.kind === 'edit'
101
+ ? { kind: 'edit', index: result.index }
102
+ : result.kind === 'cancel'
103
+ ? 'cancel'
104
+ : 'submit') }, ++sequence)));
457
105
  },
458
106
  form(title, fields, validate) {
459
107
  return prompt(done => (_jsx(InlineForm, { title: title, fields: fields, validate: validate, interrupt: interrupt, done: done }, ++sequence)));
460
108
  },
461
- async wait(title, work, signal, firstFrame) {
109
+ async wait(title, work, signal) {
462
110
  if (signal?.aborted)
463
111
  return null;
464
112
  const reading = new AbortController();
@@ -471,7 +119,7 @@ export function createTerminal(interrupt = () => { }) {
471
119
  const key = ++sequence;
472
120
  const result = prompt(done => {
473
121
  finish = done;
474
- return (_jsx(Waiting, { title: title, ...(firstFrame !== undefined ? { message: firstFrame } : {}), cancel: cancel, interrupt: interrupt }, key));
122
+ return _jsx(Waiting, { title: title, cancel: cancel, interrupt: interrupt }, key);
475
123
  });
476
124
  const update = (message) => {
477
125
  if (!reading.signal.aborted)
@@ -481,7 +129,7 @@ export function createTerminal(interrupt = () => { }) {
481
129
  .then(() => work(reading.signal, update))
482
130
  .then(finish, (error) => {
483
131
  if (!reading.signal.aborted)
484
- rejectPending?.(error instanceof Error ? error : new Error('inspection-failed', { cause: error }));
132
+ rejectPending?.(asError(error, 'inspection-failed'));
485
133
  });
486
134
  try {
487
135
  return await result;
@@ -504,6 +152,7 @@ export function createTerminal(interrupt = () => { }) {
504
152
  finally {
505
153
  isSuspended = false;
506
154
  await ownership.resume();
155
+ // 交互命令仅限执行屏活动期发起;恢复重放最近执行视图
507
156
  if (progressView !== undefined)
508
157
  display(_jsx(RunScreen, { view: progressView, interrupt: interrupt }));
509
158
  // 快速任务可能在 readable 监听恢复前结束;重新启动读取但不消费输入
@@ -515,6 +164,7 @@ export function createTerminal(interrupt = () => { }) {
515
164
  if (!isSuspended)
516
165
  display(_jsx(RunScreen, { view: view, interrupt: interrupt }));
517
166
  },
167
+ /** 终止待决输入并卸载界面;等待 Ink 退出和清理,失败时拒绝 Promise */
518
168
  async close() {
519
169
  closed = true;
520
170
  rejectPending?.(new Error('terminal-closed'));
@@ -527,3 +177,261 @@ export function createTerminal(interrupt = () => { }) {
527
177
  },
528
178
  };
529
179
  }
180
+ function Host({ children, ready, }) {
181
+ const { suspendTerminal } = useApp();
182
+ useLayoutEffect(() => {
183
+ ready(suspendTerminal);
184
+ }, [ready, suspendTerminal]);
185
+ return children;
186
+ }
187
+ function Menu({ title, choices, selection, change, focus, home = false, interrupt, done, }) {
188
+ const [page, setPage] = useState(selection);
189
+ const rows = page ? [...page.rows, { label: page.submitLabel }, { label: BACK_TO_HOME }] : choices;
190
+ const size = useWindowSize();
191
+ const labelWidth = Math.max(0, ...rows.map(row => (typeof row === 'string' ? 0 : stringWidth(row.label))));
192
+ const displayRows = [];
193
+ let previousGroup;
194
+ for (const [index, choice] of rows.entries()) {
195
+ const row = typeof choice === 'string' ? { label: choice } : choice;
196
+ if (row.group && row.group !== previousGroup)
197
+ displayRows.push({ row: { label: '── ' + row.group }, index: null });
198
+ displayRows.push({ row, index });
199
+ previousGroup = row.group;
200
+ }
201
+ const [active, setActive] = useState(Math.max(0, Math.min(focus, rows.length - 1)));
202
+ const activeRef = useRef(active);
203
+ const move = (index) => {
204
+ activeRef.current = index;
205
+ setActive(index);
206
+ };
207
+ const [offset, setOffset] = useState(0);
208
+ const toggle = (event) => {
209
+ if (change)
210
+ setPage(change(event));
211
+ };
212
+ useInput((input, key) => {
213
+ const index = activeRef.current;
214
+ if (key.ctrl && input === 'c') {
215
+ interrupt();
216
+ done({ kind: 'cancel', index });
217
+ }
218
+ else if (key.escape)
219
+ done({ kind: 'cancel', index });
220
+ else if (key.pageDown || key.pageUp) {
221
+ if (title.includes('\n'))
222
+ setOffset(previous => Math.max(0, previous + (key.pageUp ? -1 : 1)));
223
+ else
224
+ move(Math.max(0, Math.min(rows.length - 1, index + (key.pageUp ? -1 : 1) * Math.max(1, size.rows - LAYOUT.menuPageOverheadRows))));
225
+ }
226
+ else if (key.home)
227
+ move(0);
228
+ else if (key.end)
229
+ move(rows.length - 1);
230
+ else if (key.upArrow)
231
+ move((index + rows.length - 1) % rows.length);
232
+ else if (key.downArrow)
233
+ move((index + 1) % rows.length);
234
+ else if (page && input.toLowerCase() === 'a')
235
+ toggle({ kind: 'all' });
236
+ else if (page && input === ' ' && index < page.rows.length)
237
+ toggle({ kind: 'toggle', index });
238
+ else if (key.return) {
239
+ if (page && index === page.rows.length + 1)
240
+ done({ kind: 'cancel', index });
241
+ else if (page?.rows[index]?.editable)
242
+ done({ kind: 'edit', index });
243
+ else if (page && index < page.rows.length)
244
+ toggle({ kind: 'toggle', index });
245
+ else
246
+ done({ kind: 'confirm', index });
247
+ }
248
+ });
249
+ return (_jsx(Frame, { title: title, home: home, page: offset, reserveRows: Math.min(rows.length, LAYOUT.defaultContentRows) + 1, footer: page ? '↑↓ 移动 · 空格勾选 · A 全选 · Enter 编辑/确认 · Esc 返回' : '↑↓ 移动 · Enter 确认 · Esc 返回', children: (height, width) => {
250
+ const visible = Math.max(1, height - 1);
251
+ const activeRow = displayRows.findIndex(row => row.index === active);
252
+ const start = Math.max(0, Math.min(activeRow - Math.floor(visible / 2), displayRows.length - visible));
253
+ return (_jsxs(_Fragment, { children: [displayRows.slice(start, start + visible).map(({ row, index }, offset) => {
254
+ if (index === null)
255
+ return (_jsxs(Text, { color: ACCENT, dimColor: true, wrap: "truncate-end", children: [' ' + safeText(row.label) + ' ', '─'.repeat(Math.max(0, Math.min(BANNER_WIDTH, width) - stringWidth(row.label) - LAYOUT.groupHeadingPaddingColumns))] }, 'group-' + (start + offset)));
256
+ return (_jsxs(Box, { flexShrink: 0, children: [_jsxs(Text, { bold: index === active, ...(index === active ? { color: ACCENT } : {}), children: [index === active ? '› ' : ' ', page && index < page.rows.length ? (page.rows[index]?.checked ? '[x] ' : '[ ] ') : ''] }), _jsx(Box, { width: row.detail
257
+ ? Math.min(labelWidth + 2, Math.max(LAYOUT.labelMinimumColumns, Math.floor(width / 2)))
258
+ : undefined, flexShrink: row.detail ? 0 : 1, children: _jsx(Text, { bold: index === active, wrap: "truncate-end", ...(index === active ? { color: ACCENT } : {}), children: safeText(row.label) }) }), row.detail && (_jsx(Text, { dimColor: index !== active, wrap: "truncate-end", ...(index === active ? { color: ACCENT } : {}), children: safeText(row.detail) }))] }, index));
259
+ }), displayRows.length > visible && (_jsxs(Text, { dimColor: true, children: [start + 1, "\u2013", Math.min(displayRows.length, start + visible), "/", displayRows.length] }))] }));
260
+ } }));
261
+ }
262
+ function InlineForm({ title, fields, validate, interrupt, done, }) {
263
+ const [values, setValues] = useState(() => Object.fromEntries(fields.map(field => [field.key, field.value])));
264
+ const valuesRef = useRef(values);
265
+ const cursorRef = useRef(Array.from(fields[0]?.value ?? '').length);
266
+ const [cursor, setCursor] = useState(cursorRef.current);
267
+ const position = (next) => {
268
+ cursorRef.current = next;
269
+ setCursor(next);
270
+ };
271
+ const replace = (field, text, next) => {
272
+ valuesRef.current = { ...valuesRef.current, [field.key]: text };
273
+ setValues(valuesRef.current);
274
+ position(next);
275
+ setProblem(null);
276
+ };
277
+ const [active, setActive] = useState(0);
278
+ const activeRef = useRef(active);
279
+ const move = (index) => {
280
+ activeRef.current = index;
281
+ setActive(index);
282
+ position(Array.from(valuesRef.current[fields[index]?.key ?? ''] ?? '').length);
283
+ };
284
+ const [problem, setProblem] = useState(null);
285
+ const size = useWindowSize();
286
+ const append = (text) => {
287
+ const field = fields[activeRef.current];
288
+ if (field) {
289
+ const characters = Array.from(valuesRef.current[field.key] ?? '');
290
+ const inserted = Array.from(safeText(text).replace(/\r?\n/g, ' '));
291
+ characters.splice(cursorRef.current, 0, ...inserted);
292
+ replace(field, characters.join(''), cursorRef.current + inserted.length);
293
+ }
294
+ };
295
+ usePaste(append);
296
+ useInput((input, key) => {
297
+ const index = activeRef.current;
298
+ const field = fields[index];
299
+ const characters = Array.from(valuesRef.current[field?.key ?? ''] ?? '');
300
+ if (key.ctrl && input === 'c') {
301
+ interrupt();
302
+ done(null);
303
+ }
304
+ else if (key.escape)
305
+ done(null);
306
+ else if (key.upArrow)
307
+ move(Math.max(0, index - 1));
308
+ else if (key.tab && key.shift)
309
+ move(Math.max(0, index - 1));
310
+ else if (key.downArrow || key.tab)
311
+ move(Math.min(fields.length + 1, index + 1));
312
+ else if (field && key.leftArrow)
313
+ position(Math.max(0, cursorRef.current - 1));
314
+ else if (field && key.rightArrow)
315
+ position(Math.min(characters.length, cursorRef.current + 1));
316
+ else if (field && key.home)
317
+ position(0);
318
+ else if (field && key.end)
319
+ position(characters.length);
320
+ else if (field && key.ctrl && input === 'u')
321
+ replace(field, '', 0);
322
+ else if (key.return) {
323
+ if (index === fields.length + 1)
324
+ done(null);
325
+ else if (index < fields.length - 1)
326
+ move(index + 1);
327
+ else {
328
+ const error = validate(valuesRef.current);
329
+ if (error) {
330
+ setProblem(error);
331
+ move(Math.max(0, fields.findIndex(field => field.key === error.field)));
332
+ }
333
+ else
334
+ done(valuesRef.current);
335
+ }
336
+ }
337
+ else if (key.backspace || key.delete) {
338
+ if (field) {
339
+ const next = Math.max(0, cursorRef.current - (key.backspace ? 1 : 0));
340
+ if (!key.backspace || cursorRef.current > 0)
341
+ characters.splice(next, 1);
342
+ replace(field, characters.join(''), next);
343
+ }
344
+ }
345
+ else if (!key.ctrl && !key.meta && input)
346
+ append(input);
347
+ });
348
+ return (_jsx(Frame, { title: title, footer: "Tab \u5207\u6362 \u00B7 \u2190\u2192 \u7F16\u8F91 \u00B7 Ctrl+U \u6E05\u7A7A \u00B7 Enter \u7EE7\u7EED \u00B7 Esc \u53D6\u6D88", children: height => {
349
+ const visible = Math.max(1, height - 2 - (problem ? 1 : 0));
350
+ const start = Math.max(0, Math.min(active - Math.floor(visible / 2), fields.length - visible));
351
+ return (_jsxs(_Fragment, { children: [fields.slice(start, start + visible).map((field, offset) => {
352
+ const index = start + offset;
353
+ const text = field.secret
354
+ ? '•'.repeat(Array.from(values[field.key] ?? '').length)
355
+ : (values[field.key] ?? '');
356
+ const characters = Array.from(text);
357
+ const caret = index === active ? cursor : characters.length;
358
+ const available = Math.max(1, size.columns - stringWidth(field.label) - LAYOUT.formDecorationColumns);
359
+ let from = caret;
360
+ while (from > 0 && stringWidth(characters.slice(from - 1, caret).join('')) < available)
361
+ from--;
362
+ let to = caret;
363
+ while (to < characters.length && stringWidth(characters.slice(from, to + 1).join('')) < available)
364
+ to++;
365
+ return (_jsxs(Text, { wrap: "truncate-end", ...(index === active ? { color: ACCENT } : {}), children: [index === active ? '› ' : ' ', field.label, "\uFF1A", safeText(characters.slice(from, caret).join('')), index === active && _jsx(Text, { inverse: true, children: characters[caret] ?? ' ' }), safeText(characters.slice(caret + (index === active ? 1 : 0), to).join('')), !values[field.key] && field.placeholder ? ' ' + field.placeholder : ''] }, field.key));
366
+ }), _jsxs(Text, { ...(active === fields.length ? { color: ACCENT } : {}), children: [active === fields.length ? '› ' : ' ', "\u4FDD\u5B58"] }), _jsxs(Text, { ...(active === fields.length + 1 ? { color: ACCENT } : {}), children: [active === fields.length + 1 ? '› ' : ' ', "\u8FD4\u56DE"] }), problem && _jsx(Text, { color: "red", children: problem.message })] }));
367
+ } }));
368
+ }
369
+ function Waiting({ title, message, cancel, interrupt, }) {
370
+ useInput((input, key) => {
371
+ if (key.ctrl && input === 'c') {
372
+ interrupt();
373
+ cancel();
374
+ }
375
+ else if (key.escape)
376
+ cancel();
377
+ });
378
+ return (_jsx(Frame, { title: title, footer: "Esc \u53D6\u6D88", children: () => _jsx(Text, { children: message ?? '请稍候…' }) }));
379
+ }
380
+ function RunScreen({ view, interrupt }) {
381
+ const [page, setPage] = useState(0);
382
+ useInput((input, key) => {
383
+ if (key.ctrl && input === 'c')
384
+ interrupt();
385
+ else if (key.pageDown)
386
+ setPage(previous => previous + 1);
387
+ else if (key.pageUp)
388
+ setPage(previous => Math.max(0, previous - 1));
389
+ });
390
+ return (_jsx(Frame, { title: view.title, footer: "PgUp/PgDn \u67E5\u770B\u8FDB\u5EA6 \u00B7 Ctrl+C \u505C\u6B62\u540E\u7EED\u64CD\u4F5C", children: (height, width) => {
391
+ const lines = wrapAnsi(view.rows.map(statusLine).join('\n'), width, { hard: true }).split('\n');
392
+ const visible = Math.max(1, height - 2);
393
+ const start = Math.min(page * visible, Math.max(0, lines.length - visible));
394
+ return (_jsxs(_Fragment, { children: [_jsx(Text, { dimColor: true, children: view.summary }), _jsx(Text, { children: lines.slice(start, start + visible).join('\n') }), lines.length > visible && (_jsxs(Text, { dimColor: true, children: [start + 1, "\u2013", Math.min(lines.length, start + visible), "/", lines.length] }))] }));
395
+ } }));
396
+ }
397
+ function homeLayout(width, height) {
398
+ const showEnvironment = height >= LAYOUT.homeExpandedRows;
399
+ const showCredit = height >= LAYOUT.homeCreditRows;
400
+ const showLogo = showEnvironment && width >= LAYOUT.homeLogoColumns;
401
+ return {
402
+ showEnvironment,
403
+ showCredit,
404
+ showLogo,
405
+ rows: LAYOUT.homeFixedRows +
406
+ (showLogo ? BRAND.logo.length : 1) +
407
+ (showCredit ? 1 : 0) +
408
+ (showEnvironment ? LAYOUT.homeEnvironmentRows : showCredit ? 1 : 0),
409
+ };
410
+ }
411
+ function HomeHeader({ width, height }) {
412
+ const platform = process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux';
413
+ const { showLogo, showCredit, showEnvironment } = homeLayout(width, height);
414
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: ACCENT, children: '═'.repeat(Math.min(BANNER_WIDTH, width)) }), showLogo ? (BRAND.logo.map((line, index) => (_jsx(Text, { color: ACCENT, bold: true, children: ' ' + line }, index)))) : (_jsxs(Text, { bold: true, color: ACCENT, children: [' ', "CCW"] })), _jsxs(Text, { bold: true, wrap: "truncate-end", children: [' ', BRAND.title, " ", _jsxs(Text, { dimColor: true, children: ["V", BRAND.versionNumber] })] }), showCredit && _jsxs(Text, { dimColor: true, children: [" ", BRAND.credit] }), showEnvironment ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: ACCENT, children: '─'.repeat(Math.min(BANNER_WIDTH, width)) }), _jsx(Text, { bold: true, children: " \u5F53\u524D\u73AF\u5883\u72B6\u6001" }), _jsxs(Text, { children: [' ', "1. \u7CFB\u7EDF ", platform, " (", os.arch(), ")"] }), _jsxs(Text, { children: [" 2. Node ", process.version] }), _jsxs(Text, { wrap: "truncate-end", children: [" 3. \u4E3B\u76EE\u5F55 ", safeText(os.homedir())] })] })) : (showCredit && (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [' ', platform, " (", os.arch(), ") \u00B7 Node ", process.version] }))), _jsx(Text, { color: ACCENT, children: '═'.repeat(Math.min(BANNER_WIDTH, width)) }), _jsx(Text, { bold: true, children: "\u8BF7\u9009\u62E9\uFF1A" })] }));
415
+ }
416
+ function Frame({ title, footer, page = 0, reserveRows = LAYOUT.defaultContentRows, home = false, children, }) {
417
+ const size = useWindowSize();
418
+ const width = Math.max(LAYOUT.minimumColumns, size.columns - 1);
419
+ const height = Math.max(LAYOUT.minimumRows, size.rows - 1);
420
+ const [name = '', ...body] = safeText(title).split('\n');
421
+ const lines = wrapAnsi(body.join('\n'), width, { hard: true }).split('\n').filter(Boolean);
422
+ const detailHeight = Math.min(Math.max(1, height - reserveRows - LAYOUT.headerRows - LAYOUT.footerRows - LAYOUT.sectionGapRows), lines.length);
423
+ const start = Math.min(page * detailHeight, Math.max(0, lines.length - detailHeight));
424
+ const hasPages = lines.length > detailHeight;
425
+ const headerHeight = home ? homeLayout(width, height).rows : LAYOUT.headerRows + detailHeight + (hasPages ? 1 : 0);
426
+ const contentHeight = Math.max(1, height - headerHeight - LAYOUT.footerRows);
427
+ return (_jsxs(Box, { flexDirection: "column", width: width, height: height, children: [home ? (_jsx(HomeHeader, { width: width, height: height })) : (_jsxs(_Fragment, { children: [_jsx(Box, { borderStyle: "double", borderColor: ACCENT, paddingX: 1, width: Math.min(BANNER_WIDTH, width), flexShrink: 0, children: _jsxs(Text, { bold: true, color: ACCENT, wrap: "truncate-end", children: ["CCW \u00B7 ", name] }) }), lines.slice(start, start + detailHeight).map((line, index) => (_jsx(Text, { children: line }, index))), hasPages && (_jsxs(Text, { dimColor: true, children: ["PgUp/PgDn \u9605\u8BFB \u00B7 ", start + 1, "\u2013", Math.min(lines.length, start + detailHeight), "/", lines.length] }))] })), _jsx(Box, { flexDirection: "column", height: contentHeight, marginTop: 1, flexShrink: 0, children: children(contentHeight, width) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, wrap: "truncate-end", children: footer }) })] }));
428
+ }
429
+ async function pauseReading() {
430
+ // Ink 使用 readable 模式,pause() 可能不发事件;通知 Node 停止底层读取后再交接
431
+ process.stdin.pause();
432
+ process.stdin.emit('pause');
433
+ await new Promise(resolve => process.nextTick(resolve));
434
+ }
435
+ function asError(error, fallback) {
436
+ return error instanceof Error ? error : new Error(fallback);
437
+ }