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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262import { type ITerminalAddon, Terminal } from '@xterm/xterm'
export class LocalCliAddon implements ITerminalAddon {
private term!: Terminal
private currentLine: string = ''
private cursorPos: number = 0
private startOfLine: string = '> '
private commandHandlers: Record<string, (args: string[]) => void> = {}
private commandHistory: string[] = []
private historyCursor: number = 0
private historySize: number;
constructor(
{
historySize = 100,
startOfLine = undefined
}: {
historySize?: number,
startOfLine?: string
} = {}) {
this.historySize = historySize
this.startOfLine = startOfLine || '> '
}
activate(terminal: Terminal): void {
this.term = terminal
}
dispose(): void {
this.commandHandlers = {}
}
get currentInput(): string {
return this.currentLine
}
_writeLineStart = () => {
this.term.write(this.startOfLine)
}
defaultCommandHandler = (_cmd: string, _args: string[]) => {
// this.term.writeln(`Command not found: ${cmd}`)
this._writeLineStart()
}
registerCommandHandler(command: string[], handler: (args: string[]) => void) {
for (const cmd of command) {
if (this.commandHandlers[cmd]) {
console.warn(`Command '${cmd}' is already registered. Overwriting.`)
}
this.commandHandlers[cmd] = handler
}
}
processCommand = (line: string, useDefault: boolean = true) => {
const [command, ...args] = line.trim().split(' ')
const handler = this.commandHandlers[command]
if (handler) {
handler(args)
return
}
if (useDefault) {
this.defaultCommandHandler(command, args)
}
}
private _clearLine() {
this.term.write('\r' + this.startOfLine + ' '.repeat(this.currentLine.length))
this.term.write('\r' + this.startOfLine)
}
private _showHistory() {
this._clearLine()
this.currentLine = this.commandHistory[this.historyCursor] || ''
this.term.write(this.currentLine)
this.cursorPos = this.currentLine.length
}
handleOtherInput = (data: string) => {
// Handle ANSI escape sequences
// data len > 1
if (!data || data[0] != '\u001b') {
// unknown input, ignore
console.log(`Unknown input: ${JSON.stringify(data)}`)
return
}
switch (data.substring(1)) {
case "[A": // Up arrow
if (this.historyCursor > 0) {
this.historyCursor--
this._showHistory()
}
break;
case "[B": // Down arrow
if (this.historyCursor < this.commandHistory.length) {
this.historyCursor++
this._showHistory()
}
break;
case "[D": // Left Arrow
if (this.cursorPos > 0) {
this.term.write(data)
this.cursorPos--
}
break;
case "[C": // Right Arrow
if (this.cursorPos < this.currentLine.length) {
this.term.write(data)
this.cursorPos++
}
break;
case "[3~": // Delete
if (this.cursorPos < this.currentLine.length) {
const right = this.currentLine.slice(this.cursorPos + 1)
this.term.write(right + ' ' + '\b'.repeat(right.length + 1))
this.currentLine = this.currentLine.slice(0, this.cursorPos) + right
}
break;
case "[F": // End
if (this.cursorPos < this.currentLine.length) {
const move = this.currentLine.length - this.cursorPos
this.term.write(`\u001b[${move}C`)
this.cursorPos = this.currentLine.length
}
break;
case "[H": // Home
if (this.cursorPos > 0) {
this.term.write(`\u001b[${this.cursorPos}D`)
this.cursorPos = 0
}
break;
default:
console.log(`Unhandled ANSI sequence: ${JSON.stringify(data)}`);
}
}
handleCtrlInput = (char: string) => {
switch (char) {
case '\u0001': // Ctrl+A
if (this.cursorPos > 0) {
this.term.write(`\u001b[${this.cursorPos}D`)
this.cursorPos = 0
}
break
case '\u0005': // Ctrl+E
if (this.cursorPos < this.currentLine.length) {
const move = this.currentLine.length - this.cursorPos
this.term.write(`\u001b[${move}C`)
this.cursorPos = this.currentLine.length
}
break
case '\u0015': // Ctrl+U
if (this.cursorPos > 0) {
const right = this.currentLine.slice(this.cursorPos)
this.term.write('\b'.repeat(this.cursorPos) + right)
this.term.write(' '.repeat(this.cursorPos))
this.term.write('\b'.repeat(this.currentLine.length))
this.currentLine = right
this.cursorPos = 0
}
break
case '\u000b': // Ctrl+K
if (this.cursorPos < this.currentLine.length) {
const right = this.currentLine.slice(this.cursorPos)
this.term.write(' '.repeat(right.length))
this.term.write('\b'.repeat(right.length))
this.currentLine = this.currentLine.slice(0, this.cursorPos)
}
break
default:
break
}
}
handleSingleCharInput = (char: string) => {
const charCode = char.charCodeAt(0)
if (char === '\r') { // Enter
this.term.writeln('')
if (this.currentLine.trim()) {
if (this.commandHistory.at(-1) !== this.currentLine) {
this.commandHistory.push(this.currentLine)
if (this.commandHistory.length > this.historySize) {
this.commandHistory.shift()
}
}
this.processCommand(this.currentLine)
} else {
this._writeLineStart()
}
this.currentLine = ''
this.cursorPos = 0
this.historyCursor = this.commandHistory.length
} else if (char === '\u007f') { // Backspace
if (this.cursorPos > 0) {
const left = this.currentLine.slice(0, this.cursorPos - 1)
const right = this.currentLine.slice(this.cursorPos)
this.term.write('\b' + right + ' ' + '\b'.repeat(right.length + 1))
this.currentLine = left + right
this.cursorPos--
}
} else if (char === '\u0003') { // Ctrl+C
this.term.write('^C\n')
this._writeLineStart()
this.currentLine = ''
this.cursorPos = 0
} else if (charCode >= '\u0000'.charCodeAt(0) && charCode <= '\u001f'.charCodeAt(0)) {
this.handleCtrlInput(char)
} else {
const left = this.currentLine.slice(0, this.cursorPos)
const right = this.currentLine.slice(this.cursorPos)
this.term.write(char + right + '\b'.repeat(right.length))
this.currentLine = left + char + right
this.cursorPos++
this.historyCursor = this.commandHistory.length
}
}
handleTermInput = (data: string) => {
if (data.length === 1) {
this.handleSingleCharInput(data)
return
}
// paste?
if (data.length > 3 && data[0] !== '\u001b') {
const normData = data.replace(/[\r\n]+/g, "\r")
Array.from(normData).forEach(c => this.handleSingleCharInput(c));
} else {
this.handleOtherInput(data)
}
}
private connectedLineBuffer: string = ''
// When connected, only handle local commands starting with '#'
handleConnectedInput = (data: string) => {
if (data.length > 1) return
if (data === '\r') { // Enter
if (this.connectedLineBuffer.trim()) {
this.processCommand(this.connectedLineBuffer.substring(1), false) // skip '#'
}
this.connectedLineBuffer = ''
} else if (data === '\u007f') { // Backspace
if (this.connectedLineBuffer.length > 0) {
this.connectedLineBuffer = this.connectedLineBuffer.slice(0, -1)
return
}
} else if (data === '\u0003') { // Ctrl+C
this.connectedLineBuffer = ''
}
if (this.connectedLineBuffer.length > 0) {
this.connectedLineBuffer += data
return
}
if (data === '#') {
this.connectedLineBuffer = data
}
}
}