-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
229 lines (198 loc) · 6.76 KB
/
Copy pathtest.js
File metadata and controls
229 lines (198 loc) · 6.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import readline from 'readline';
import { spawn } from 'child_process';
import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
// --- 状态管理 ---
const COMMANDS = ['git', 'npm', 'node', 'cd', 'ls', 'cat', 'mkdir', 'rm', 'yarn', 'docker', 'code'];
const GIT_SUBS = ['status', 'checkout', 'commit', 'push', 'pull', 'add', 'log', 'branch'];
let history = ['git status', 'npm install', 'node test.js'];
let historyIdx = -1;
let input = '';
let suggestions = [];
const PROMPT_SYMBOL = chalk.green('➜ ');
const visibleLen = (str) => str.replace(/\u001b\[.*?m/g, '').length;
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY) process.stdin.setRawMode(true);
/**
* 语法高亮
*/
function getHighlightedInput(text) {
if (!text) return '';
const words = text.split(/(\s+)/);
return words.map((word, i) => {
if (/^\s+$/.test(word)) return word;
if (i === 0 && COMMANDS.includes(word)) return chalk.bold.yellow(word);
if (word.startsWith('-')) return chalk.magenta(word);
if (fs.existsSync(word)) return chalk.blue.underline(word);
return chalk.white(word);
}).join('');
}
/**
* 核心渲染:修复光标与 UI 残留
*/
function render() {
process.stdout.write('\u001b[0J'); // 清除光标以下
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
const cwd = chalk.cyan(path.basename(process.cwd()) || path.sep);
const prefix = `${PROMPT_SYMBOL}${cwd} `;
// 1. 打印高亮输入
process.stdout.write(prefix + getHighlightedInput(input));
// 2. 渲染 Ghost Text (历史建议)
const ghost = history.find(h => h.startsWith(input) && input.length > 0);
if (ghost && input.length > 0) {
process.stdout.write(chalk.gray(ghost.slice(input.length)));
}
// 3. 渲染 Linux 风格的建议预览窗 (仅展示,不选中)
if (suggestions.length > 0) {
process.stdout.write('\n');
suggestions.forEach((item) => {
const icon = COMMANDS.includes(item) ? chalk.blue(' ') : chalk.gray(' ');
process.stdout.write(` ${icon}${chalk.gray(item.padEnd(20))}\n`);
});
process.stdout.moveCursor(0, -(suggestions.length + 1));
}
process.stdout.cursorTo(visibleLen(prefix) + input.length);
}
/**
* 补全逻辑:Linux 风格 (Tab 采纳)
*/
function handleTab() {
if (suggestions.length === 0) return;
if (suggestions.length === 1) {
// 只有一个建议,直接补全
applyCompletion(suggestions[0]);
} else {
// 多个建议时,寻找共同前缀 (类似 Linux)
const common = getCommonPrefix(suggestions);
const words = input.split(/\s+/);
const lastWord = words[words.length - 1];
if (common && common.length > lastWord.length) {
applyCompletion(common);
}
}
}
function getCommonPrefix(strs) {
if (!strs.length) return '';
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
if (!prefix) return '';
}
}
return prefix;
}
function applyCompletion(item) {
const words = input.split(/\s+/);
words[words.length - 1] = item;
input = words.join(' ');
updateSuggestions();
}
/**
* 执行命令并清理
*/
function handleCommand(rawLine) {
const line = rawLine.trim();
input = '';
suggestions = [];
historyIdx = -1;
if (!line) return render();
const [cmd, ...args] = line.split(/\s+/);
if (cmd === 'cd') {
const target = args[0] || process.env.USERPROFILE || process.env.HOME;
try { process.chdir(path.resolve(target)); }
catch (e) { process.stdout.write(chalk.red(`\ncd: 目录不存在\n`)); }
return render();
}
if (cmd === 'ls') {
doLs(args);
if (!history.includes(line)) history.unshift(line);
return render();
}
const mapping = { 'cat': 'type', 'rm': 'del', 'clear': 'cls' };
const finalCmd = mapping[cmd] || cmd;
process.stdout.write('\n');
const child = spawn(finalCmd, args, { shell: true, stdio: 'inherit' });
child.on('close', (code) => {
if (code === 0 && !history.includes(line)) history.unshift(line);
render();
});
}
function doLs(args) {
try {
const files = fs.readdirSync('.').filter(f => args.includes('-a') ? true : !f.startsWith('.'));
const termWidth = process.stdout.columns || 80;
const maxLen = Math.max(...files.map(f => f.length), 10) + 4;
const cols = Math.floor(termWidth / maxLen);
let output = '\n';
files.sort().forEach((f, i) => {
const stats = fs.statSync(f);
const style = stats.isDirectory() ? chalk.blue.bold : chalk.white;
output += style(f).padEnd(maxLen + (style(f).length - f.length));
if ((i + 1) % cols === 0) output += '\n';
});
process.stdout.write(output + '\n');
} catch (e) {}
}
function updateSuggestions() {
if (!input.trim()) { suggestions = []; return; }
const words = input.split(/\s+/);
const last = words[words.length - 1];
let list = [];
if (words.length === 1) list = COMMANDS.filter(c => c.startsWith(last));
else if (words[0] === 'git') list = GIT_SUBS.filter(s => s.startsWith(last));
try {
const files = fs.readdirSync('.').filter(f => f.startsWith(last));
list = [...new Set([...list, ...files])];
} catch (e) {}
suggestions = list.slice(0, 8);
}
// --- 键盘监听 ---
process.stdin.on('keypress', (str, key) => {
if (key.ctrl && key.name === 'c') process.exit();
if (key.name === 'tab') {
handleTab();
render();
return;
}
if (key.name === 'return') {
process.stdout.write('\n');
handleCommand(input);
return;
}
// 上下键回归:滚动历史记录
if (key.name === 'up') {
if (history.length > 0) {
historyIdx = Math.min(historyIdx + 1, history.length - 1);
input = history[historyIdx];
updateSuggestions();
}
render();
return;
}
if (key.name === 'down') {
if (historyIdx > 0) {
historyIdx--;
input = history[historyIdx];
} else {
historyIdx = -1;
input = '';
}
updateSuggestions();
render();
return;
}
if (key.name === 'backspace') input = input.slice(0, -1);
else if (key.name === 'right') {
const ghost = history.find(h => h.startsWith(input));
if (ghost && input.length > 0) input = ghost;
}
else if (!key.ctrl && str) input += str;
historyIdx = -1;
updateSuggestions();
render();
});
console.clear();
render();