@namewta/skills-hub 0.1.16 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,7 @@ node /path/to/skills-hub/install.mjs install --skill system-herdr-core
29
29
  npx @namewta/skills-hub install --domain upstream-skills --dry-run
30
30
  ```
31
31
 
32
- 交互界面支持按名称、分组或中文用途搜索,整组选择和跨组混选。使用 ↑/↓ 移动、←/→ 翻页、Tab 勾选、Enter 确认;搜索和翻页保留已选项。非交互环境使用带 `--domain`、`--skill` 或 `--all` 的安装命令。
32
+ 交互界面默认勾选当前项目已安装的技能。使用 ↑/↓ 移动、Tab 展开或收拢领域、空格勾选、←/→ 翻页,按 Enter 查看安装确认。按 `/` 可搜索名称、分组或中文用途。非交互环境使用带 `--domain`、`--skill` 或 `--all` 的安装命令。
33
33
 
34
34
  技能安装到当前项目的 `.agents/skills/<技能名>/`。重复安装时,相同内容保持不变,有差异的同名技能先备份再替换。安装器只复制文件,不执行技能中的工具;技能是否自动加载由所用 Agent 决定,也可以直接读取对应的 `SKILL.md`。
35
35
 
package/cli.mjs CHANGED
@@ -2,7 +2,9 @@ import * as prompts from '@clack/prompts';
2
2
  import pc from 'picocolors';
3
3
  import stringWidth from 'string-width';
4
4
  import wrapAnsi from 'wrap-ansi';
5
- import { createInstaller, select, main } from './install.mjs';
5
+ import { join } from 'node:path';
6
+ import { createInstaller, select, main, readUtf8, repositoryRoot } from './install.mjs';
7
+ import { isNpmInstallation, latestUpdate, installUpdate } from './scripts/update-cli.mjs';
6
8
  import { treeSelect } from './tree-select.mjs';
7
9
  export { matchesSkillSearch } from './tree-select.mjs';
8
10
 
@@ -12,7 +14,8 @@ export function formatSummary(names, columns = process.stdout.columns ?? 80) {
12
14
  return wrapAnsi(`${pc.bold(label)}${' '.repeat(Math.max(1, 8 - stringWidth(label)))}${names.join('、')}`, width, { hard: true });
13
15
  }
14
16
 
15
- export async function interactive({ argv = [], project = process.cwd(), ui = prompts, choose = treeSelect } = {}) {
17
+ export async function interactive({ argv = [], project = process.cwd(), ui = prompts, choose = treeSelect,
18
+ checkUpdate = isNpmInstallation(repositoryRoot) ? latestUpdate : undefined, update = installUpdate } = {}) {
16
19
  if (argv.some(value => !['install', '--replace', '--dry-run'].includes(value))) {
17
20
  throw new Error('交互安装只接受 install、--replace 和 --dry-run。');
18
21
  }
@@ -23,18 +26,32 @@ export async function interactive({ argv = [], project = process.cwd(), ui = pro
23
26
  };
24
27
  try {
25
28
  ui.intro(pc.cyan('skills-hub · 按需安装中文技能'));
29
+ const dryRun = argv.includes('--dry-run');
30
+ if (checkUpdate && !dryRun) {
31
+ const { version } = JSON.parse(readUtf8(join(repositoryRoot, 'package.json')));
32
+ const latest = await checkUpdate(version);
33
+ if (latest && await ask(ui.select({
34
+ message: `skills-hub ${latest} 已发布,当前版本为 ${version}`,
35
+ options: [{ value: true, label: '更新' }, { value: false, label: '跳过本次' }],
36
+ initialValue: false,
37
+ }))) {
38
+ try { return update(latest, { root: repositoryRoot, project, argv }); }
39
+ catch (error) { ui.note(error.message, '更新失败,可以继续使用当前版本'); }
40
+ }
41
+ }
26
42
  ui.note(project, '目标项目(技能写入 .agents/skills/)');
27
- const skills = createInstaller().catalog();
28
- ui.note('↑/↓ 页内移动,←/→ 整页翻页,Tab 勾选,Enter 确认。\n直接输入搜索;勾选分组包含其他页和隐藏子项,可再取消个别技能。\n■ 全选 · ◩ 部分选中 · □ 未选;Ctrl+U 清空搜索。', '树形搜索多选');
29
- const names = await ask(choose({ skills }));
43
+ const installer = createInstaller();
44
+ const skills = installer.catalog();
45
+ const initialNames = installer.installedNames(skills, project);
46
+ if (initialNames.length) ui.note(`已预选 ${initialNames.length} 个已安装技能。`, '当前项目');
47
+ const names = await ask(choose({ skills, initialNames }));
30
48
  const selected = select(skills, [], names);
31
49
  if (!selected.length) throw new Error('请至少勾选一个技能。');
32
50
  ui.note(formatSummary(selected.map(skill => skill.name)), `${selected.length} 个技能`);
33
51
  if (selected.some(skill => ['dev', 'system', 'ops'].includes(skill.domain))) {
34
52
  ui.note('将补齐所选领域的持久化目录和简短 AGENTS.md;固定模板自动更新,业务记录保留,预览不写入。', '领域初始化');
35
53
  }
36
- const dryRun = argv.includes('--dry-run');
37
- if (!await ask(ui.confirm({ message: dryRun ? '检查安装计划?(不写入文件)' : '安装以上技能?', initialValue: true }))) {
54
+ if (!await ask(ui.confirm({ message: dryRun ? '检查安装计划?(不写入文件)' : '安装或更新以上技能?(有差异的现有技能会先备份)', initialValue: true }))) {
38
55
  ui.cancel('已取消,未修改文件。'); return 0;
39
56
  }
40
57
  const command = ['install', '--skill', ...selected.map(skill => skill.name)];
package/install.mjs CHANGED
@@ -132,6 +132,16 @@ export function createInstaller({ repository = repositoryRoot, fsOps = fs } = {}
132
132
  }
133
133
  }
134
134
 
135
+ function installedNames(skills, project) {
136
+ const agents = path.join(project, '.agents');
137
+ const target = path.join(agents, 'skills');
138
+ if (!exists(agents)?.isDirectory() || !exists(target)?.isDirectory()) return [];
139
+ return skills.filter(({ name }) => {
140
+ const directory = path.join(target, name);
141
+ return exists(directory)?.isDirectory() && exists(path.join(directory, 'SKILL.md'))?.isFile();
142
+ }).map(({ name }) => name);
143
+ }
144
+
135
145
  function plan(skills, project, replace = true) {
136
146
  const actualProject = fsOps.realpathSync(project);
137
147
  for (const source of [skillRoot, upstreamRoot, licenseRoot]) {
@@ -236,7 +246,7 @@ export function createInstaller({ repository = repositoryRoot, fsOps = fs } = {}
236
246
  for (const lock of locks.reverse()) fsOps.rmdirSync(lock);
237
247
  }
238
248
  }
239
- return { catalog, plan, apply, persistencePlan };
249
+ return { catalog, installedNames, plan, apply, persistencePlan };
240
250
  }
241
251
 
242
252
  export function catalog(repository = repositoryRoot) { return createInstaller({ repository }).catalog(); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@namewta/skills-hub",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "独立中文 Agent Skills:按领域安装,覆盖开发交付、项目知识与系统维护。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,8 @@
10
10
  "install.mjs",
11
11
  "cli.mjs",
12
12
  "tree-select.mjs",
13
+ "scripts/npm-cli.mjs",
14
+ "scripts/update-cli.mjs",
13
15
  "scripts/init-persistence.mjs",
14
16
  "scripts/persistence/",
15
17
  "skills/",
@@ -0,0 +1,33 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { delimiter, dirname, join } from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+
5
+ export function findNpmCli(environment = process.env) {
6
+ const candidates = [
7
+ environment.npm_execpath,
8
+ join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
9
+ join(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js'),
10
+ ];
11
+ for (const directory of (environment.PATH ?? environment.Path ?? '').split(delimiter)) {
12
+ if (!directory) continue;
13
+ candidates.push(join(directory, 'npm'), join(directory, 'node_modules/npm/bin/npm-cli.js'));
14
+ }
15
+ for (const candidate of candidates.filter(Boolean)) {
16
+ if (!existsSync(candidate)) continue;
17
+ const resolved = realpathSync(candidate);
18
+ if (resolved.endsWith('npm-cli.js')) return resolved;
19
+ }
20
+ throw new Error('未找到随 Node.js 安装的 npm CLI;请使用完整的 Node.js 发行版。');
21
+ }
22
+
23
+ export function runNpm(arguments_, options = {}) {
24
+ const result = spawnSync(process.execPath, [findNpmCli(options.env), ...arguments_], {
25
+ windowsHide: true,
26
+ encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, ...options,
27
+ });
28
+ if (result.error) throw result.error;
29
+ if (result.status !== 0) {
30
+ throw new Error(`npm ${arguments_[0]} 失败(${result.status}):\n${result.stdout ?? ''}${result.stderr ?? ''}`);
31
+ }
32
+ return result;
33
+ }
@@ -0,0 +1,51 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
+ import { findNpmCli, runNpm } from './npm-cli.mjs';
5
+
6
+ const packageName = '@namewta/skills-hub';
7
+ const registry = 'https://registry.npmjs.org';
8
+ const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
9
+
10
+ export function isNpmInstallation(root) {
11
+ return basename(root) === 'skills-hub' && basename(dirname(root)) === '@namewta'
12
+ && basename(dirname(dirname(root))) === 'node_modules';
13
+ }
14
+
15
+ export async function latestUpdate(version, request = fetch) {
16
+ const current = stable.exec(version.split(/[+-]/, 1)[0]);
17
+ if (!current) return;
18
+ try {
19
+ const response = await request(`${registry}/@namewta%2Fskills-hub/latest`, {
20
+ signal: AbortSignal.timeout(1800),
21
+ });
22
+ if (!response.ok) return;
23
+ const metadata = await response.json();
24
+ const latest = typeof metadata?.version === 'string' && stable.exec(metadata.version);
25
+ if (!latest || metadata.name !== packageName) return;
26
+ const difference = latest.slice(1).map((part, i) => BigInt(part) - BigInt(current[i + 1])).find(part => part !== 0n);
27
+ if (difference > 0n || (difference === undefined && version.includes('-'))) return metadata.version;
28
+ } catch {
29
+ // 离线、超时或注册表响应不可用时继续安装技能。
30
+ }
31
+ }
32
+
33
+ export function installUpdate(version, { root, project, argv }) {
34
+ if (!stable.test(version)) throw new Error('无效的 npm 更新版本。');
35
+ const options = { cwd: project, timeout: 120_000 };
36
+ const globalRoot = runNpm(['root', '--global'], options).stdout.trim();
37
+ const globalPackage = join(globalRoot, packageName);
38
+ const global = existsSync(globalPackage) && realpathSync(globalPackage) === realpathSync(root);
39
+ const spec = `${packageName}@${version}`;
40
+ const flags = ['--ignore-scripts', `--registry=${registry}`];
41
+ let command;
42
+ if (global) {
43
+ runNpm(['install', '--global', ...flags, '--no-audit', '--no-fund', spec], options);
44
+ command = [resolve(globalPackage, 'install.mjs'), ...argv];
45
+ } else {
46
+ command = [findNpmCli(), 'exec', '--yes', ...flags, `--package=${spec}`, '--', 'skills-hub', ...argv];
47
+ }
48
+ const result = spawnSync(process.execPath, command, { cwd: project, windowsHide: true, stdio: 'inherit' });
49
+ if (result.error) throw result.error;
50
+ return result.status ?? 1;
51
+ }
package/tree-select.mjs CHANGED
@@ -18,8 +18,9 @@ export function matchesSkillSearch(search, option) {
18
18
  });
19
19
  }
20
20
 
21
- export function createSkillTree(skills) {
22
- const selected = new Set();
21
+ export function createSkillTree(skills, initialNames = []) {
22
+ const installed = new Set(initialNames);
23
+ const selected = new Set(skills.filter(skill => installed.has(skill.name)).map(skill => skill.name));
23
24
  const root = { value: '@all', label: '全部技能', depth: 0, names: skills.map(skill => skill.name) };
24
25
  const nodes = [root];
25
26
  for (const domain of [...new Set(skills.map(skill => skill.domain))]) {
@@ -55,63 +56,81 @@ export function createSkillTree(skills) {
55
56
  };
56
57
  }
57
58
 
58
- // 每页只属于一个分组;分组行始终置顶且可勾选,不与子项一起滚出屏幕。
59
- export function createTreePager(tree, pageSize = 8) {
60
- let query = '', size = Math.max(1, pageSize), page = 0, cursor = 0;
61
- function pages() {
62
- const result = [];
63
- for (const domain of tree.nodes.filter(node => node.depth === 1)) {
64
- const children = tree.nodes.filter(node => node.domain === domain.value && tree.matches(query, node));
65
- for (let start = 0; start < children.length; start += size) {
66
- result.push({ domain, children: children.slice(start, start + size),
67
- domainPage: Math.floor(start / size) + 1, domainPages: Math.ceil(children.length / size) });
68
- }
69
- }
70
- return result;
71
- }
59
+ const maxPageSize = 20;
60
+ const frameOverhead = 5;
61
+
62
+ export function createTreePager(tree, pageSize = maxPageSize) {
63
+ const [root] = tree.nodes;
64
+ const domains = tree.nodes.filter(node => node.depth === 1);
65
+ let query = '', size = Math.max(1, pageSize), page = 0, focus = root.value, expanded;
66
+ const matchingDomains = () => domains.filter(node => tree.matches(query, node));
67
+ const matchingChildren = () => expanded
68
+ ? tree.nodes.filter(node => node.domain === expanded && tree.matches(query, node)) : [];
72
69
  function view() {
73
- const all = pages();
74
- page = Math.max(0, Math.min(page, all.length - 1));
75
- const current = all[page];
76
- const rows = current ? [tree.nodes[0], current.domain, ...current.children] : [];
77
- cursor = Math.max(0, Math.min(cursor, rows.length - 1));
78
- return { ...current, rows, cursor, page, totalPages: all.length, query, pageSize: size };
70
+ const groups = matchingDomains();
71
+ const matching = matchingChildren();
72
+ const children = matching.slice(page * size, (page + 1) * size);
73
+ const rows = groups.length ? [root, ...groups.flatMap(domain =>
74
+ domain.value === expanded ? [domain, ...children] : [domain])] : [];
75
+ const cursor = rows.findIndex(node => node.value === focus);
76
+ return { rows, cursor, page, totalPages: Math.ceil(matching.length / size), query,
77
+ pageSize: size, expanded, groups, children };
78
+ }
79
+ function clearSearch() {
80
+ query = '';
81
+ page = 0;
82
+ focus = root.value;
83
+ expanded = undefined;
79
84
  }
80
85
  return {
81
86
  view,
87
+ clearSearch,
82
88
  search(value) {
83
89
  if (value === query) return;
84
- query = value; page = 0; cursor = 0;
85
- const current = view();
86
- if (query.trim() && current.rows.length) {
87
- cursor = matchesSkillSearch(query, tree.nodes[0]) ? 0
88
- : matchesSkillSearch(query, current.domain) ? 1 : 2;
90
+ if (!value.trim()) {
91
+ clearSearch();
92
+ return;
93
+ }
94
+ query = value;
95
+ page = 0;
96
+ focus = root.value;
97
+ const domain = matchingDomains()[0];
98
+ expanded = domain?.value;
99
+ if (domain && !matchesSkillSearch(query, root)) {
100
+ focus = matchesSkillSearch(query, domain) ? domain.value : matchingChildren()[0]?.value ?? domain.value;
89
101
  }
90
102
  },
91
103
  resize(value) {
92
- if (size === value) return;
93
- const before = view();
94
- const focused = before.rows[cursor]?.value;
95
- size = Math.max(1, value);
96
- const all = pages();
97
- const target = all.findIndex(item => item.children.some(node => node.value === focused)
98
- || ((focused === '@all' || focused === before.domain?.value) && item.domain.value === before.domain?.value));
99
- if (target !== -1) page = target;
100
- const current = view();
101
- const index = current.rows.findIndex(node => node.value === focused);
102
- if (index !== -1) cursor = index;
104
+ const nextSize = Math.max(1, value);
105
+ if (size === nextSize) return;
106
+ const index = matchingChildren().findIndex(node => node.value === focus);
107
+ page = Math.floor((index === -1 ? page * size : index) / nextSize);
108
+ size = nextSize;
103
109
  },
104
110
  move(direction) {
105
111
  const current = view();
106
- cursor = Math.max(0, Math.min(cursor + direction, current.rows.length - 1));
112
+ const index = Math.max(0, Math.min(current.cursor + direction, current.rows.length - 1));
113
+ focus = current.rows[index]?.value ?? focus;
107
114
  },
108
115
  turn(direction) {
116
+ const { totalPages } = view();
117
+ const next = Math.max(0, Math.min(page + direction, totalPages - 1));
118
+ if (next === page) return;
119
+ page = next;
120
+ focus = view().children[0].value;
121
+ },
122
+ toggleExpanded() {
109
123
  const current = view();
110
- const next = Math.max(0, Math.min(page + direction, current.totalPages - 1));
111
- if (next !== page) { page = next; cursor = 2; }
124
+ const node = current.rows[current.cursor];
125
+ const domain = node?.depth === 1 ? node.value : node?.domain;
126
+ if (!domain) return;
127
+ expanded = domain === expanded ? undefined : domain;
128
+ focus = domain;
129
+ page = 0;
112
130
  },
113
131
  toggle() {
114
- const focused = view().rows[cursor];
132
+ const current = view();
133
+ const focused = current.rows[current.cursor];
115
134
  if (focused) tree.toggle(focused.value);
116
135
  },
117
136
  };
@@ -130,67 +149,85 @@ export function fitTreeText(value, width) {
130
149
  return `${result}…`;
131
150
  }
132
151
 
133
- export function renderTreePage(tree, pager, { columns = 80, colors = pc, error = '' } = {}) {
134
- const c = colors, view = pager.view(), width = Math.max(12, columns - 1);
152
+ export function renderTreePage(tree, pager, { columns = 80, rows = Infinity, colors = pc, error = '', editing = false } = {}) {
153
+ const c = colors, view = pager.view(), width = Math.max(1, columns - 1);
135
154
  const line = (text, style = value => value) => style(fitTreeText(text, width));
136
- const lines = [line('◆ 搜索并选择分组 / 技能', c.green), line(`│ 搜索:${view.query || '输入名称 / 用途'} ▌`), '│'];
137
- for (const [index, node] of view.rows.entries()) {
155
+ const lines = [line('◆ 选择安装技能', c.green), line(editing
156
+ ? `│ 搜索:${view.query} ▌` : `│ / 搜索${view.query ? ` · ${view.query}` : ''}`)];
157
+ const available = Math.max(1, rows - frameOverhead);
158
+ const start = Math.max(0, Math.min(view.cursor - available + 1, view.rows.length - available));
159
+ const selected = new Set(tree.names());
160
+ for (const [offset, node] of view.rows.slice(start, start + available).entries()) {
161
+ const index = start + offset;
138
162
  const active = index === view.cursor;
139
163
  const state = tree.state(node.value);
140
164
  const marker = { none: '□', all: '■', partial: '◩' }[state];
141
- const branch = node.depth === 0 ? '◆ ' : node.depth === 1 ? '└─ ▸ '
142
- : index === view.rows.length - 1 ? ' └─ ' : ' ├─ ';
165
+ const branch = node.depth === 0 ? '◆ '
166
+ : node.depth === 1 ? `${node === view.groups.at(-1) ? '└─' : '├─'} ${node.value === view.expanded ? '▾' : '▸'} `
167
+ : node === view.children.at(-1) ? ' └─ ' : ' ├─ ';
143
168
  const prefix = `│ ${active ? '›' : ' '} ${branch}${marker} `;
144
- const suffix = node.depth < 2 ? ` ${node.names.filter(name => tree.names().includes(name)).length}/${node.names.length}` : '';
169
+ const suffix = node.depth < 2 ? ` ${node.names.filter(name => selected.has(name)).length}/${node.names.length}` : '';
145
170
  const name = node.depth < 2 ? `${node.label}${node.depth === 1 ? ` ${node.groupType}` : ''}` : node.label;
171
+ if (stringWidth(prefix) >= width) {
172
+ lines.push(line(`${prefix}${name}`, active ? c.green : c.dim));
173
+ continue;
174
+ }
146
175
  const label = fitTreeText(`${prefix}${name}${suffix}`, width).slice(prefix.length);
147
176
  // 行首保留非空树枝,避免折行工具裁掉缩进;目录与技能有不同图标和颜色。
148
177
  lines.push(c.gray(prefix.slice(0, -2)) + (state === 'none' ? c.dim(`${marker} `) : c.green(`${marker} `))
149
178
  + (node.depth < 2 ? c.bold(active ? c.green(label) : c.cyan(label)) : active ? c.green(label) : label));
150
179
  }
151
- if (!view.rows.length) lines.push(line('│ 无匹配;退格修改或 Ctrl+U 清空搜索。', c.yellow));
152
180
  const focused = view.rows[view.cursor];
153
- const detail = focused?.depth === 2 ? focused.hint
154
- : focused ? '勾选将操作全部子技能,包括其他页和搜索隐藏项。' : '输入其他关键词以继续选择。';
155
- lines.push('│', line(`│ ${focused?.label ?? '搜索提示'} · ${view.domain?.label ?? '—'}`, c.dim),
156
- line(`│ ${detail}`, c.dim),
157
- line(`│ 第 ${view.totalPages ? view.page + 1 : 0}/${view.totalPages} 页 · ${view.domain?.label ?? '—'} ${view.domainPage ?? 0}/${view.domainPages ?? 0} · 已选 ${tree.names().length} 个`, c.green),
158
- line(error ? `│ ${error}` : '│ ←/→ 整页翻页 · ↑/↓ 页内移动', error ? c.red : c.dim),
159
- line('└ Tab 勾选 · Enter 确认 · Ctrl+C 取消', c.dim));
181
+ const detail = focused?.depth === 2 ? focused.hint : '空格勾选整组,包括其他页和筛选隐藏项。';
182
+ const page = view.totalPages ? ` · 第 ${view.page + 1}/${view.totalPages} 页` : '';
183
+ lines.push(line(error ? `│ ${error}` : focused ? `│ ${detail}` : '│ 无匹配,按 / 修改或 Ctrl+U 清空。', error ? c.red : focused ? c.dim : c.yellow),
184
+ line(`│ 已选 ${selected.size} 个${page}${editing ? ' · 输入关键词,空格分隔' : ' · ↑/↓ 移动 · ←/→ 翻页'}`, c.green),
185
+ line(editing ? '└ Enter 返回树 · Ctrl+U 清空 · Ctrl+C 取消'
186
+ : '└ Tab 展开/收拢 · 空格勾选 · Enter 确认 · Ctrl+U 清空 · Ctrl+C 取消', c.dim));
160
187
  return lines.join('\n');
161
188
  }
162
189
 
163
- export function treeSelect({ skills, input = process.stdin, output = process.stdout }) {
164
- const tree = createSkillTree(skills);
165
- const pageSize = () => Math.max(1, Math.min(8, (output.rows || 24) - 13));
166
- const pager = createTreePager(tree, pageSize());
190
+ export function treeSelect({ skills, initialNames = [], input = process.stdin, output = process.stdout }) {
191
+ const tree = createSkillTree(skills, initialNames);
192
+ const pager = createTreePager(tree);
167
193
  class TreePrompt extends Prompt {
168
194
  constructor() {
169
195
  super({ input, output,
170
196
  render() {
171
197
  if (this.state === 'submit') return pc.green(`◇ 已选择 ${tree.names().length} 个技能`);
172
198
  if (this.state === 'cancel') return pc.yellow('◇ 已取消树形选择');
173
- pager.resize(pageSize());
174
- return renderTreePage(tree, pager, { columns: output.columns || 80, error: this.state === 'error' ? this.error : '' });
199
+ const rows = output.rows || 24;
200
+ pager.resize(Math.min(maxPageSize, rows - frameOverhead - 1 - pager.view().groups.length));
201
+ return renderTreePage(tree, pager, { rows, columns: output.columns || 80,
202
+ error: this.state === 'error' ? this.error : '', editing: this.editing });
175
203
  },
176
204
  });
177
- this.value = [];
178
- this.on('userInput', value => pager.search(value));
205
+ this.editing = false;
206
+ this.value = tree.names();
207
+ this.on('userInput', value => {
208
+ if (this.editing) pager.search(value);
209
+ });
179
210
  this.on('key', (character, key) => {
180
- if (key.name === 'up' || key.name === 'down') pager.move(key.name === 'up' ? -1 : 1);
181
- if (key.name === 'left' || key.name === 'right') {
182
- pager.turn(key.name === 'left' ? -1 : 1);
183
- // 左右键被分页占用,不让 readline 光标移动后将搜索文字插到中间。
184
- if (this.rl) this.rl.cursor = this.rl.line.length;
211
+ if (key.ctrl && key.name === 'u') pager.clearSearch();
212
+ if (this.editing) return;
213
+ if (character === '/') {
214
+ const { query } = pager.view();
215
+ this._clearUserInput();
216
+ this.editing = true;
217
+ this._setUserInput(query, true);
185
218
  }
186
- if (key.name === 'tab' || (key.name === 'space' && !pager.view().query.trim())) pager.toggle();
219
+ if (key.name === 'up' || key.name === 'down') pager.move(key.name === 'up' ? -1 : 1);
220
+ if (key.name === 'left' || key.name === 'right') pager.turn(key.name === 'left' ? -1 : 1);
221
+ if (key.name === 'tab') pager.toggleExpanded();
222
+ if (key.name === 'space') pager.toggle();
187
223
  this.value = tree.names();
188
224
  });
189
225
  }
190
- _isActionKey(character, key) {
191
- return key.name === 'tab' || (key.name === 'space' && !pager.view().query.trim());
192
- }
193
226
  _shouldSubmit() {
227
+ if (this.editing) {
228
+ this.editing = false;
229
+ return false;
230
+ }
194
231
  if (this.value.length) return true;
195
232
  this.error = '请至少勾选一个技能。';
196
233
  this.state = 'error';