brsh 2.8.1 → 3.0.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.
package/lib/Terminal.js CHANGED
@@ -1,16 +1,94 @@
1
1
  'use strict';
2
2
 
3
3
  import _Shell from 'brsh';
4
- import _AnsiUp from 'ansi_up';
5
4
  import '../styles/terminal.css';
5
+ import { ScreenBuffer } from './terminal/ScreenBuffer.js';
6
+ import { VtParser, DEFAULT_URL_WHITELIST } from './terminal/VtParser.js';
7
+ import { DomRenderer } from './terminal/DomRenderer.js';
8
+ import { spawnPty } from './terminal/PtyBridge.js';
6
9
 
7
10
  const ImportedShell = _Shell?.default ?? _Shell;
8
- const AnsiUp = _AnsiUp?.default ?? _AnsiUp;
9
11
 
10
- const HISTORY_FILE = '/.brsh_history';
12
+ class MiniEventStream {
13
+ constructor() {
14
+ this._listeners = new Map();
15
+ this.readable = true;
16
+ this.writable = true;
17
+ this.isTTY = true;
18
+ }
19
+
20
+ on(event, fn) {
21
+ if (!this._listeners.has(event)) this._listeners.set(event, []);
22
+ this._listeners.get(event).push(fn);
23
+ return this;
24
+ }
25
+
26
+ addListener(event, fn) {
27
+ return this.on(event, fn);
28
+ }
29
+
30
+ once(event, fn) {
31
+ const wrapper = (...args) => {
32
+ this.removeListener(event, wrapper);
33
+ fn(...args);
34
+ };
35
+ return this.on(event, wrapper);
36
+ }
37
+
38
+ removeListener(event, fn) {
39
+ const list = this._listeners.get(event);
40
+ if (!list) return this;
41
+ const idx = list.indexOf(fn);
42
+ if (idx !== -1) list.splice(idx, 1);
43
+ return this;
44
+ }
45
+
46
+ off(event, fn) {
47
+ return this.removeListener(event, fn);
48
+ }
49
+
50
+ removeAllListeners(event) {
51
+ if (event) this._listeners.delete(event);
52
+ else this._listeners.clear();
53
+ return this;
54
+ }
55
+
56
+ listeners(event) {
57
+ return [...(this._listeners.get(event) || [])];
58
+ }
59
+
60
+ emit(event, ...args) {
61
+ const list = this._listeners.get(event);
62
+ if (!list || list.length === 0) return false;
63
+ for (const fn of [...list]) {
64
+ fn(...args);
65
+ }
66
+ return true;
67
+ }
68
+
69
+ setRawMode(flag) {
70
+ this.isRaw = Boolean(flag);
71
+ return this;
72
+ }
73
+
74
+ resume() { return this; }
75
+ pause() { return this; }
76
+ setEncoding(enc) {
77
+ this._encoding = enc;
78
+ return this;
79
+ }
80
+ pipe(dest) {
81
+ this.on('data', chunk => dest.write(chunk));
82
+ return dest;
83
+ }
84
+ unpipe() { return this; }
85
+ destroy() {
86
+ this.removeAllListeners();
87
+ }
88
+ }
11
89
 
12
90
  class Terminal {
13
- constructor(options) {
91
+ constructor(options = {}) {
14
92
  const {
15
93
  el,
16
94
  font = 'Roboto Mono',
@@ -20,22 +98,26 @@ class Terminal {
20
98
  onExit = null,
21
99
  mobileInput = 'click',
22
100
  lineWrap = false,
23
- command = null
101
+ command = null,
102
+ cols = 80,
103
+ rows = 24,
104
+ maxScrollback = 1000,
105
+ stream = null
24
106
  } = options;
25
107
 
26
- if(!el) {
108
+ if (!el) {
27
109
  throw new Error('you must set `el` option');
28
110
  }
29
111
 
30
- if(!['none', 'block', 'blink'].includes(cursor)) {
112
+ if (!['none', 'block', 'blink'].includes(cursor)) {
31
113
  throw new Error('cursor value must be one of: \'none\', \'block\', \'blink\'');
32
114
  }
33
115
 
34
- if(!['none', 'type'].includes(outputAnimation)) {
116
+ if (!['none', 'type'].includes(outputAnimation)) {
35
117
  throw new Error('outputAnimation value must be one of: \'none\', \'type\'');
36
118
  }
37
119
 
38
- if(!Number.isInteger(animateSpeed) || animateSpeed < 1 || animateSpeed > 20) {
120
+ if (!Number.isInteger(animateSpeed) || animateSpeed < 1 || animateSpeed > 20) {
39
121
  throw new Error('animateSpeed value must be between 1 and 20');
40
122
  }
41
123
 
@@ -44,642 +126,819 @@ class Terminal {
44
126
  this._outputAnimation = outputAnimation;
45
127
  this._animateSpeed = animateSpeed;
46
128
  this._lineWrap = lineWrap;
47
- this._working = true;
48
- this._pendingCommands = [];
129
+ this._el = el;
130
+
131
+ this._dataListeners = [];
132
+ this._resizeListeners = [];
133
+ this._titleListeners = [];
134
+ this._mouseButtonDown = null;
135
+
136
+ this._typeQueue = '';
137
+ this._typeTimer = null;
138
+ this._isHandlingInput = false;
139
+ this._suppressAnimationUntil = 0;
140
+
141
+ this.screen = new ScreenBuffer(cols, rows, { maxScrollback });
142
+ this.parser = new VtParser(this.screen, {
143
+ urlWhitelist: DEFAULT_URL_WHITELIST,
144
+ onResponse: (resp) => this._emitInput(resp),
145
+ onTitle: (title) => {
146
+ this.title = title;
147
+ for (const fn of this._titleListeners) fn(title);
148
+ }
149
+ });
150
+
151
+ // Resolve optional brsh Shell instance unless stream-only or Shell: false
152
+ this.cli = options.cli || options.shell || null;
153
+ if (!this.cli && !stream && options.Shell !== false) {
154
+ const ShellClass = options.Shell === null
155
+ ? null
156
+ : (options.Shell
157
+ || (typeof globalThis !== 'undefined' && (globalThis.Shell || globalThis.shell))
158
+ || (typeof ImportedShell === 'function' ? ImportedShell : null));
49
159
 
50
- let ShellClass = null;
51
- if (options.Shell !== false && options.Shell !== null) {
52
- ShellClass = options.Shell || (typeof globalThis !== 'undefined' && (globalThis.Shell || globalThis.shell)) || (typeof ImportedShell === 'function' ? ImportedShell : null);
53
- }
54
- this.cli = options.cli || options.shell;
55
- if (!this.cli) {
56
160
  if (!ShellClass) {
57
161
  throw new Error('Shell is required by Terminal. Please import Shell from "brsh" or include shell.min.js before terminal.min.js.');
58
162
  }
59
163
  this.cli = new ShellClass(Object.assign({}, options, { command: undefined }));
60
164
  }
61
165
 
62
- this._buffer = [];
63
- this._cursorPos = 0;
64
- this._history = [];
65
- this._historyPos = null;
66
- this._savedInput = null;
67
- this._historyLoaded = false;
68
- this._el = el;
69
- this._ansi = new AnsiUp();
70
-
71
- this._ansi.use_classes = true;
72
- this._ansi.url_whitelist = {
73
- http: true,
74
- https: true,
75
- tel: true,
76
- mailto: true
77
- }
78
-
79
166
  this._setupDom(this._el, font);
80
- this._attachShellListeners();
167
+ this.renderer = new DomRenderer(this._cmdList, this.screen, {
168
+ cursor: this._cursor,
169
+ urlWhitelist: DEFAULT_URL_WHITELIST
170
+ });
81
171
 
82
- if (command) {
83
- this.onCommand(command);
84
- }
172
+ this._listenForEvents();
85
173
 
86
- if(mobileInput === 'click') {
87
- this._mobileInput();
174
+ if (this.cli) {
175
+ this.attach(this.cli);
176
+ if (typeof this.cli.on === 'function') {
177
+ this.cli.on('exit', (code) => {
178
+ delete this.cli;
179
+ if (typeof this._exitFn === 'function') {
180
+ this._exitFn(code);
181
+ }
182
+ });
183
+ }
184
+ if (command) {
185
+ this.onCommand(command);
186
+ }
88
187
  }
89
- }
90
188
 
91
- sendKey(key, modifiers = {}) {
92
- const { alt = false, ctrl = false } = modifiers;
93
- const onUpdate = this._setCurrentLine.bind(this);
94
-
95
- const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'Delete'];
96
- if (navKeys.includes(key) || (ctrl && ['a', 'e', 'u', 'k'].includes(key.toLowerCase()))) {
97
- this._navKeyEvent(onUpdate, { key, altKey: alt, ctrlKey: ctrl });
98
- } else {
99
- this._keyEvent(onUpdate, key);
189
+ if (stream) {
190
+ this.attach(stream);
191
+ if (command) {
192
+ this.onCommand(command);
193
+ }
100
194
  }
101
- }
102
195
 
103
- onCommand(command) {
104
- if(!this._currentLine) {
105
- if (this.cli) {
106
- this.cli.suppressMotd();
107
- }
108
- this._pendingCommands.push(command);
109
- return;
196
+ if (mobileInput === 'click') {
197
+ this._mobileInput();
110
198
  }
111
199
 
112
- const onUpdate = this._setCurrentLine.bind(this);
113
- this._cursorPos = command.length;
114
- onUpdate(Array.from(command));
115
- this.cli.onCommand(command);
200
+ this.renderer.flushRender();
116
201
  }
117
202
 
118
- _mobileInput() {
119
- const input = document.createElement('input');
120
- input.type = 'text';
121
- input.style.position = 'absolute';
122
- input.style.left = '-9999999px';
123
- this._el.appendChild(input);
124
- this._mobileInputBuffer = '';
203
+ get cols() {
204
+ return this.screen.cols;
205
+ }
125
206
 
126
- this._el.addEventListener('click', () => {
127
- input.focus();
128
- });
207
+ get rows() {
208
+ return this.screen.rows;
209
+ }
129
210
 
130
- input.addEventListener('keypress', e => {
131
- if(e.key === 'Enter') {
132
- input.value = '';
133
- this._mobileInputBuffer = input.value
211
+ /**
212
+ * Feed raw terminal output (including ANSI/VT100 escape sequences) into the terminal.
213
+ */
214
+ write(data) {
215
+ if (data == null || data === '') return;
216
+ const str = typeof data === 'string'
217
+ ? data
218
+ : (data instanceof Uint8Array || (typeof Buffer !== 'undefined' && Buffer.isBuffer(data)))
219
+ ? new TextDecoder().decode(data)
220
+ : String(data);
221
+
222
+ if (this._outputAnimation === 'type') {
223
+ if (this._isUserInputActive() || this._isFullScreenWrite(str)) {
224
+ this._flushTypeQueue();
225
+ this.parser.write(str);
226
+ this.renderer.flushRender();
227
+ this._autoScroll();
228
+ return;
134
229
  }
135
- });
136
-
137
- const onUpdate = this._setCurrentLine.bind(this);
138
230
 
139
- input.addEventListener('keyup', (e) => {
140
- if(e.key === 'Unidentified') {
141
- if (input.value.length < this._mobileInputBuffer.length) {
142
- //backspace
143
- this._keyEvent(onUpdate, 'Backspace');
144
- } else if (input.value.length > this._mobileInputBuffer.length) {
145
- //a new character
146
- const char = input.value[input.value.length - 1];
147
- this._keyEvent(onUpdate, char.toLowerCase());
231
+ if (this._isLineRewrite(str) || !/[^\r\n]/.test(str)) {
232
+ if (!this._typeQueue || !this._typeQueue.includes('\n')) {
233
+ this._flushTypeQueue();
234
+ this.parser.write(str);
235
+ this.renderer.flushRender();
236
+ this._autoScroll();
237
+ return;
148
238
  }
149
-
150
- this._mobileInputBuffer = input.value;
151
239
  }
152
- });
153
- }
154
-
155
- _setupDom(parent, font = 'Roboto Mono') {
156
- const style = document.createElement('link');
157
- style.href = `https://fonts.googleapis.com/css?family=${encodeURIComponent(font)}:ital,wght@0,400;0,700;1,400;1,700&display=swap`;
158
- style.rel = 'stylesheet';
159
- document.head.appendChild(style);
160
240
 
161
- this._cmdList = document.createElement('ul');
162
- this._cmdList.style.fontFamily = `'${font}', monospace`;
163
- this._cmdList.style.listStyle = 'none';
164
- this._cmdList.style.padding = '0';
165
- if (this._lineWrap) {
166
- this._cmdList.classList.add('terminal--wrap');
241
+ this._enqueueTypeAnimation(str);
242
+ return;
167
243
  }
168
- parent.appendChild(this._cmdList);
169
244
 
170
- // Full-screen surface for interactive commands (pico, etc.)
171
- this._screen = document.createElement('pre');
172
- this._screen.className = 'terminal__screen';
173
- this._screen.style.fontFamily = `'${font}', monospace`;
174
- parent.appendChild(this._screen);
175
-
176
- // Hidden single-character span for measuring character cell dimensions.
177
- // fontFamily must be set explicitly to match _cmdList — without it the span
178
- // inherits from the page font, giving a wrong character width.
179
- this._charMeasure = document.createElement('span');
180
- this._charMeasure.className = 'terminal__char-measure';
181
- this._charMeasure.style.fontFamily = `'${font}', monospace`;
182
- this._charMeasure.textContent = 'X';
183
- this._charMeasure.setAttribute('aria-hidden', 'true');
184
- parent.appendChild(this._charMeasure);
245
+ this.parser.write(str);
246
+ this.renderer.flushRender();
247
+ this._autoScroll();
248
+ }
185
249
 
186
- // Measure on first paint, then re-measure once the webfont is ready
187
- // (the setTimeout fires before the Google Font downloads, so the initial
188
- // measurement uses the fallback font; document.fonts.ready corrects it).
189
- setTimeout(() => this._measureAndSetSize(), 0);
190
- if (document.fonts) {
191
- document.fonts.ready.then(() => this._measureAndSetSize());
192
- }
193
- if (typeof ResizeObserver !== 'undefined') {
194
- new ResizeObserver(() => this._measureAndSetSize()).observe(parent);
195
- }
250
+ writeln(data = '') {
251
+ this.write(String(data) + '\r\n');
196
252
  }
197
253
 
198
- _newPrompt(callback) {
199
- if (typeof document === 'undefined' || !this._cmdList) return;
200
- this._progressLine = null;
201
- this._clearCursor();
202
- this._currentLine = document.createElement('li');
203
- this._cmdList.appendChild(this._currentLine);
204
- if(callback) {
205
- callback();
206
- }
207
- this._autoScroll();
254
+ clear() {
255
+ this.write('\x1b[2J\x1b[3J\x1b[H');
208
256
  }
209
257
 
210
- _print(data, type = 'out') {
211
- if (typeof data === 'string' && data.startsWith('\r')) {
212
- const clean = data.slice(1);
213
- if (this._progressLine && this._progressLine.parentNode === this._cmdList) {
214
- this._progressLine.innerHTML = this._ansi.ansi_to_html(clean);
215
- this._autoScroll();
216
- return;
217
- }
218
- const line = document.createElement('li');
219
- line.classList.add('terminal__line');
220
- line.classList.add(type);
221
- line.innerHTML = this._ansi.ansi_to_html(clean);
222
- this._cmdList.appendChild(line);
223
- this._progressLine = line;
224
- this._autoScroll();
225
- return;
226
- }
258
+ reset() {
259
+ this._flushTypeQueue();
260
+ this.parser.reset();
261
+ this.renderer.flushRender();
262
+ }
227
263
 
228
- this._progressLine = null;
229
- if(this._outputAnimation === 'none') {
230
- const line = document.createElement('li');
231
- line.classList.add('terminal__line');
232
- line.classList.add(type);
264
+ /**
265
+ * Subscribe to raw terminal input sequences (keystrokes, paste, mouse reports, DSR responses).
266
+ */
267
+ onData(callback) {
268
+ if (typeof callback !== 'function') return () => {};
269
+ this._dataListeners.push(callback);
270
+ return () => {
271
+ const idx = this._dataListeners.indexOf(callback);
272
+ if (idx !== -1) this._dataListeners.splice(idx, 1);
273
+ };
274
+ }
233
275
 
234
- line.innerHTML = this._ansi.ansi_to_html(data);
276
+ /**
277
+ * Subscribe to terminal resize events `{ cols, rows }`.
278
+ */
279
+ onResize(callback) {
280
+ if (typeof callback !== 'function') return () => {};
281
+ this._resizeListeners.push(callback);
282
+ return () => {
283
+ const idx = this._resizeListeners.indexOf(callback);
284
+ if (idx !== -1) this._resizeListeners.splice(idx, 1);
285
+ };
286
+ }
235
287
 
236
- this._cmdList.appendChild(line);
237
- this._autoScroll();
238
- } else {
239
- this._animateType(data, type);
240
- }
288
+ onTitleChange(callback) {
289
+ if (typeof callback !== 'function') return () => {};
290
+ this._titleListeners.push(callback);
291
+ return () => {
292
+ const idx = this._titleListeners.indexOf(callback);
293
+ if (idx !== -1) this._titleListeners.splice(idx, 1);
294
+ };
241
295
  }
242
296
 
243
- _autoScroll() {
244
- if(this._el.scrollTop + this._el.offsetHeight >= this._el.scrollHeight -50) {
245
- this._el.scrollTo(0, this._el.scrollHeight)
297
+ /**
298
+ * Resize the terminal grid to `(cols, rows)`.
299
+ */
300
+ resize(cols, rows) {
301
+ const c = Math.max(1, Math.floor(cols));
302
+ const r = Math.max(1, Math.floor(rows));
303
+ if (c === this.screen.cols && r === this.screen.rows && this._lastCols === c && this._lastRows === r) {
304
+ return;
246
305
  }
306
+ this._lastCols = c;
307
+ this._lastRows = r;
308
+ this.screen.resize(c, r);
309
+ if (this.cli && typeof this.cli.setTerminalSize === 'function') {
310
+ this.cli.setTerminalSize(c, r);
311
+ }
312
+ for (const fn of this._resizeListeners) {
313
+ fn({ cols: c, rows: r });
314
+ }
315
+ this.renderer.flushRender();
247
316
  }
248
317
 
249
- _animateType(text, type) {
250
- if(this._animating) {
251
- return requestAnimationFrame(this._animateType.bind(this, text, type));
252
- }
318
+ /**
319
+ * Attach an external shell / PTY / Duplex stream (e.g. zsh, bash, WebSocket bridge).
320
+ */
321
+ attach(stream) {
322
+ if (!stream) return () => {};
323
+ this._attachedStream = stream;
253
324
 
254
- const line = document.createElement('li');
255
- line.classList.add('terminal__line');
256
- line.classList.add(type);
257
- this._cmdList.appendChild(line);
325
+ const onStreamData = (chunk) => {
326
+ this.write(chunk);
327
+ };
258
328
 
259
- let content
260
- try {
261
- content = this._ansi.ansi_to_html(text);
262
- } catch(e) {
263
- content = text
329
+ if (typeof stream.on === 'function') {
330
+ stream.on('data', onStreamData);
331
+ } else if (typeof stream.addEventListener === 'function') {
332
+ stream.addEventListener('message', (ev) => this.write(ev.data ?? ev));
264
333
  }
265
- this._animating = line;
266
334
 
267
- let index = 0;
268
- const timer = setInterval(() => {
269
- const char = content.charAt(index);
335
+ const offData = this.onData((data) => {
336
+ if (typeof stream.write === 'function') {
337
+ stream.write(data);
338
+ } else if (typeof stream.send === 'function') {
339
+ stream.send(data);
340
+ }
341
+ });
270
342
 
271
- if(char === '<') {
272
- index = content.indexOf('>', index);
343
+ const offResize = this.onResize(({ cols, rows }) => {
344
+ if (typeof stream.resize === 'function') {
345
+ stream.resize(cols, rows);
273
346
  }
347
+ });
274
348
 
275
- line.innerHTML = content.substr(0, index);
349
+ if (typeof stream.resize === 'function') {
350
+ stream.resize(this.cols, this.rows);
351
+ }
276
352
 
277
- let increment = 0;
278
- while(increment < this._animateSpeed) {
279
- index++;
280
- if(content.charAt(index) === '<') {
281
- index = content.indexOf('>', index);
282
- }
283
- increment++;
353
+ return () => {
354
+ offData();
355
+ offResize();
356
+ if (typeof stream.removeListener === 'function') {
357
+ stream.removeListener('data', onStreamData);
284
358
  }
285
-
286
- if(index >= content.length - 1) {
287
- line.innerHTML = content;
288
- clearInterval(timer);
289
- delete this._animating;
359
+ if (this._attachedStream === stream) {
360
+ this._attachedStream = null;
290
361
  }
291
- this._autoScroll();
292
- }, 10);
362
+ };
293
363
  }
294
364
 
295
- _clearOutput() {
296
- const lines = this._cmdList.querySelectorAll('li');
297
- lines.forEach(line => this._cmdList.removeChild(line));
365
+ /**
366
+ * Spawn an external shell/command (e.g. '/bin/zsh' or '$SHELL') in a real OS PTY and attach it to this Terminal.
367
+ */
368
+ spawn(command, args = [], options = {}) {
369
+ const pty = spawnPty(command, args, Object.assign({
370
+ cols: this.cols,
371
+ rows: this.rows
372
+ }, options));
373
+ const detach = this.attach(pty);
374
+ pty.on('exit', (code) => {
375
+ if (typeof this._exitFn === 'function') {
376
+ this._exitFn(code);
377
+ }
378
+ });
379
+ return { pty, detach };
298
380
  }
299
381
 
300
- _clearLine(type) {
301
- const lines = this._cmdList.querySelectorAll(`li.terminal__line.${type}`);
302
- lines.forEach(line => this._cmdList.removeChild(line));
303
- }
382
+ /**
383
+ * Create a Node-compatible `{ stdin, stdout }` TTY stream pair wired to this Terminal.
384
+ * Can be passed directly to `blessed.screen({ input: tty.stdin, output: tty.stdout })`
385
+ * or Node's `readline`.
386
+ */
387
+ createTty(options = {}) {
388
+ const stdin = new MiniEventStream();
389
+ const stdout = new MiniEventStream();
390
+ const interceptShell = options.interceptShell !== false;
391
+
392
+ stdout.columns = this.cols;
393
+ stdout.rows = this.rows;
394
+ stdout.getWindowSize = () => [stdout.columns, stdout.rows];
395
+ stdout.write = (chunk, enc, cb) => {
396
+ this.write(chunk);
397
+ if (typeof enc === 'function') enc();
398
+ else if (typeof cb === 'function') cb();
399
+ return true;
400
+ };
401
+
402
+ const offData = this.onData((data) => {
403
+ const payload = stdin._encoding
404
+ ? data
405
+ : (typeof Buffer !== 'undefined' ? Buffer.from(data, 'utf8') : data);
406
+ stdin.emit('data', payload);
407
+ });
408
+
409
+ const offResize = this.onResize(({ cols, rows }) => {
410
+ stdout.columns = cols;
411
+ stdout.rows = rows;
412
+ stdout.emit('resize');
413
+ });
414
+
415
+ const dispose = () => {
416
+ offData();
417
+ offResize();
418
+ stdin.destroy();
419
+ stdout.destroy();
420
+ };
304
421
 
305
- _setCurrentLine(buffer) {
306
- const pos = Math.min(this._cursorPos, buffer.length);
422
+ return { stdin, stdout, dispose };
423
+ }
307
424
 
308
- while (this._currentLine.firstChild) {
309
- this._currentLine.removeChild(this._currentLine.firstChild);
425
+ /**
426
+ * Programmatically send a key press (with optional `{ alt, ctrl, shift }` modifiers).
427
+ */
428
+ sendKey(key, modifiers = {}) {
429
+ const seq = this._encodeKey(key, modifiers);
430
+ if (seq) {
431
+ this._emitInput(seq);
310
432
  }
433
+ }
311
434
 
312
- const prompt = `${this.cli.getPrompt()} `;
435
+ /**
436
+ * Programmatically or DOM-triggered mouse event at 1-based `(col, row)`.
437
+ */
438
+ sendMouse(type, { button = 0, col = 1, row = 1, shift = false, alt = false, ctrl = false, deltaY = 0 } = {}) {
439
+ const mode = this.parser.mouseTrackingMode;
440
+ const c = Math.max(1, Math.min(this.cols, col));
441
+ const r = Math.max(1, Math.min(this.rows, row));
442
+
443
+ // When TUI mouse mode is off (or Shift is held), handle native scrollback / alt-scroll
444
+ if (mode === 0 || shift) {
445
+ if (type === 'wheel') {
446
+ if (this.screen.isAltScreen && this.parser.alternateScrollMode) {
447
+ const arrow = deltaY < 0 ? 'ArrowUp' : 'ArrowDown';
448
+ this.sendKey(arrow);
449
+ } else if (!this.screen.isAltScreen) {
450
+ this.screen.scrollViewport(deltaY < 0 ? 3 : -3);
451
+ this.renderer.flushRender();
452
+ }
453
+ }
454
+ return false;
455
+ }
456
+
457
+ let btnCode = button;
458
+ if (type === 'wheel') {
459
+ btnCode = deltaY < 0 ? 64 : 65;
460
+ } else if (type === 'mousemove') {
461
+ if (mode === 1000) return false;
462
+ if (mode === 1002 && this._mouseButtonDown === null) return false;
463
+ btnCode = (this._mouseButtonDown ?? 0) + 32;
464
+ } else if (type === 'mousedown') {
465
+ this._mouseButtonDown = button;
466
+ } else if (type === 'mouseup') {
467
+ this._mouseButtonDown = null;
468
+ if (this.parser.mouseProtocol !== 'sgr') {
469
+ btnCode = 3;
470
+ }
471
+ }
313
472
 
314
- if (this._cursor !== 'none') {
315
- const before = buffer.slice(0, pos).join('');
316
- const atChar = pos < buffer.length ? buffer[pos] : ' ';
317
- const after = buffer.slice(pos + 1).join('');
473
+ if (shift) btnCode += 4;
474
+ if (alt) btnCode += 8;
475
+ if (ctrl) btnCode += 16;
318
476
 
319
- this._currentLine.appendChild(document.createTextNode(prompt + before));
477
+ if (this.parser.mouseProtocol === 'sgr') {
478
+ const suffix = type === 'mouseup' ? 'm' : 'M';
479
+ this._emitInput(`\x1b[<${btnCode};${c};${r}${suffix}`);
480
+ return true;
481
+ }
320
482
 
321
- const cursor = document.createElement('span');
322
- cursor.textContent = atChar;
323
- cursor.classList.add('terminal__cursor');
324
- cursor.classList.add(this._cursor);
325
- this._currentLine.appendChild(cursor);
483
+ // X10 / UTF-8 protocol
484
+ const maxCoord = this.parser.mouseProtocol === 'utf8' ? 2015 : 223;
485
+ const clampedCol = Math.min(maxCoord, c);
486
+ const clampedRow = Math.min(maxCoord, r);
487
+ this._emitInput(
488
+ '\x1b[M'
489
+ + String.fromCharCode(32 + btnCode)
490
+ + String.fromCharCode(32 + clampedCol)
491
+ + String.fromCharCode(32 + clampedRow)
492
+ );
493
+ return true;
494
+ }
326
495
 
327
- if (after) {
328
- this._currentLine.appendChild(document.createTextNode(after));
329
- }
496
+ onCommand(command) {
497
+ if (this.cli && typeof this.cli.sendCommand === 'function') {
498
+ this.cli.sendCommand(command);
330
499
  } else {
331
- this._currentLine.innerText = `${prompt}${buffer.join('')}`;
500
+ this._emitInput(String(command) + '\r');
332
501
  }
333
502
  }
334
503
 
335
- _clearCursor() {
336
- if(this._cursor !== 'none') {
337
- const cursor = document.querySelectorAll('.terminal__cursor');
338
- if(cursor.length) {
339
- cursor.forEach(c => c.parentElement.removeChild(c));
340
- }
341
- }
504
+ getScreenText(options) {
505
+ this.renderer.flushRender();
506
+ return this.screen.getScreenText(options);
342
507
  }
343
508
 
344
- _statusCheck(status) {
345
- const readyStatus = this.cli?.constructor?.STATUS_READY || ImportedShell?.STATUS_READY || globalThis.Shell?.STATUS_READY || globalThis.shell?.STATUS_READY || 'READY';
346
- if(status === readyStatus) {
347
- if (this._interactive) {
348
- this._exitInteractiveMode();
349
- }
350
- this._working = false;
351
- if (!this._historyLoaded) {
352
- this._loadHistory();
353
- this._historyLoaded = true;
354
- }
355
- if(this._animating) {
356
- return requestAnimationFrame(this._statusCheck.bind(this, status));
357
- }
358
- this._newPrompt(this._setCurrentLine.bind(this, this._buffer));
359
- if (this._pendingCommands && this._pendingCommands.length > 0) {
360
- const nextCmd = this._pendingCommands.shift();
361
- if (this._pendingCommands.length === 0 && this.cli) {
362
- const flags = this.cli.context.getVar('-');
363
- if (flags.includes('c')) {
364
- this.cli.context.setVar('-', flags.replace(/c/g, ''));
365
- }
366
- }
367
- this.onCommand(nextCmd);
368
- }
369
- } else {
370
- this._clearCursor();
371
- this._working = true;
372
- }
509
+ getLineText(row, trimRight = true) {
510
+ this.renderer.flushRender();
511
+ return this.screen.getLineText(row, trimRight);
373
512
  }
374
513
 
375
- _loadHistory() {
514
+ _emitInput(data) {
515
+ if (!data) return;
516
+ // Snap viewport back to bottom on user input
517
+ if (this.screen.viewportOffset > 0) {
518
+ this.screen.viewportOffset = 0;
519
+ this.screen._markAllDirty();
520
+ this.renderer.flushRender();
521
+ }
522
+ // Flush any in-progress typing animation when the user interacts with the terminal
523
+ if (this._typeQueue || this._typeTimer !== null) {
524
+ this._flushTypeQueue();
525
+ this.renderer.flushRender();
526
+ this._autoScroll();
527
+ }
528
+ const isPureEnter = data === '\r' || data === '\n' || data === '\r\n';
529
+ this._suppressAnimationUntil = isPureEnter ? 0 : Date.now() + 80;
530
+ this._isHandlingInput = !isPureEnter;
376
531
  try {
377
- const file = this.cli.context.fs._getFileRaw(HISTORY_FILE);
378
- if (file && typeof file === 'string' && file.length > 0) {
379
- this._history = file.split('\n').filter(l => l.length > 0);
532
+ for (const fn of this._dataListeners) {
533
+ fn(data);
380
534
  }
381
- } catch(e) {
382
- // No history file yet
535
+ } finally {
536
+ this._isHandlingInput = false;
383
537
  }
384
538
  }
385
539
 
386
- _saveHistory() {
387
- try {
388
- this.cli.context.fs._setFileRaw(HISTORY_FILE, this._history.join('\n'), true);
389
- } catch(e) {
390
- // Ignore persistence errors
540
+ _flushTypeQueue() {
541
+ if (this._typeTimer !== null) {
542
+ clearInterval(this._typeTimer);
543
+ this._typeTimer = null;
544
+ }
545
+ if (this._typeQueue) {
546
+ const pending = this._typeQueue;
547
+ this._typeQueue = '';
548
+ this.parser.write(pending);
391
549
  }
392
550
  }
393
551
 
394
- _navigateHistory(direction, onUpdate) {
395
- if (this._history.length === 0) return;
552
+ _isUserInputActive() {
553
+ if (this._isHandlingInput) return true;
554
+ if (this._suppressAnimationUntil && Date.now() < this._suppressAnimationUntil) {
555
+ return true;
556
+ }
557
+ return false;
558
+ }
396
559
 
397
- if (direction === -1) {
398
- if (this._historyPos === null) {
399
- this._savedInput = [...this._buffer];
400
- this._historyPos = this._history.length - 1;
401
- } else if (this._historyPos > 0) {
402
- this._historyPos--;
403
- } else {
404
- return;
405
- }
406
- this._buffer = Array.from(this._history[this._historyPos]);
407
- } else {
408
- if (this._historyPos === null) return;
409
- if (this._historyPos < this._history.length - 1) {
410
- this._historyPos++;
411
- this._buffer = Array.from(this._history[this._historyPos]);
412
- } else {
413
- this._historyPos = null;
414
- this._buffer = this._savedInput ? [...this._savedInput] : [];
415
- this._savedInput = null;
560
+ _isFullScreenWrite(str) {
561
+ if (this.screen.isAltScreen) return true;
562
+ if (this.cli && this.cli.runningCommand) {
563
+ const cmd = this.cli.runningCommand;
564
+ if (cmd.interactive || cmd._inAltScreen || (cmd.stdinStream && cmd.stdinStream.isRaw)) {
565
+ return true;
416
566
  }
417
567
  }
418
-
419
- this._cursorPos = this._buffer.length;
420
- onUpdate(this._buffer);
568
+ if (this._attachedStream && this._attachedStream.isRaw) {
569
+ return true;
570
+ }
571
+ // Alternate screen buffer enter/exit or full-screen 2D cursor/screen control sequences
572
+ if (/\x1b\[\?(?:1049|1047|47)[hl]/.test(str)) return true;
573
+ if (/\x1b\[(?:\d*J|(?:\d+;\d+)?[Hf]|\d*[ABLM]|\d*;\d*r)/.test(str)) return true;
574
+ return false;
421
575
  }
422
576
 
423
- _attachShellListeners() {
424
- this.cli.on('status', this._statusCheck.bind(this));
425
-
426
- this.cli.on('stdOut', line => {
427
- if (this._interactive) {
428
- this._renderInteractiveScreen(line);
429
- } else {
430
- this._print(line, 'out');
431
- }
432
- });
577
+ _isLineRewrite(str) {
578
+ // Bare carriage return (\r not followed by \n) rewrites the current line in-place
579
+ if (/\r(?!\n)/.test(str)) return true;
580
+ // In-line erase (EL) or horizontal cursor movement / char insert-delete
581
+ if (/\x1b\[\d*[KCDG@P]/.test(str)) return true;
582
+ // Backspace / delete character editing on the current line
583
+ if (/[\x08\x7f]/.test(str)) return true;
584
+ return false;
585
+ }
433
586
 
434
- this.cli.on('stdErr', line => {
435
- if (!this._interactive) {
436
- this._print(line, 'err');
437
- }
438
- });
587
+ _encodeKey(key, modifiers = {}) {
588
+ const { alt = false, ctrl = false, shift = false, meta = false } = modifiers;
589
+ if (!key || ['Control', 'Alt', 'Shift', 'Meta', 'CapsLock'].includes(key)) {
590
+ return null;
591
+ }
439
592
 
440
- this.cli.on('clear', () => {
441
- this._clearOutput();
442
- });
593
+ // Allow native browser copy/paste/reload shortcuts with Meta (Cmd on macOS)
594
+ if (meta) return null;
443
595
 
444
- this.cli.on('interactive', () => {
445
- this._enterInteractiveMode();
446
- });
596
+ const appCursor = this.parser.applicationCursorKeys;
447
597
 
448
- this.cli.on('exit', code => {
449
- delete this.cli;
450
- if(typeof this._exitFn === 'function') {
451
- this._exitFn(code);
598
+ if (key === 'ArrowUp') {
599
+ if (alt) return '\x1b[1;3A';
600
+ if (ctrl) return '\x1b[1;5A';
601
+ return appCursor ? '\x1bOA' : '\x1b[A';
602
+ }
603
+ if (key === 'ArrowDown') {
604
+ if (alt) return '\x1b[1;3B';
605
+ if (ctrl) return '\x1b[1;5B';
606
+ return appCursor ? '\x1bOB' : '\x1b[B';
607
+ }
608
+ if (key === 'ArrowRight') {
609
+ if (alt) return '\x1b[1;3C';
610
+ if (ctrl) return '\x1b[1;5C';
611
+ return appCursor ? '\x1bOC' : '\x1b[C';
612
+ }
613
+ if (key === 'ArrowLeft') {
614
+ if (alt) return '\x1b[1;3D';
615
+ if (ctrl) return '\x1b[1;5D';
616
+ return appCursor ? '\x1bOD' : '\x1b[D';
617
+ }
618
+ if (key === 'Home') return appCursor ? '\x1bOH' : '\x1b[H';
619
+ if (key === 'End') return appCursor ? '\x1bOF' : '\x1b[F';
620
+ if (key === 'Delete') return '\x1b[3~';
621
+ if (key === 'Insert') return '\x1b[2~';
622
+ if (key === 'PageUp') return '\x1b[5~';
623
+ if (key === 'PageDown') return '\x1b[6~';
624
+ if (key === 'Enter') return '\r';
625
+ if (key === 'Backspace') return alt ? '\x1b\x7f' : '\x7f';
626
+ if (key === 'Tab') return shift ? '\x1b[Z' : '\t';
627
+ if (key === 'Escape') return '\x1b';
628
+
629
+ const fnMatch = key.match(/^F(\d{1,2})$/);
630
+ if (fnMatch) {
631
+ const fnMap = {
632
+ 1: '\x1bOP', 2: '\x1bOQ', 3: '\x1bOR', 4: '\x1bOS',
633
+ 5: '\x1b[15~', 6: '\x1b[17~', 7: '\x1b[18~', 8: '\x1b[19~',
634
+ 9: '\x1b[20~', 10: '\x1b[21~', 11: '\x1b[23~', 12: '\x1b[24~'
635
+ };
636
+ return fnMap[Number(fnMatch[1])] || null;
637
+ }
638
+
639
+ if (ctrl && key.length === 1) {
640
+ const upper = key.toUpperCase().charCodeAt(0);
641
+ if (upper >= 64 && upper <= 95) {
642
+ const ctrlChar = String.fromCharCode(upper - 64);
643
+ return alt ? '\x1b' + ctrlChar : ctrlChar;
452
644
  }
453
- });
645
+ }
646
+
647
+ if (key.length === 1) {
648
+ return alt ? '\x1b' + key : key;
649
+ }
454
650
 
455
- this._listenForKeyEvents(this._setCurrentLine.bind(this), window);
651
+ return null;
456
652
  }
457
653
 
458
- _listenForKeyEvents(onUpdate, el) {
459
- window.addEventListener('keydown', e => {
460
- // Interactive mode: route ALL keystrokes to the running command
461
- if (this._interactive) {
462
- e.preventDefault();
463
- const key = this._buildInteractiveKey(e);
464
- if (key) this.cli.onInput(key);
465
- return;
466
- }
654
+ _enqueueTypeAnimation(str) {
655
+ this._typeQueue += str;
656
+ if (this._typeTimer !== null) return;
467
657
 
468
- if (e.keyCode === 9) {
469
- e.preventDefault();
658
+ this._typeTimer = setInterval(() => {
659
+ if (!this._typeQueue) {
660
+ clearInterval(this._typeTimer);
661
+ this._typeTimer = null;
662
+ return;
470
663
  }
471
664
 
472
- const navKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'Delete'];
473
- if (navKeys.includes(e.key)) {
474
- e.preventDefault();
475
- this._navKeyEvent(onUpdate, e);
665
+ if (this._isFullScreenWrite(this._typeQueue)) {
666
+ this._flushTypeQueue();
667
+ this.renderer.flushRender();
668
+ this._autoScroll();
476
669
  return;
477
670
  }
478
671
 
479
- if (e.ctrlKey && ['a', 'e', 'u', 'k'].includes(e.key.toLowerCase())) {
480
- e.preventDefault();
481
- this._navKeyEvent(onUpdate, e);
482
- }
483
- });
672
+ let count = 0;
673
+ let idx = 0;
484
674
 
485
- el.addEventListener('keyup', (e) => {
486
- if (this._interactive) return;
487
- this._keyEvent(onUpdate, e.key);
488
- });
675
+ // If the current line segment in the queue is an in-place line rewrite (e.g. trailing prompt or progress update),
676
+ // consume the entire line segment in one step instead of animating it character-by-character.
677
+ const nlIdx = this._typeQueue.indexOf('\n');
678
+ const lineEnd = nlIdx === -1 ? this._typeQueue.length : nlIdx + 1;
679
+ const currentLine = this._typeQueue.slice(0, lineEnd);
680
+ if (this._isLineRewrite(currentLine)) {
681
+ idx = lineEnd;
682
+ } else {
683
+ while (idx < this._typeQueue.length && count < this._animateSpeed) {
684
+ if (this._typeQueue.charCodeAt(idx) === 0x1b) {
685
+ // Consume entire escape sequence in one step so partial sequences don't stall
686
+ idx++;
687
+ if (this._typeQueue[idx] === '[') {
688
+ idx++;
689
+ while (idx < this._typeQueue.length && this._typeQueue.charCodeAt(idx) < 0x40) {
690
+ idx++;
691
+ }
692
+ if (idx < this._typeQueue.length) idx++;
693
+ } else if (this._typeQueue[idx] === ']') {
694
+ idx++;
695
+ while (idx < this._typeQueue.length && this._typeQueue.charCodeAt(idx) !== 0x07) {
696
+ if (this._typeQueue.charCodeAt(idx) === 0x1b && this._typeQueue[idx + 1] === '\\') {
697
+ idx += 2;
698
+ break;
699
+ }
700
+ idx++;
701
+ }
702
+ if (idx < this._typeQueue.length && this._typeQueue.charCodeAt(idx) === 0x07) idx++;
703
+ } else if (idx < this._typeQueue.length) {
704
+ idx++;
705
+ }
706
+ } else {
707
+ idx++;
708
+ count++;
709
+ }
710
+ }
711
+ }
489
712
 
490
- window.addEventListener('paste', (e) => {
491
- e.preventDefault();
492
- if (this._interactive) return;
493
- const text = (e.clipboardData || window.clipboardData).getData('text');
494
- if (!text) return;
713
+ // If only a trailing line rewrite (such as the shell prompt) remains after this slice, flush it immediately
714
+ const remainder = this._typeQueue.slice(idx);
715
+ if (remainder && !remainder.includes('\n') && this._isLineRewrite(remainder)) {
716
+ idx = this._typeQueue.length;
717
+ }
495
718
 
496
- const segments = text.split(/\r?\n/);
497
- segments.forEach((segment, idx) => {
498
- const chars = segment.split('');
499
- this._buffer.splice(this._cursorPos, 0, ...chars);
500
- this._cursorPos += chars.length;
719
+ const slice = this._typeQueue.slice(0, idx);
720
+ this._typeQueue = this._typeQueue.slice(idx);
721
+ this.parser.write(slice);
722
+ this.renderer.flushRender();
723
+ this._autoScroll();
724
+ }, 10);
725
+ }
501
726
 
502
- if (idx < segments.length - 1) {
503
- this._keyEvent(onUpdate, 'Enter');
504
- }
505
- });
727
+ _setupDom(parent, font = 'Roboto Mono') {
728
+ if (typeof document === 'undefined') return;
506
729
 
507
- onUpdate(this._buffer);
508
- });
509
- }
730
+ const style = document.createElement('link');
731
+ style.href = `https://fonts.googleapis.com/css?family=${encodeURIComponent(font)}:ital,wght@0,400;0,700;1,400;1,700&display=swap`;
732
+ style.rel = 'stylesheet';
733
+ if (document.head && document.head.appendChild) {
734
+ document.head.appendChild(style);
735
+ }
510
736
 
511
- _buildInteractiveKey(e) {
512
- const key = e.key;
513
- // Skip bare modifier keys
514
- if (['Control', 'Alt', 'Shift', 'Meta'].includes(key)) return null;
515
- // Ctrl+letter → caret notation '^X'
516
- if (e.ctrlKey && key.length === 1) {
517
- return '^' + key.toUpperCase();
737
+ this._cmdList = document.createElement('ul');
738
+ this._cmdList.style.fontFamily = `'${font}', monospace`;
739
+ this._cmdList.style.listStyle = 'none';
740
+ this._cmdList.style.padding = '0';
741
+ this._cmdList.style.margin = '0';
742
+ if (this._lineWrap) {
743
+ this._cmdList.classList.add('terminal--wrap');
518
744
  }
519
- // All other keys passed as e.key strings ('ArrowUp', 'Enter', 'a', etc.)
520
- return key;
521
- }
745
+ parent.appendChild(this._cmdList);
522
746
 
523
- _wordLeft() {
524
- let pos = this._cursorPos;
525
- while (pos > 0 && this._buffer[pos - 1] === ' ') pos--;
526
- while (pos > 0 && this._buffer[pos - 1] !== ' ') pos--;
527
- return pos;
528
- }
747
+ this._charMeasure = document.createElement('span');
748
+ this._charMeasure.className = 'terminal__char-measure';
749
+ this._charMeasure.style.fontFamily = `'${font}', monospace`;
750
+ this._charMeasure.textContent = 'X';
751
+ this._charMeasure.setAttribute('aria-hidden', 'true');
752
+ parent.appendChild(this._charMeasure);
529
753
 
530
- _wordRight() {
531
- let pos = this._cursorPos;
532
- const len = this._buffer.length;
533
- while (pos < len && this._buffer[pos] === ' ') pos++;
534
- while (pos < len && this._buffer[pos] !== ' ') pos++;
535
- return pos;
754
+ setTimeout(() => this._measureAndSetSize(), 0);
755
+ if (document.fonts && document.fonts.ready) {
756
+ document.fonts.ready.then(() => this._measureAndSetSize());
757
+ }
758
+ if (typeof ResizeObserver !== 'undefined') {
759
+ new ResizeObserver(() => this._measureAndSetSize()).observe(parent);
760
+ }
536
761
  }
537
762
 
538
- _navKeyEvent(onUpdate, e) {
539
- if (this._working || this._animating) return;
540
-
541
- const key = e.key;
763
+ _listenForEvents() {
764
+ if (typeof window === 'undefined') return;
542
765
 
543
- if (key === 'ArrowLeft') {
544
- if (e.altKey) {
545
- this._cursorPos = this._wordLeft();
546
- } else if (this._cursorPos > 0) {
547
- this._cursorPos--;
548
- }
549
- onUpdate(this._buffer);
550
- } else if (key === 'ArrowRight') {
551
- if (e.altKey) {
552
- this._cursorPos = this._wordRight();
553
- } else if (this._cursorPos < this._buffer.length) {
554
- this._cursorPos++;
555
- }
556
- onUpdate(this._buffer);
557
- } else if (key === 'Home' || (e.ctrlKey && key.toLowerCase() === 'a')) {
558
- this._cursorPos = 0;
559
- onUpdate(this._buffer);
560
- } else if (key === 'End' || (e.ctrlKey && key.toLowerCase() === 'e')) {
561
- this._cursorPos = this._buffer.length;
562
- onUpdate(this._buffer);
563
- } else if (key === 'Delete') {
564
- if (this._cursorPos < this._buffer.length) {
565
- this._buffer.splice(this._cursorPos, 1);
566
- onUpdate(this._buffer);
766
+ this._onKeyDown = (e) => {
767
+ if (e.metaKey) return;
768
+ const seq = this._encodeKey(e.key, {
769
+ alt: Boolean(e.altKey),
770
+ ctrl: Boolean(e.ctrlKey),
771
+ shift: Boolean(e.shiftKey),
772
+ meta: Boolean(e.metaKey)
773
+ });
774
+ if (seq) {
775
+ if (e.preventDefault) e.preventDefault();
776
+ this._emitInput(seq);
567
777
  }
568
- } else if (e.ctrlKey && key.toLowerCase() === 'u') {
569
- this._buffer.splice(0, this._cursorPos);
570
- this._cursorPos = 0;
571
- onUpdate(this._buffer);
572
- } else if (e.ctrlKey && key.toLowerCase() === 'k') {
573
- this._buffer.splice(this._cursorPos);
574
- onUpdate(this._buffer);
575
- } else if (key === 'ArrowUp') {
576
- this._navigateHistory(-1, onUpdate);
577
- } else if (key === 'ArrowDown') {
578
- this._navigateHistory(1, onUpdate);
579
- }
580
- }
581
-
582
- _keyEvent(onUpdate, key) {
583
- this._clearLine('autoComplete');
584
- if (this.cli.onInput(key)) {
585
- return;
586
- }
778
+ };
587
779
 
588
- if (key.length === 1) {
589
- this._buffer.splice(this._cursorPos, 0, key);
590
- this._cursorPos++;
780
+ this._onPaste = (e) => {
781
+ const clipboard = e.clipboardData || (typeof window !== 'undefined' && window.clipboardData);
782
+ if (!clipboard || typeof clipboard.getData !== 'function') return;
783
+ const text = clipboard.getData('text');
784
+ if (!text) return;
785
+ if (e.preventDefault) e.preventDefault();
591
786
 
592
- if (!this._working && !this._animating) {
593
- onUpdate(this._buffer);
594
- }
595
- } else if (key === 'Enter' && !this._working) {
596
- const command = this._buffer.join('');
597
- this._buffer = [];
598
- this._cursorPos = 0;
599
- this._historyPos = null;
600
- this._savedInput = null;
601
-
602
- if (command.trim()) {
603
- if (this._history[this._history.length - 1] !== command) {
604
- this._history.push(command);
605
- }
606
- this._saveHistory();
787
+ const normalized = text.replace(/\r?\n/g, '\r');
788
+ if (this.parser.bracketedPasteMode) {
789
+ this._emitInput(`\x1b[200~${normalized}\x1b[201~`);
790
+ } else {
791
+ this._emitInput(normalized);
607
792
  }
793
+ };
608
794
 
609
- this.cli.onCommand(command);
610
- } else if (key === 'Backspace') {
611
- if (this._cursorPos > 0) {
612
- this._buffer.splice(this._cursorPos - 1, 1);
613
- this._cursorPos--;
795
+ window.addEventListener('keydown', this._onKeyDown);
796
+ window.addEventListener('paste', this._onPaste);
614
797
 
615
- if (!this._working && !this._animating) {
616
- onUpdate(this._buffer);
798
+ if (this._el && typeof this._el.addEventListener === 'function') {
799
+ const coordsFromMouse = (e) => {
800
+ if (!this._charMeasure || !this._el.getBoundingClientRect) {
801
+ return { col: 1, row: 1 };
617
802
  }
618
- }
619
- } else if (key === 'Tab' && !this._working && !this._animating) {
620
- const commandParts = this._buffer.join('').split(' ');
621
- const lastPath = commandParts.pop();
622
-
623
- const autoComplete = this.cli.tabCompletion(lastPath);
624
- if(autoComplete) {
625
- const {options, path} = autoComplete;
626
-
627
- if(options.length === 1) {
628
- commandParts.push(`${path != null ? path.concat('/') : ''}${options[0]}`);
629
- this._buffer = commandParts.join(' ').split('');
630
- } else {
631
- this._print(options.join(' '), 'autoComplete');
803
+ const charRect = this._charMeasure.getBoundingClientRect();
804
+ const box = this._el.getBoundingClientRect();
805
+ const cw = charRect.width || 8;
806
+ const ch = charRect.height || 16;
807
+ const col = Math.max(1, Math.min(this.cols, Math.floor(((e.clientX || 0) - box.left) / cw) + 1));
808
+ const row = Math.max(1, Math.min(this.rows, Math.floor(((e.clientY || 0) - box.top) / ch) + 1));
809
+ return { col, row };
810
+ };
811
+
812
+ this._el.addEventListener('mousedown', (e) => {
813
+ // Allow clicking links when TUI mouse tracking is off or Cmd/Ctrl is held
814
+ const target = e.target;
815
+ if (target && target.tagName === 'A' && (this.parser.mouseTrackingMode === 0 || e.metaKey || e.ctrlKey)) {
816
+ return;
632
817
  }
818
+ const { col, row } = coordsFromMouse(e);
819
+ const handled = this.sendMouse('mousedown', {
820
+ button: e.button || 0,
821
+ col,
822
+ row,
823
+ shift: Boolean(e.shiftKey),
824
+ alt: Boolean(e.altKey),
825
+ ctrl: Boolean(e.ctrlKey)
826
+ });
827
+ if (handled && e.preventDefault) e.preventDefault();
828
+ });
633
829
 
634
- this._cursorPos = this._buffer.length;
635
- onUpdate(this._buffer);
636
- }
830
+ this._el.addEventListener('mouseup', (e) => {
831
+ const { col, row } = coordsFromMouse(e);
832
+ const handled = this.sendMouse('mouseup', {
833
+ button: e.button || 0,
834
+ col,
835
+ row,
836
+ shift: Boolean(e.shiftKey),
837
+ alt: Boolean(e.altKey),
838
+ ctrl: Boolean(e.ctrlKey)
839
+ });
840
+ if (handled && e.preventDefault) e.preventDefault();
841
+ });
842
+
843
+ this._el.addEventListener('mousemove', (e) => {
844
+ if (this.parser.mouseTrackingMode === 0) return;
845
+ const { col, row } = coordsFromMouse(e);
846
+ this.sendMouse('mousemove', {
847
+ button: e.button || 0,
848
+ col,
849
+ row,
850
+ shift: Boolean(e.shiftKey),
851
+ alt: Boolean(e.altKey),
852
+ ctrl: Boolean(e.ctrlKey)
853
+ });
854
+ });
855
+
856
+ this._el.addEventListener('wheel', (e) => {
857
+ const { col, row } = coordsFromMouse(e);
858
+ const handled = this.sendMouse('wheel', {
859
+ col,
860
+ row,
861
+ deltaY: e.deltaY || 0,
862
+ shift: Boolean(e.shiftKey),
863
+ alt: Boolean(e.altKey),
864
+ ctrl: Boolean(e.ctrlKey)
865
+ });
866
+ if (handled && e.preventDefault) e.preventDefault();
867
+ });
637
868
  }
638
869
  }
639
- _enterInteractiveMode() {
640
- this._interactive = true;
641
- this._cmdList.style.display = 'none';
642
- this._screen.style.display = 'block';
643
- this._clearCursor();
644
- }
645
870
 
646
- _exitInteractiveMode() {
647
- this._interactive = false;
648
- this._screen.style.display = 'none';
649
- this._screen.innerHTML = '';
650
- this._cmdList.style.display = '';
871
+ _mobileInput() {
872
+ if (typeof document === 'undefined' || !this._el) return;
873
+ const input = document.createElement('input');
874
+ input.type = 'text';
875
+ input.style.position = 'absolute';
876
+ input.style.left = '-9999999px';
877
+ this._el.appendChild(input);
878
+ this._mobileInputBuffer = '';
879
+
880
+ this._el.addEventListener('click', () => {
881
+ if (typeof input.focus === 'function') input.focus();
882
+ });
883
+
884
+ input.addEventListener('keypress', e => {
885
+ if (e.key === 'Enter') {
886
+ input.value = '';
887
+ this._mobileInputBuffer = input.value;
888
+ }
889
+ });
890
+
891
+ input.addEventListener('keyup', (e) => {
892
+ if (e.key === 'Unidentified') {
893
+ if (input.value.length < this._mobileInputBuffer.length) {
894
+ this.sendKey('Backspace');
895
+ } else if (input.value.length > this._mobileInputBuffer.length) {
896
+ const char = input.value[input.value.length - 1];
897
+ this.sendKey(char);
898
+ }
899
+ this._mobileInputBuffer = input.value;
900
+ }
901
+ });
651
902
  }
652
903
 
653
- _renderInteractiveScreen(text) {
654
- // Strip ANSI clear-screen and cursor-home/position sequences used as
655
- // full-screen replace signal. AnsiUp handles colours; we just drop the
656
- // cursor-control codes before passing to it.
657
- const cleaned = text
658
- .replace(/\x1b\[\d*J/g, '') // erase in display (\x1b[2J etc.)
659
- .replace(/\x1b\[\d+;\d+H/g, '') // cursor position row;col
660
- .replace(/\x1b\[H/g, ''); // cursor home (no args)
661
- try {
662
- this._screen.innerHTML = this._ansi.ansi_to_html(cleaned);
663
- } catch(e) {
664
- this._screen.textContent = cleaned;
904
+ _autoScroll() {
905
+ if (!this._el || typeof this._el.scrollTo !== 'function') return;
906
+ if (this._el.scrollTop + this._el.offsetHeight >= this._el.scrollHeight - 50) {
907
+ this._el.scrollTo(0, this._el.scrollHeight);
665
908
  }
666
909
  }
667
910
 
668
911
  _measureAndSetSize() {
669
- if (!this._charMeasure || !this.cli) return;
912
+ if (!this._charMeasure || !this._el || typeof this._el.getBoundingClientRect !== 'function') return;
670
913
  const charRect = this._charMeasure.getBoundingClientRect();
671
914
  const containerRect = this._el.getBoundingClientRect();
672
- if (!charRect.width || !charRect.height || !containerRect.width) return;
915
+ if (!charRect || !containerRect || !charRect.width || !charRect.height || !containerRect.width) return;
916
+ // Ignore degenerate/mock measurements where single-char span equals container size
917
+ if (charRect.width >= containerRect.width && charRect.height >= containerRect.height) return;
673
918
  const cols = Math.max(1, Math.floor(containerRect.width / charRect.width));
674
- const rows = Math.max(1, Math.floor(containerRect.height / charRect.height));
919
+ const rows = Math.max(1, Math.floor((containerRect.height || (charRect.height * 24)) / charRect.height));
675
920
  if (cols !== this._lastCols || rows !== this._lastRows) {
676
- this._lastCols = cols;
677
- this._lastRows = rows;
678
- this.cli.setTerminalSize(cols, rows);
921
+ this.resize(cols, rows);
679
922
  }
680
923
  }
924
+
925
+ destroy() {
926
+ if (this._typeTimer !== null) {
927
+ clearInterval(this._typeTimer);
928
+ this._typeTimer = null;
929
+ }
930
+ if (typeof window !== 'undefined' && window.removeEventListener) {
931
+ if (this._onKeyDown) window.removeEventListener('keydown', this._onKeyDown);
932
+ if (this._onPaste) window.removeEventListener('paste', this._onPaste);
933
+ }
934
+ this._dataListeners = [];
935
+ this._resizeListeners = [];
936
+ this._titleListeners = [];
937
+ }
681
938
  }
939
+
682
940
  Terminal.Terminal = Terminal;
941
+ Terminal.spawnPty = spawnPty;
683
942
  if (typeof globalThis !== 'undefined') {
684
943
  globalThis.Terminal = Terminal;
685
944
  }