@trismegisto/terminal 3.3.14 → 4.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.
Files changed (156) hide show
  1. package/LICENSE +56 -56
  2. package/MIGRATION.md +831 -0
  3. package/NOTICE +7 -39
  4. package/README.md +55 -16
  5. package/dist/core/attributes.d.ts +53 -0
  6. package/dist/core/attributes.js +75 -0
  7. package/dist/core/attributes.js.map +1 -0
  8. package/dist/core/buffer-line.d.ts +55 -0
  9. package/dist/core/buffer-line.js +242 -0
  10. package/dist/core/buffer-line.js.map +1 -0
  11. package/dist/core/buffer.d.ts +74 -0
  12. package/dist/core/buffer.js +277 -0
  13. package/dist/core/buffer.js.map +1 -0
  14. package/dist/core/charsets.d.ts +8 -0
  15. package/dist/core/charsets.js +79 -0
  16. package/dist/core/charsets.js.map +1 -0
  17. package/dist/core/circular-list.d.ts +22 -0
  18. package/dist/core/circular-list.js +84 -0
  19. package/dist/core/circular-list.js.map +1 -0
  20. package/dist/core/colors.d.ts +32 -0
  21. package/dist/core/colors.js +123 -0
  22. package/dist/core/colors.js.map +1 -0
  23. package/dist/core/event.d.ts +23 -0
  24. package/dist/core/event.js +41 -0
  25. package/dist/core/event.js.map +1 -0
  26. package/dist/core/index.d.ts +11 -0
  27. package/dist/core/index.js +13 -0
  28. package/dist/core/index.js.map +1 -0
  29. package/dist/core/keyboard.d.ts +76 -0
  30. package/dist/core/keyboard.js +248 -0
  31. package/dist/core/keyboard.js.map +1 -0
  32. package/dist/core/parser.d.ts +73 -0
  33. package/dist/core/parser.js +482 -0
  34. package/dist/core/parser.js.map +1 -0
  35. package/dist/core/terminal-core.d.ts +322 -0
  36. package/dist/core/terminal-core.js +1512 -0
  37. package/dist/core/terminal-core.js.map +1 -0
  38. package/dist/core/unicode.d.ts +35 -0
  39. package/dist/core/unicode.js +185 -0
  40. package/dist/core/unicode.js.map +1 -0
  41. package/dist/features/clipboard.d.ts +31 -0
  42. package/dist/features/clipboard.js +77 -0
  43. package/dist/features/clipboard.js.map +1 -0
  44. package/dist/features/connect.d.ts +16 -0
  45. package/dist/features/connect.js +58 -0
  46. package/dist/features/connect.js.map +1 -0
  47. package/dist/features/fit.d.ts +22 -0
  48. package/dist/features/fit.js +98 -0
  49. package/dist/features/fit.js.map +1 -0
  50. package/dist/features/gpu/atlas.d.ts +57 -0
  51. package/dist/features/gpu/atlas.js +90 -0
  52. package/dist/features/gpu/atlas.js.map +1 -0
  53. package/dist/features/gpu/box.d.ts +12 -0
  54. package/dist/features/gpu/box.js +105 -0
  55. package/dist/features/gpu/box.js.map +1 -0
  56. package/dist/features/gpu/frame-model.d.ts +28 -0
  57. package/dist/features/gpu/frame-model.js +105 -0
  58. package/dist/features/gpu/frame-model.js.map +1 -0
  59. package/dist/features/gpu/gl-renderer.d.ts +24 -0
  60. package/dist/features/gpu/gl-renderer.js +211 -0
  61. package/dist/features/gpu/gl-renderer.js.map +1 -0
  62. package/dist/features/gpu/index.d.ts +31 -0
  63. package/dist/features/gpu/index.js +158 -0
  64. package/dist/features/gpu/index.js.map +1 -0
  65. package/dist/features/image/graphics-protocol.d.ts +57 -0
  66. package/dist/features/image/graphics-protocol.js +91 -0
  67. package/dist/features/image/graphics-protocol.js.map +1 -0
  68. package/dist/features/image/iip.d.ts +38 -0
  69. package/dist/features/image/iip.js +158 -0
  70. package/dist/features/image/iip.js.map +1 -0
  71. package/dist/features/image/index.d.ts +100 -0
  72. package/dist/features/image/index.js +783 -0
  73. package/dist/features/image/index.js.map +1 -0
  74. package/dist/features/image/qoi.d.ts +5 -0
  75. package/dist/features/image/qoi.js +70 -0
  76. package/dist/features/image/qoi.js.map +1 -0
  77. package/dist/features/image/sixel.d.ts +30 -0
  78. package/dist/features/image/sixel.js +251 -0
  79. package/dist/features/image/sixel.js.map +1 -0
  80. package/dist/features/image/storage.d.ts +68 -0
  81. package/dist/features/image/storage.js +87 -0
  82. package/dist/features/image/storage.js.map +1 -0
  83. package/dist/features/ligatures.d.ts +17 -0
  84. package/dist/features/ligatures.js +65 -0
  85. package/dist/features/ligatures.js.map +1 -0
  86. package/dist/features/links.d.ts +24 -0
  87. package/dist/features/links.js +86 -0
  88. package/dist/features/links.js.map +1 -0
  89. package/dist/features/program-status.d.ts +32 -0
  90. package/dist/features/program-status.js +196 -0
  91. package/dist/features/program-status.js.map +1 -0
  92. package/dist/features/progress.d.ts +21 -0
  93. package/dist/features/progress.js +55 -0
  94. package/dist/features/progress.js.map +1 -0
  95. package/dist/features/search.d.ts +47 -0
  96. package/dist/features/search.js +188 -0
  97. package/dist/features/search.js.map +1 -0
  98. package/dist/features/serialize.d.ts +33 -0
  99. package/dist/features/serialize.js +301 -0
  100. package/dist/features/serialize.js.map +1 -0
  101. package/dist/features/unicode.d.ts +22 -0
  102. package/dist/features/unicode.js +39 -0
  103. package/dist/features/unicode.js.map +1 -0
  104. package/dist/features/web-fonts.d.ts +22 -0
  105. package/dist/features/web-fonts.js +90 -0
  106. package/dist/features/web-fonts.js.map +1 -0
  107. package/dist/index.d.ts +23 -0
  108. package/dist/index.js +19 -0
  109. package/dist/index.js.map +1 -0
  110. package/dist/terminal/api.d.ts +488 -0
  111. package/dist/terminal/api.js +2 -0
  112. package/dist/terminal/api.js.map +1 -0
  113. package/dist/terminal/create-terminal.d.ts +12 -0
  114. package/dist/terminal/create-terminal.js +17 -0
  115. package/dist/terminal/create-terminal.js.map +1 -0
  116. package/dist/terminal/engine.d.ts +219 -0
  117. package/dist/terminal/engine.js +1654 -0
  118. package/dist/terminal/engine.js.map +1 -0
  119. package/dist/terminal/glyphs.d.ts +7 -0
  120. package/dist/terminal/glyphs.js +135 -0
  121. package/dist/terminal/glyphs.js.map +1 -0
  122. package/dist/terminal/i18n/terminal-catalogs.d.ts +15 -0
  123. package/dist/terminal/i18n/terminal-catalogs.js +22 -0
  124. package/dist/terminal/i18n/terminal-catalogs.js.map +1 -0
  125. package/dist/terminal/i18n/terminal-messages.d.ts +32 -0
  126. package/dist/terminal/i18n/terminal-messages.en.d.ts +2 -0
  127. package/dist/terminal/i18n/terminal-messages.en.js +23 -0
  128. package/dist/terminal/i18n/terminal-messages.en.js.map +1 -0
  129. package/dist/terminal/i18n/terminal-messages.es.d.ts +2 -0
  130. package/dist/terminal/i18n/terminal-messages.es.js +23 -0
  131. package/dist/terminal/i18n/terminal-messages.es.js.map +1 -0
  132. package/dist/terminal/i18n/terminal-messages.js +23 -0
  133. package/dist/terminal/i18n/terminal-messages.js.map +1 -0
  134. package/dist/terminal/renderer.d.ts +120 -0
  135. package/dist/terminal/renderer.js +585 -0
  136. package/dist/terminal/renderer.js.map +1 -0
  137. package/dist/terminal/screen.d.ts +18 -0
  138. package/dist/terminal/screen.js +132 -0
  139. package/dist/terminal/screen.js.map +1 -0
  140. package/dist/terminal/styles.d.ts +2 -0
  141. package/dist/terminal/styles.js +117 -0
  142. package/dist/terminal/styles.js.map +1 -0
  143. package/dist/terminal/terminal-messages.d.ts +2 -0
  144. package/dist/terminal/terminal-messages.js +5 -0
  145. package/dist/terminal/terminal-messages.js.map +1 -0
  146. package/dist/terminal/terminal-view.d.ts +116 -0
  147. package/dist/terminal/terminal-view.js +362 -0
  148. package/dist/terminal/terminal-view.js.map +1 -0
  149. package/dist/terminal/token-theme.d.ts +12 -0
  150. package/dist/terminal/token-theme.js +66 -0
  151. package/dist/terminal/token-theme.js.map +1 -0
  152. package/package.json +39 -30
  153. package/fesm2022/trismegisto-terminal.mjs +0 -9717
  154. package/fesm2022/trismegisto-terminal.mjs.map +0 -1
  155. package/types/trismegisto-terminal.d.ts +0 -1952
  156. package/types/trismegisto-terminal.d.ts.map +0 -1
@@ -0,0 +1,1654 @@
1
+ // O terminal montado: o núcleo deste pacote com renderização DOM, teclado, mouse, seleção, links, decorações, leitor de
2
+ // tela e os recursos ligados por opção. É a implementação do `TerminalHandle` que o `createTerminal` devolve; a classe
3
+ // em si não é exportada pelo pacote.
4
+ import { CircularList } from '../core/circular-list';
5
+ import { ANSI_DEFAULTS, DEFAULT_BACKGROUND, DEFAULT_FOREGROUND, defaultPalette, parseCssColor } from '../core/colors';
6
+ import { DisposableStore, Emitter } from '../core/event';
7
+ import { encodeKey, encodeProgressiveKey, encodeMouse, encodePaste, encodeWin32Key } from '../core/keyboard';
8
+ import { TerminalCore } from '../core/terminal-core';
9
+ import { ClipboardFeature } from '../features/clipboard';
10
+ import { Connection } from '../features/connect';
11
+ import { FitFeature } from '../features/fit';
12
+ import { LigaturesFeature } from '../features/ligatures';
13
+ import { LinksFeature } from '../features/links';
14
+ import { ProgramStatusFeature } from '../features/program-status';
15
+ import { ProgressFeature } from '../features/progress';
16
+ import { SearchFeature } from '../features/search';
17
+ import { Serializer } from '../features/serialize';
18
+ import { Unicode11Feature, UnicodeGraphemesFeature } from '../features/unicode';
19
+ import { WebFontsFeature } from '../features/web-fonts';
20
+ import { DomRenderer } from './renderer';
21
+ import { ScreenView } from './screen';
22
+ import { ensureStyles } from './styles';
23
+ import { DEFAULT_TERMINAL_STRINGS } from './terminal-messages';
24
+ const FEATURE_KEYS = [
25
+ 'fit', 'links', 'search', 'clipboard', 'images', 'gpu', 'unicode', 'ligatures', 'progress', 'programStatus', 'webFonts',
26
+ ];
27
+ export const DEFAULT_TERMINAL_OPTIONS = {
28
+ cols: 80,
29
+ rows: 24,
30
+ scrollback: 1000,
31
+ theme: {},
32
+ fontFamily: 'ui-monospace, monospace',
33
+ fontSize: 15,
34
+ fontWeight: 'normal',
35
+ boldFontWeight: 'bold',
36
+ letterSpacing: 0,
37
+ lineHeight: 1,
38
+ cursorShape: 'block',
39
+ cursorBlink: false,
40
+ cursorBarWidth: 1,
41
+ cursorUnfocusedShape: 'outline',
42
+ builtinBoxGlyphs: true,
43
+ boldAsBright: true,
44
+ minimumContrast: 1,
45
+ squeezeWideGlyphs: false,
46
+ transparentBackground: false,
47
+ textBlinkInterval: 0,
48
+ lineFeedAsNewline: false,
49
+ readOnly: false,
50
+ screenReader: false,
51
+ plainPaste: false,
52
+ optionAsMeta: false,
53
+ optionClickSelects: false,
54
+ moveCursorOnAltClick: true,
55
+ contextMenuSelectsWord: false,
56
+ mouseReportNeedsAlt: false,
57
+ wordSeparators: ' ()[]{}\',"`',
58
+ scrollFactor: 1,
59
+ fastScrollKey: 'alt',
60
+ fastScrollFactor: 5,
61
+ smoothScrollTime: 0,
62
+ followInput: true,
63
+ eraseScrollsIntoHistory: false,
64
+ rewrapCursorLine: false,
65
+ tabWidth: 8,
66
+ scrollbar: {},
67
+ extensions: {},
68
+ windowOps: {},
69
+ windowsPty: null,
70
+ hyperlinkHandler: null,
71
+ strings: DEFAULT_TERMINAL_STRINGS,
72
+ logLevel: 'info',
73
+ logger: null,
74
+ targetDocument: null,
75
+ };
76
+ /** Inatividade depois da qual o cursor para de piscar. */
77
+ const BLINK_IDLE_MS = 5 * 60 * 1000;
78
+ const THEME_ANSI = [
79
+ 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white',
80
+ 'brightBlack', 'brightRed', 'brightGreen', 'brightYellow', 'brightBlue', 'brightMagenta', 'brightCyan', 'brightWhite',
81
+ ];
82
+ const isMac = () => typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
83
+ class Decoration {
84
+ config;
85
+ element;
86
+ isDisposed = false;
87
+ renderEmitter = new Emitter();
88
+ disposeEmitter = new Emitter();
89
+ onRender = this.renderEmitter.event;
90
+ onDispose = this.disposeEmitter.event;
91
+ constructor(config) {
92
+ this.config = config;
93
+ }
94
+ get marker() {
95
+ return this.config.marker;
96
+ }
97
+ fireRender(el) {
98
+ this.renderEmitter.fire(el);
99
+ }
100
+ dispose() {
101
+ if (this.isDisposed)
102
+ return;
103
+ this.isDisposed = true;
104
+ this.element?.remove();
105
+ this.element = undefined;
106
+ this.disposeEmitter.fire();
107
+ this.renderEmitter.dispose();
108
+ this.disposeEmitter.dispose();
109
+ }
110
+ }
111
+ /** Separa as opções em configurações e recursos. */
112
+ function splitOptions(options) {
113
+ const settings = {};
114
+ const features = {};
115
+ for (const [key, value] of Object.entries(options)) {
116
+ if (value === undefined)
117
+ continue;
118
+ if (FEATURE_KEYS.includes(key))
119
+ features[key] = value;
120
+ else
121
+ settings[key] = value;
122
+ }
123
+ return { settings: settings, features: features };
124
+ }
125
+ export class TerminalEngine {
126
+ /** O elemento do terminal, depois de montado. */
127
+ element;
128
+ /** A área de texto escondida que recebe o foco e o teclado (IME incluído). */
129
+ inputElement;
130
+ core;
131
+ store = new DisposableStore();
132
+ resolved;
133
+ renderer;
134
+ viewport;
135
+ scrollArea;
136
+ a11yTree;
137
+ liveRegion;
138
+ liveText = '';
139
+ liveTimer;
140
+ keyFilter = null;
141
+ wheelFilter = null;
142
+ linkSources = [];
143
+ decorations = [];
144
+ hoveredLink;
145
+ linkRequest = 0;
146
+ selecting;
147
+ mouseButton = -1;
148
+ lastMouseCell = '';
149
+ composing = false;
150
+ keyHandled = false;
151
+ disposed = false;
152
+ mounted = false;
153
+ // Recursos ligados por opção.
154
+ featureOptions = { search: true };
155
+ features = new Map();
156
+ /** Versão do pedido de cada recurso: um carregamento sob demanda que chega depois de outro pedido é descartado. */
157
+ featureTokens = new Map();
158
+ fitter = new FitFeature(false);
159
+ serializer = new Serializer();
160
+ loading = 0;
161
+ loads = [];
162
+ /** O que foi escrito enquanto um recurso sob demanda carregava (sai na ordem, depois). */
163
+ queued = [];
164
+ keyEmitter = new Emitter();
165
+ renderEmitter = new Emitter();
166
+ scrollEmitter = new Emitter();
167
+ selectionEmitter = new Emitter();
168
+ screenEmitter = new Emitter();
169
+ metricsEmitter = new Emitter();
170
+ searchEmitter = new Emitter();
171
+ progressEmitter = new Emitter();
172
+ programStatusEmitter = new Emitter();
173
+ nextJoinerId = 1;
174
+ joiners = new Map();
175
+ blinkTimer;
176
+ smoothTarget = null;
177
+ smoothFrame = 0;
178
+ overviewRuler;
179
+ announcedLines = 0;
180
+ announceWindow = 0;
181
+ onKey = this.keyEmitter.event;
182
+ onRender = this.renderEmitter.event;
183
+ onScroll = this.scrollEmitter.event;
184
+ onSelection = this.selectionEmitter.event;
185
+ onScreenChange = this.screenEmitter.event;
186
+ onMetrics = this.metricsEmitter.event;
187
+ onProgress = this.progressEmitter.event;
188
+ onProgramStatus = this.programStatusEmitter.event;
189
+ screens;
190
+ selection;
191
+ search;
192
+ sequences;
193
+ unicode;
194
+ programStatus;
195
+ constructor(options = {}) {
196
+ const { settings, features } = splitOptions(options);
197
+ this.resolved = {
198
+ ...DEFAULT_TERMINAL_OPTIONS,
199
+ ...settings,
200
+ theme: { ...(settings.theme ?? {}) },
201
+ strings: { ...DEFAULT_TERMINAL_STRINGS, ...(settings.strings ?? {}) },
202
+ };
203
+ this.featureOptions = { ...this.featureOptions, ...features };
204
+ const o = this.resolved;
205
+ this.core = new TerminalCore({
206
+ cols: o.cols,
207
+ rows: o.rows,
208
+ scrollback: o.scrollback,
209
+ tabWidth: o.tabWidth,
210
+ lineFeedAsNewline: o.lineFeedAsNewline,
211
+ eraseScrollsIntoHistory: o.eraseScrollsIntoHistory,
212
+ cursorShape: o.cursorShape,
213
+ cursorBlink: o.cursorBlink,
214
+ readOnly: o.readOnly,
215
+ cursorBlinkMode: !!o.extensions.cursorBlinkMode,
216
+ rewrapCursorLine: o.rewrapCursorLine,
217
+ windowsPty: o.windowsPty ? { ...o.windowsPty } : null,
218
+ extensions: { ...o.extensions },
219
+ windowOps: { ...o.windowOps },
220
+ logLevel: o.logLevel,
221
+ logger: o.logger,
222
+ });
223
+ this.applyTheme();
224
+ const core = this.core;
225
+ this.screens = { normal: new ScreenView(() => core.normal), alternate: new ScreenView(() => core.alt) };
226
+ this.selection = {
227
+ get active() {
228
+ return core.hasSelection();
229
+ },
230
+ text: () => core.getSelection(),
231
+ range: () => {
232
+ const s = core.selection;
233
+ return s ? { start: { col: s.start.x, row: s.start.y }, end: { col: s.end.x, row: s.end.y } } : undefined;
234
+ },
235
+ select: (col, row, length) => core.select(col, row, length),
236
+ selectLines: (first, last) => core.selectLines(first, last),
237
+ selectAll: () => core.selectAll(),
238
+ clear: () => core.clearSelection(),
239
+ };
240
+ this.search = {
241
+ next: (query, opts) => this.searchFeature?.findNext(query, opts) ?? false,
242
+ previous: (query, opts) => this.searchFeature?.findPrevious(query, opts) ?? false,
243
+ clear: (keepActive) => this.searchFeature?.clearDecorations(keepActive),
244
+ onResults: this.searchEmitter.event,
245
+ };
246
+ this.sequences = {
247
+ csi: (id, handler) => core.parser.addCsiHandler(id, handler),
248
+ esc: (id, handler) => core.parser.addEscHandler(id, handler),
249
+ osc: (code, handler) => core.parser.addOscHandler(code, handler),
250
+ dcs: (id, handler) => core.parser.addDcsHandler(id, handler),
251
+ apc: (id, handler) => core.parser.addApcHandler(id, handler),
252
+ };
253
+ const unicode = core.unicode;
254
+ this.unicode = {
255
+ register: (provider) => unicode.register(provider),
256
+ get versions() {
257
+ return unicode.versions;
258
+ },
259
+ get active() {
260
+ return unicode.activeVersion;
261
+ },
262
+ set active(version) {
263
+ unicode.activeVersion = version;
264
+ },
265
+ };
266
+ const status = () => this.features.get('programStatus');
267
+ this.programStatus = {
268
+ get records() {
269
+ return status()?.records ?? [];
270
+ },
271
+ clear: (id) => status()?.clear(id),
272
+ processExited: () => status()?.processExited(),
273
+ promptStarted: () => status()?.promptStarted(),
274
+ };
275
+ this.store.add(core.onDirty(({ start, end }) => this.renderer?.refreshRows(start, end)));
276
+ this.store.add(core.onScroll((ydisp) => {
277
+ this.syncScrollArea();
278
+ this.scrollEmitter.fire(ydisp);
279
+ }));
280
+ this.store.add(core.onCursor(() => {
281
+ this.renderer?.refreshRows(this.core.buffer.y, this.core.buffer.y);
282
+ this.wakeBlink();
283
+ }));
284
+ this.store.add(core.onSelection(() => {
285
+ this.renderer?.refreshRows(0, -1);
286
+ this.selectionEmitter.fire();
287
+ }));
288
+ this.store.add(core.onScreenChange(() => {
289
+ this.syncScrollArea();
290
+ this.screenEmitter.fire(this.screen);
291
+ }));
292
+ this.store.add(core.onResize(() => {
293
+ this.renderer?.layout();
294
+ this.syncScrollArea();
295
+ }));
296
+ this.store.add(core.onCursorShapeChange(() => this.renderer?.refreshAll()));
297
+ this.store.add(core.onColorsChange(() => {
298
+ this.applyBackground();
299
+ this.renderer?.refreshAll();
300
+ this.renderOverviewRuler();
301
+ }));
302
+ this.store.add(core.onParsed(() => this.announce()));
303
+ }
304
+ // ---------------------------------------------------------------- propriedades
305
+ get cols() {
306
+ return this.core.cols;
307
+ }
308
+ get rows() {
309
+ return this.core.rows;
310
+ }
311
+ get title() {
312
+ return this.core.title;
313
+ }
314
+ get settings() {
315
+ return this.resolved;
316
+ }
317
+ get screen() {
318
+ return this.core.buffer === this.core.normal ? this.screens.normal : this.screens.alternate;
319
+ }
320
+ get modes() {
321
+ const m = this.core.modes;
322
+ return {
323
+ applicationCursorKeys: m.applicationCursorKeysMode,
324
+ applicationKeypad: m.applicationKeypadMode,
325
+ bracketedPaste: m.bracketedPasteMode,
326
+ insert: m.insertMode,
327
+ mouseTracking: m.mouseTrackingMode,
328
+ origin: m.originMode,
329
+ reverseWraparound: m.reverseWraparoundMode,
330
+ focusReports: m.sendFocusMode,
331
+ cursorVisible: m.showCursor,
332
+ synchronizedOutput: m.synchronizedOutputMode,
333
+ autoWrap: m.wraparoundMode,
334
+ };
335
+ }
336
+ /** O elemento das camadas de desenho (linhas, cursor, seleção, decorações), sem o viewport nem a barra. */
337
+ get screenElement() {
338
+ return this.renderer.screen;
339
+ }
340
+ /** Medidas da tela e da célula; `undefined` antes de montar e medir. */
341
+ get metrics() {
342
+ const r = this.renderer;
343
+ if (!r || !r.cellWidth)
344
+ return undefined;
345
+ return {
346
+ cell: { width: r.cellWidth, height: r.cellHeight },
347
+ screen: { width: r.cellWidth * this.cols, height: r.cellHeight * this.rows },
348
+ devicePixelRatio: this.element?.ownerDocument.defaultView?.devicePixelRatio || 1,
349
+ };
350
+ }
351
+ get markers() {
352
+ return this.core.markers;
353
+ }
354
+ /** Medidas da célula em px (zero antes de medir). */
355
+ get cellSize() {
356
+ return { width: this.renderer?.cellWidth ?? 0, height: this.renderer?.cellHeight ?? 0 };
357
+ }
358
+ get progress() {
359
+ return this.features.get('progress')?.progress ?? { state: 0, value: 0 };
360
+ }
361
+ get ready() {
362
+ return Promise.all(this.loads).then(() => undefined);
363
+ }
364
+ get searchFeature() {
365
+ return this.features.get('search');
366
+ }
367
+ addJoiner(joiner) {
368
+ const id = this.nextJoinerId++;
369
+ this.joiners.set(id, joiner);
370
+ this.renderer?.joiners.set(id, joiner);
371
+ this.renderer?.refreshAll();
372
+ return () => {
373
+ this.joiners.delete(id);
374
+ if (this.renderer?.joiners.delete(id))
375
+ this.renderer.refreshAll();
376
+ };
377
+ }
378
+ onInput(listener) {
379
+ return this.core.onInput(listener);
380
+ }
381
+ onBinaryInput(listener) {
382
+ return this.core.onBinaryInput(listener);
383
+ }
384
+ onBell(listener) {
385
+ return this.core.onBell(listener);
386
+ }
387
+ onTitle(listener) {
388
+ return this.core.onTitle(listener);
389
+ }
390
+ onLineFeed(listener) {
391
+ return this.core.onLineFeed(listener);
392
+ }
393
+ onCursor(listener) {
394
+ return this.core.onCursor(listener);
395
+ }
396
+ onResize(listener) {
397
+ return this.core.onResize(listener);
398
+ }
399
+ onParsed(listener) {
400
+ return this.core.onParsed(listener);
401
+ }
402
+ // ---------------------------------------------------------------- opções e tema
403
+ configure(options) {
404
+ const { settings, features } = splitOptions(options);
405
+ const o = this.resolved;
406
+ for (const [key, value] of Object.entries(settings)) {
407
+ o[key] = key === 'theme' ? { ...value } : key === 'strings' ? { ...DEFAULT_TERMINAL_STRINGS, ...value } : value;
408
+ this.applyOption(key);
409
+ }
410
+ for (const [key, value] of Object.entries(features)) {
411
+ if (sameValue(this.featureOptions[key], value))
412
+ continue;
413
+ this.featureOptions[key] = value;
414
+ if (this.mounted)
415
+ this.setFeature(key);
416
+ }
417
+ }
418
+ applyOption(key) {
419
+ const o = this.resolved;
420
+ const core = this.core;
421
+ switch (key) {
422
+ case 'scrollback':
423
+ core.setScrollback(o.scrollback);
424
+ this.syncScrollArea();
425
+ break;
426
+ case 'tabWidth':
427
+ case 'lineFeedAsNewline':
428
+ case 'eraseScrollsIntoHistory':
429
+ case 'readOnly':
430
+ case 'rewrapCursorLine':
431
+ case 'logLevel':
432
+ case 'logger':
433
+ core.options[key] = o[key];
434
+ break;
435
+ case 'cursorShape':
436
+ case 'cursorBlink':
437
+ core.options[key] = o[key];
438
+ core.modes.cursorBlinkOverride = null;
439
+ this.renderer?.refreshAll();
440
+ break;
441
+ case 'theme':
442
+ this.applyTheme();
443
+ break;
444
+ case 'screenReader':
445
+ this.setupA11y();
446
+ break;
447
+ case 'cols':
448
+ case 'rows':
449
+ this.resize(o.cols, o.rows);
450
+ break;
451
+ case 'windowsPty':
452
+ core.options.windowsPty = o.windowsPty ? { ...o.windowsPty } : null;
453
+ break;
454
+ case 'extensions':
455
+ core.options.extensions = { ...o.extensions };
456
+ core.options.cursorBlinkMode = !!o.extensions.cursorBlinkMode;
457
+ if (!core.options.cursorBlinkMode)
458
+ core.modes.cursorBlinkOverride = null;
459
+ break;
460
+ case 'windowOps':
461
+ core.options.windowOps = { ...o.windowOps };
462
+ break;
463
+ case 'scrollbar':
464
+ this.applyScrollbar();
465
+ break;
466
+ case 'strings':
467
+ this.inputElement?.setAttribute('aria-label', o.strings.promptLabel);
468
+ break;
469
+ }
470
+ this.renderer?.setOptions(this.renderOptions());
471
+ this.syncScrollArea();
472
+ }
473
+ applyTheme() {
474
+ const theme = this.resolved.theme ?? {};
475
+ const ansi = THEME_ANSI.map((name, i) => cssOr(theme[name], ANSI_DEFAULTS[i]));
476
+ const palette = defaultPalette(ansi);
477
+ theme.extended?.forEach((css, i) => {
478
+ if (16 + i < 256)
479
+ palette[16 + i] = cssOr(css, palette[16 + i]);
480
+ });
481
+ const foreground = cssOr(theme.foreground, DEFAULT_FOREGROUND);
482
+ const background = cssOr(theme.background, DEFAULT_BACKGROUND);
483
+ this.core.colors.setBase(palette, foreground, background, cssOr(theme.cursor, foreground));
484
+ this.core.notifyColorScheme();
485
+ this.applyBackground();
486
+ this.renderer?.setOptions(this.renderOptions());
487
+ }
488
+ applyBackground() {
489
+ if (!this.element)
490
+ return;
491
+ const { foreground, background } = this.core.colors;
492
+ const hex = (v) => `#${v.toString(16).padStart(6, '0')}`;
493
+ this.element.style.setProperty('--hmt-foreground', hex(foreground));
494
+ this.element.style.setProperty('--hmt-background', this.resolved.transparentBackground && this.resolved.theme.background === 'transparent' ? 'transparent' : hex(background));
495
+ const t = this.resolved.theme;
496
+ if (t.scrollbarThumb)
497
+ this.element.style.setProperty('--hmt-scrollbar', t.scrollbarThumb);
498
+ }
499
+ renderOptions() {
500
+ const o = this.resolved;
501
+ const t = o.theme;
502
+ return {
503
+ fontFamily: o.fontFamily,
504
+ fontSize: o.fontSize,
505
+ fontWeight: o.fontWeight,
506
+ boldFontWeight: o.boldFontWeight,
507
+ lineHeight: o.lineHeight,
508
+ letterSpacing: o.letterSpacing,
509
+ cursorShape: o.cursorShape,
510
+ cursorUnfocusedShape: o.cursorUnfocusedShape,
511
+ cursorBarWidth: o.cursorBarWidth,
512
+ cursorBlink: o.cursorBlink,
513
+ boldAsBright: o.boldAsBright,
514
+ builtinBoxGlyphs: o.builtinBoxGlyphs,
515
+ textBlinkInterval: o.textBlinkInterval,
516
+ minimumContrast: o.minimumContrast,
517
+ squeezeWideGlyphs: o.squeezeWideGlyphs,
518
+ selectionBackground: t.selectionBackground ?? 'rgba(255, 255, 255, 0.3)',
519
+ selectionForeground: t.selectionForeground,
520
+ selectionUnfocusedBackground: t.selectionUnfocusedBackground ?? t.selectionBackground ?? 'rgba(255, 255, 255, 0.2)',
521
+ cursorText: t.cursorText,
522
+ };
523
+ }
524
+ // ---------------------------------------------------------------- recursos
525
+ /** Liga, troca ou desliga o recurso conforme a opção atual. */
526
+ setFeature(key) {
527
+ const token = (this.featureTokens.get(key) ?? 0) + 1;
528
+ this.featureTokens.set(key, token);
529
+ this.features.get(key)?.dispose();
530
+ this.features.delete(key);
531
+ const value = this.featureOptions[key];
532
+ if (!value)
533
+ return;
534
+ const opts = (v) => (typeof v === 'object' && v ? v : {});
535
+ switch (key) {
536
+ case 'fit':
537
+ return this.attachFeature(key, new FitFeature(true));
538
+ case 'links':
539
+ return this.attachFeature(key, new LinksFeature(opts(value)));
540
+ case 'search': {
541
+ const feature = new SearchFeature(opts(value));
542
+ feature.onResults((results) => this.searchEmitter.fire(results));
543
+ return this.attachFeature(key, feature);
544
+ }
545
+ case 'clipboard': {
546
+ const { codec, provider } = opts(value);
547
+ return this.attachFeature(key, new ClipboardFeature(codec, provider));
548
+ }
549
+ case 'unicode':
550
+ if (value === '11')
551
+ return this.attachFeature(key, new Unicode11Feature());
552
+ if (value === 'graphemes')
553
+ return this.attachFeature(key, new UnicodeGraphemesFeature());
554
+ this.core.unicode.activeVersion = String(value);
555
+ return;
556
+ case 'ligatures':
557
+ return this.attachFeature(key, new LigaturesFeature(opts(value)));
558
+ case 'progress': {
559
+ const feature = new ProgressFeature();
560
+ feature.onChange((state) => this.progressEmitter.fire(state));
561
+ return this.attachFeature(key, feature);
562
+ }
563
+ case 'programStatus': {
564
+ const feature = new ProgramStatusFeature();
565
+ feature.onChange((records) => this.programStatusEmitter.fire(records));
566
+ return this.attachFeature(key, feature);
567
+ }
568
+ case 'webFonts':
569
+ return this.attachFeature(key, new WebFontsFeature());
570
+ case 'images':
571
+ return this.loadFeature(key, token, () => import('../features/image/index').then((m) => new m.ImageFeature(opts(value))));
572
+ case 'gpu':
573
+ return this.loadFeature(key, token, () => import('../features/gpu/index').then((m) => new m.GpuFeature(opts(value))));
574
+ }
575
+ }
576
+ /** Liga o recurso; se ele recusar (sem WebGL, por exemplo), avisa no registro e o terminal segue sem ele. */
577
+ attachFeature(key, feature) {
578
+ try {
579
+ feature.attach(this);
580
+ this.features.set(key, feature);
581
+ }
582
+ catch (error) {
583
+ feature.dispose();
584
+ this.core.log('warn', `recurso ${key} desligado: ${error instanceof Error ? error.message : String(error)}`, error);
585
+ }
586
+ }
587
+ /** Recurso pesado, em chunk próprio: a escrita espera ele entrar para nenhuma sequência passar sem ele. */
588
+ loadFeature(key, token, load) {
589
+ this.loading++;
590
+ const done = load()
591
+ .then((feature) => {
592
+ if (this.disposed || this.featureTokens.get(key) !== token)
593
+ return;
594
+ this.attachFeature(key, feature);
595
+ })
596
+ .catch((error) => this.core.log('error', 'não foi possível carregar um recurso do terminal', key, error))
597
+ .finally(() => {
598
+ this.loading--;
599
+ if (!this.loading)
600
+ for (const item of this.queued.splice(0))
601
+ this.core.write(item.data, item.done);
602
+ });
603
+ this.loads.push(done);
604
+ }
605
+ // ---------------------------------------------------------------- montar na página
606
+ /** Monta no host (o `createTerminal` chama) e liga os recursos pedidos. */
607
+ mount(parent) {
608
+ if (this.mounted)
609
+ throw new Error('[hermes-terminal] O terminal já está montado.');
610
+ this.mounted = true;
611
+ const doc = this.resolved.targetDocument ?? parent.ownerDocument;
612
+ ensureStyles(doc);
613
+ const el = doc.createElement('div');
614
+ el.className = 'hmt';
615
+ el.dir = 'ltr';
616
+ this.element = el;
617
+ const viewport = doc.createElement('div');
618
+ viewport.className = 'hmt-viewport';
619
+ const scrollArea = doc.createElement('div');
620
+ scrollArea.className = 'hmt-scroll-area';
621
+ viewport.appendChild(scrollArea);
622
+ el.appendChild(viewport);
623
+ this.viewport = viewport;
624
+ this.scrollArea = scrollArea;
625
+ this.renderer = new DomRenderer(this.core, el, this.renderOptions());
626
+ this.renderer.onOverlays = () => {
627
+ this.renderDecorations();
628
+ this.renderOverviewRuler();
629
+ };
630
+ this.renderer.onMeasured = () => {
631
+ const r = this.renderer;
632
+ this.core.pixelMetrics = { cellWidth: r.cellWidth, cellHeight: r.cellHeight };
633
+ const metrics = this.metrics;
634
+ if (metrics)
635
+ this.metricsEmitter.fire(metrics);
636
+ };
637
+ for (const [id, joiner] of this.joiners)
638
+ this.renderer.joiners.set(id, joiner);
639
+ this.renderer.onRendered = (start, end) => {
640
+ this.updateA11yRows(start, end);
641
+ this.renderEmitter.fire({ start, end });
642
+ };
643
+ const textarea = doc.createElement('textarea');
644
+ textarea.className = 'hmt-helper-textarea';
645
+ textarea.setAttribute('autocorrect', 'off');
646
+ textarea.setAttribute('autocapitalize', 'off');
647
+ textarea.setAttribute('spellcheck', 'false');
648
+ textarea.setAttribute('tabindex', '0');
649
+ textarea.setAttribute('aria-label', this.resolved.strings.promptLabel);
650
+ textarea.setAttribute('aria-multiline', 'false');
651
+ el.appendChild(textarea);
652
+ this.inputElement = textarea;
653
+ parent.appendChild(el);
654
+ this.applyBackground();
655
+ this.renderer.measureCell();
656
+ this.setupA11y();
657
+ this.applyScrollbar();
658
+ this.bindEvents();
659
+ this.wakeBlink();
660
+ this.syncScrollArea();
661
+ this.renderer.refreshAll();
662
+ this.fitter.attach(this);
663
+ for (const key of FEATURE_KEYS)
664
+ if (this.featureOptions[key])
665
+ this.setFeature(key);
666
+ }
667
+ bindEvents() {
668
+ const el = this.element;
669
+ const ta = this.inputElement;
670
+ const screen = this.renderer.screen;
671
+ const on = (target, type, fn, opts) => {
672
+ target.addEventListener(type, fn, opts);
673
+ this.store.add(() => target.removeEventListener(type, fn, opts));
674
+ };
675
+ on(ta, 'keydown', (e) => this.handleKeyDown(e));
676
+ on(ta, 'keyup', (e) => this.handleKeyUp(e));
677
+ on(el, 'mousedown', () => this.wakeBlink());
678
+ on(ta, 'input', (e) => this.handleInput(e));
679
+ on(ta, 'compositionstart', () => (this.composing = true));
680
+ on(ta, 'compositionend', (e) => {
681
+ this.composing = false;
682
+ const data = e.data;
683
+ if (data)
684
+ this.sendUserInput(data);
685
+ ta.value = '';
686
+ });
687
+ on(ta, 'paste', (e) => {
688
+ const text = e.clipboardData?.getData('text/plain');
689
+ e.preventDefault();
690
+ if (text)
691
+ this.paste(text);
692
+ });
693
+ on(ta, 'copy', (e) => this.handleCopy(e));
694
+ on(el, 'copy', (e) => this.handleCopy(e));
695
+ on(ta, 'focus', () => this.setFocused(true));
696
+ on(ta, 'blur', () => this.setFocused(false));
697
+ on(screen, 'mousedown', (e) => this.handleMouseDown(e));
698
+ on(screen, 'mousemove', (e) => this.handleHover(e));
699
+ on(screen, 'mouseleave', (e) => this.clearHoveredLink(e));
700
+ on(screen, 'contextmenu', (e) => {
701
+ if (this.resolved.contextMenuSelectsWord)
702
+ this.selectWordAt(e);
703
+ this.inputElement?.focus();
704
+ });
705
+ on(el, 'wheel', (e) => this.handleWheel(e), { passive: false });
706
+ on(this.viewport, 'scroll', () => {
707
+ if (!this.renderer?.cellHeight)
708
+ return;
709
+ const b = this.core.buffer;
710
+ const vp = this.viewport;
711
+ // No fim da rolagem, a vista cola no fundo (acompanha a saída nova), seja qual for o arredondamento.
712
+ const atEnd = vp.scrollTop + vp.clientHeight >= vp.scrollHeight - 1;
713
+ const target = atEnd ? b.ybase : Math.max(0, Math.min(b.ybase, Math.round(vp.scrollTop / this.renderer.cellHeight)));
714
+ if (target !== b.ydisp) {
715
+ b.ydisp = target;
716
+ this.renderer.refreshAll();
717
+ this.scrollEmitter.fire(target);
718
+ }
719
+ });
720
+ }
721
+ setFocused(focused) {
722
+ if (!this.renderer)
723
+ return;
724
+ this.renderer.focused = focused;
725
+ this.element?.classList.toggle('hmt-focus', focused);
726
+ if (this.core.modes.sendFocusMode)
727
+ this.core.emitInput(focused ? '\x1b[I' : '\x1b[O', false);
728
+ this.renderer.refreshAll();
729
+ }
730
+ focus() {
731
+ this.inputElement?.focus();
732
+ }
733
+ blur() {
734
+ this.inputElement?.blur();
735
+ }
736
+ // ---------------------------------------------------------------- teclado
737
+ setKeyFilter(handler) {
738
+ this.keyFilter = handler;
739
+ }
740
+ setWheelFilter(handler) {
741
+ this.wheelFilter = handler;
742
+ }
743
+ handleKeyDown(e) {
744
+ this.keyHandled = false;
745
+ if (this.keyFilter && this.keyFilter(e) === false)
746
+ return;
747
+ if (this.composing || e.isComposing || e.key === 'Process' || e.keyCode === 229)
748
+ return;
749
+ this.wakeBlink();
750
+ // Protocolos estendidos pedidos pelo processo: win32-input-mode e o teclado progressivo (CSI u).
751
+ const extended = this.extendedKey(e, 'keydown');
752
+ if (extended !== null) {
753
+ e.preventDefault();
754
+ this.keyHandled = true;
755
+ if (extended) {
756
+ this.keyEmitter.fire({ data: extended, event: e });
757
+ this.sendUserInput(extended);
758
+ }
759
+ return;
760
+ }
761
+ const result = encodeKey(e, {
762
+ applicationCursorKeys: this.core.modes.applicationCursorKeysMode,
763
+ applicationKeypad: this.core.modes.applicationKeypadMode,
764
+ optionAsMeta: this.resolved.optionAsMeta,
765
+ isMac: isMac(),
766
+ });
767
+ // Shift+PageUp/PageDown/Home/End rolam a vista, não vão para o processo.
768
+ if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey && this.core.buffer === this.core.normal) {
769
+ const page = this.rows - 1;
770
+ const scroll = { PageUp: -page, PageDown: page }[e.key];
771
+ if (scroll) {
772
+ this.scrollBy(scroll);
773
+ e.preventDefault();
774
+ return;
775
+ }
776
+ }
777
+ if (!result.data)
778
+ return;
779
+ this.keyHandled = true;
780
+ if (result.cancel || result.data.length === 1)
781
+ e.preventDefault();
782
+ this.keyEmitter.fire({ data: result.data, event: e });
783
+ this.sendUserInput(result.data);
784
+ }
785
+ handleKeyUp(e) {
786
+ if (this.keyFilter && this.keyFilter(e) === false)
787
+ return;
788
+ const extended = this.extendedKey(e, 'keyup');
789
+ if (extended) {
790
+ e.preventDefault();
791
+ this.sendUserInput(extended, false);
792
+ }
793
+ }
794
+ /** Codificação nos protocolos estendidos; `null` = segue o teclado legado, `''` = engole a tecla. */
795
+ extendedKey(e, type) {
796
+ const input = {
797
+ key: e.key,
798
+ ctrlKey: e.ctrlKey,
799
+ altKey: e.altKey,
800
+ shiftKey: e.shiftKey,
801
+ metaKey: e.metaKey,
802
+ type,
803
+ repeat: e.repeat,
804
+ code: e.code,
805
+ keyCode: e.keyCode,
806
+ location: e.location,
807
+ capsLock: e.getModifierState?.('CapsLock') ?? false,
808
+ numLock: e.getModifierState?.('NumLock') ?? false,
809
+ };
810
+ if (this.core.modes.win32InputMode)
811
+ return encodeWin32Key(input);
812
+ const flags = this.core.progressiveKeyFlags;
813
+ if (flags)
814
+ return encodeProgressiveKey(input, flags);
815
+ return null;
816
+ }
817
+ /** Texto que chega sem `keydown` útil (teclado virtual, ditado): vai como digitado. */
818
+ handleInput(e) {
819
+ const ta = this.inputElement;
820
+ if (this.composing || e.isComposing)
821
+ return;
822
+ if (!this.keyHandled && e.inputType === 'insertText' && e.data)
823
+ this.sendUserInput(e.data);
824
+ this.keyHandled = false;
825
+ ta.value = '';
826
+ }
827
+ sendUserInput(data, clearSelection = true) {
828
+ if (this.resolved.readOnly)
829
+ return;
830
+ if (this.resolved.followInput)
831
+ this.scrollToBottom();
832
+ if (clearSelection)
833
+ this.core.clearSelection();
834
+ this.core.emitInput(data, true);
835
+ }
836
+ handleCopy(e) {
837
+ if (!this.core.hasSelection())
838
+ return;
839
+ e.clipboardData?.setData("text/plain", this.core.getSelection());
840
+ e.preventDefault();
841
+ }
842
+ /** Manda dados como se a pessoa tivesse digitado (`asUser` false: não rola nem limpa a seleção). */
843
+ send(data, asUser = true) {
844
+ if (asUser)
845
+ this.sendUserInput(data);
846
+ else
847
+ this.core.emitInput(data, false);
848
+ }
849
+ paste(data) {
850
+ const bracketed = this.core.modes.bracketedPasteMode && !this.resolved.plainPaste;
851
+ this.sendUserInput(encodePaste(data, bracketed));
852
+ }
853
+ // ---------------------------------------------------------------- mouse
854
+ mouseReportingActive(e, wheel = false) {
855
+ if (this.core.modes.mouseTrackingMode === 'none')
856
+ return false;
857
+ // `mouseReportNeedsAlt`: cliques e movimento só vão para o processo com Alt (a roda não muda).
858
+ if (this.resolved.mouseReportNeedsAlt && !wheel)
859
+ return e.altKey;
860
+ // Shift (ou Option no macOS, se ligado) força a seleção mesmo com o processo pedindo o mouse.
861
+ if (e.shiftKey)
862
+ return false;
863
+ if (isMac() && e.altKey && this.resolved.optionClickSelects)
864
+ return false;
865
+ return true;
866
+ }
867
+ reportMouse(e, button, action) {
868
+ const { col, row } = this.renderer.cellAt(e.clientX, e.clientY);
869
+ const mode = this.core.modes.mouseTrackingMode;
870
+ if (mode === 'x10' && action !== 'press')
871
+ return;
872
+ if (action === 'move') {
873
+ if (mode !== 'drag' && mode !== 'any')
874
+ return;
875
+ if (mode === 'drag' && this.mouseButton < 0)
876
+ return;
877
+ const key = `${col},${row}`;
878
+ if (key === this.lastMouseCell)
879
+ return;
880
+ this.lastMouseCell = key;
881
+ }
882
+ const rect = this.renderer.screen.getBoundingClientRect();
883
+ const encoding = this.core.modes.mouseEncoding;
884
+ const data = encodeMouse({
885
+ button: action === 'move' && button < 0 ? 3 : button,
886
+ action,
887
+ col: col + 1,
888
+ row: row + 1,
889
+ shift: e.shiftKey,
890
+ // Com `mouseReportNeedsAlt`, o Alt é o gesto de liberar o mouse, não um modificador do relatório.
891
+ alt: e.altKey && !this.resolved.mouseReportNeedsAlt,
892
+ ctrl: e.ctrlKey,
893
+ px: Math.max(1, Math.round(e.clientX - rect.left) + 1),
894
+ py: Math.max(1, Math.round(e.clientY - rect.top) + 1),
895
+ }, encoding);
896
+ // No formato clássico, coordenadas acima de 223 viram bytes que não são UTF-8: vão como binário.
897
+ if (encoding === 'default' && (col + 1 > 223 || row + 1 > 223))
898
+ this.core.emitBinaryInput(data);
899
+ else
900
+ this.core.emitInput(data, true);
901
+ }
902
+ handleMouseDown(e) {
903
+ const doc = this.element.ownerDocument;
904
+ this.inputElement?.focus({ preventScroll: true });
905
+ if (this.mouseReportingActive(e)) {
906
+ const button = e.button === 1 ? 1 : e.button === 2 ? 2 : 0;
907
+ this.mouseButton = button;
908
+ this.reportMouse(e, button, 'press');
909
+ e.preventDefault();
910
+ const move = (ev) => this.reportMouse(ev, this.mouseButton, 'move');
911
+ const up = (ev) => {
912
+ this.reportMouse(ev, this.mouseButton, 'release');
913
+ this.mouseButton = -1;
914
+ doc.removeEventListener('mousemove', move);
915
+ doc.removeEventListener('mouseup', up);
916
+ };
917
+ doc.addEventListener('mousemove', move);
918
+ doc.addEventListener('mouseup', up);
919
+ return;
920
+ }
921
+ if (e.button !== 0)
922
+ return;
923
+ e.preventDefault();
924
+ const point = this.bufferPoint(e, true);
925
+ const mode = e.detail >= 3 ? 'line' : e.detail === 2 ? 'word' : 'char';
926
+ if (mode === 'char' && e.shiftKey && this.core.selection) {
927
+ this.selecting = { anchor: { ...this.core.selection.start }, mode, moved: true };
928
+ this.extendSelection(point);
929
+ }
930
+ else {
931
+ this.selecting = { anchor: point, mode, moved: false };
932
+ if (mode === 'char')
933
+ this.core.clearSelection();
934
+ else
935
+ this.extendSelection(point);
936
+ }
937
+ const move = (ev) => {
938
+ if (!this.selecting)
939
+ return;
940
+ this.selecting.moved = true;
941
+ const { row } = this.renderer.edgeAt(ev.clientX, ev.clientY);
942
+ if (row < 0)
943
+ this.scrollBy(-1);
944
+ else if (row >= this.rows)
945
+ this.scrollBy(1);
946
+ this.extendSelection(this.bufferPoint(ev, true));
947
+ };
948
+ const up = (ev) => {
949
+ const state = this.selecting;
950
+ this.selecting = undefined;
951
+ doc.removeEventListener('mousemove', move);
952
+ doc.removeEventListener('mouseup', up);
953
+ if (state && state.mode === 'char' && !state.moved) {
954
+ this.openLinkAt(ev);
955
+ if (ev.altKey && this.resolved.moveCursorOnAltClick)
956
+ this.moveCursorTo(ev);
957
+ }
958
+ };
959
+ doc.addEventListener('mousemove', move);
960
+ doc.addEventListener('mouseup', up);
961
+ }
962
+ /** Ponto do buffer (coluna/linha absoluta) sob o mouse. */
963
+ bufferPoint(e, edge) {
964
+ const r = this.renderer;
965
+ const { col, row } = edge ? r.edgeAt(e.clientX, e.clientY) : r.cellAt(e.clientX, e.clientY);
966
+ const b = this.core.buffer;
967
+ const y = Math.max(0, Math.min(b.lines.length - 1, b.ydisp + Math.max(0, Math.min(this.rows - 1, row))));
968
+ return { x: col, y };
969
+ }
970
+ extendSelection(point) {
971
+ const state = this.selecting;
972
+ const a = state.anchor;
973
+ if (state.mode === 'char') {
974
+ this.core.setSelection(a, point);
975
+ return;
976
+ }
977
+ const [first, last] = a.y < point.y || (a.y === point.y && a.x <= point.x) ? [a, point] : [point, a];
978
+ if (state.mode === 'line') {
979
+ this.core.setSelection({ x: 0, y: this.logicalStart(first.y) }, { x: this.cols, y: this.logicalEnd(last.y) });
980
+ return;
981
+ }
982
+ const start = this.wordBounds(first.x, first.y)[0];
983
+ const end = this.wordBounds(Math.max(0, last.x - (last === point && last !== a ? 1 : 0)), last.y)[1];
984
+ this.core.setSelection(start, end);
985
+ }
986
+ logicalStart(y) {
987
+ const lines = this.core.buffer.lines;
988
+ while (y > 0 && lines.get(y)?.isWrapped)
989
+ y--;
990
+ return y;
991
+ }
992
+ logicalEnd(y) {
993
+ const lines = this.core.buffer.lines;
994
+ while (y + 1 < lines.length && lines.get(y + 1)?.isWrapped)
995
+ y++;
996
+ return y;
997
+ }
998
+ /** Limites da palavra em `(x, y)`: de separador a separador, atravessando quebras automáticas. */
999
+ wordBounds(x, y) {
1000
+ const lines = this.core.buffer.lines;
1001
+ const cols = this.cols;
1002
+ const sep = this.resolved.wordSeparators;
1003
+ const charAt = (cx, cy) => {
1004
+ const line = lines.get(cy);
1005
+ if (!line)
1006
+ return ' ';
1007
+ const chars = line.getChars(cx);
1008
+ return line.getWidth(cx) === 0 ? 'wide' : chars || ' ';
1009
+ };
1010
+ const isWord = (cx, cy) => {
1011
+ const c = charAt(cx, cy);
1012
+ return c === 'wide' || !sep.includes(c);
1013
+ };
1014
+ if (!isWord(x, y))
1015
+ return [{ x, y }, { x: x + 1, y }];
1016
+ let sx = x;
1017
+ let sy = y;
1018
+ while (true) {
1019
+ if (sx > 0 && isWord(sx - 1, sy))
1020
+ sx--;
1021
+ else if (sx === 0 && sy > 0 && lines.get(sy)?.isWrapped && isWord(cols - 1, sy - 1)) {
1022
+ sy--;
1023
+ sx = cols - 1;
1024
+ }
1025
+ else
1026
+ break;
1027
+ }
1028
+ let ex = x;
1029
+ let ey = y;
1030
+ while (true) {
1031
+ if (ex < cols - 1 && isWord(ex + 1, ey))
1032
+ ex++;
1033
+ else if (ex === cols - 1 && lines.get(ey + 1)?.isWrapped && isWord(0, ey + 1)) {
1034
+ ey++;
1035
+ ex = 0;
1036
+ }
1037
+ else
1038
+ break;
1039
+ }
1040
+ if (lines.get(ey)?.getWidth(ex) === 2)
1041
+ ex++;
1042
+ return [{ x: sx, y: sy }, { x: ex + 1, y: ey }];
1043
+ }
1044
+ selectWordAt(e) {
1045
+ const point = this.bufferPoint(e, false);
1046
+ const [start, end] = this.wordBounds(point.x, point.y);
1047
+ this.core.setSelection(start, end);
1048
+ }
1049
+ /** Alt+clique: move o cursor do prompt até o ponto com setas. */
1050
+ moveCursorTo(e) {
1051
+ if (this.core.buffer !== this.core.normal)
1052
+ return;
1053
+ const target = this.bufferPoint(e, false);
1054
+ const b = this.core.buffer;
1055
+ const from = (b.ybase + b.y) * this.cols + b.x;
1056
+ const to = target.y * this.cols + target.x;
1057
+ const delta = to - from;
1058
+ if (!delta)
1059
+ return;
1060
+ const app = this.core.modes.applicationCursorKeysMode;
1061
+ const arrow = `\x1b${app ? 'O' : '['}${delta > 0 ? 'C' : 'D'}`;
1062
+ this.sendUserInput(arrow.repeat(Math.abs(delta)));
1063
+ }
1064
+ handleWheel(e) {
1065
+ if (this.wheelFilter && this.wheelFilter(e) === false)
1066
+ return;
1067
+ const cellHeight = this.renderer?.cellHeight || 16;
1068
+ const unit = e.deltaMode === 1 ? 1 : e.deltaMode === 2 ? this.rows : 1 / cellHeight;
1069
+ const fast = (this.resolved.fastScrollKey === 'alt' && e.altKey) ||
1070
+ (this.resolved.fastScrollKey === 'ctrl' && e.ctrlKey) ||
1071
+ (this.resolved.fastScrollKey === 'shift' && e.shiftKey);
1072
+ const sensitivity = fast ? this.resolved.fastScrollFactor : this.resolved.scrollFactor;
1073
+ const raw = e.deltaY * unit * sensitivity;
1074
+ const lines = raw > 0 ? Math.max(1, Math.round(raw)) : raw < 0 ? Math.min(-1, Math.round(raw)) : 0;
1075
+ if (!lines)
1076
+ return;
1077
+ if (this.mouseReportingActive(e, true) && this.core.modes.mouseTrackingMode !== 'x10') {
1078
+ for (let i = 0; i < Math.abs(lines); i++)
1079
+ this.reportMouse(e, lines < 0 ? 64 : 65, 'press');
1080
+ e.preventDefault();
1081
+ return;
1082
+ }
1083
+ // Tela alternativa sem mouse: a roda vira setas (o less e o vim rolam assim).
1084
+ if (this.core.buffer === this.core.alt) {
1085
+ const app = this.core.modes.applicationCursorKeysMode;
1086
+ this.core.emitInput(`\x1b${app ? 'O' : '['}${lines < 0 ? 'A' : 'B'}`.repeat(Math.abs(lines)), true);
1087
+ e.preventDefault();
1088
+ return;
1089
+ }
1090
+ const b = this.core.buffer;
1091
+ if ((lines < 0 && b.ydisp > 0) || (lines > 0 && b.ydisp < b.ybase))
1092
+ e.preventDefault();
1093
+ if (this.resolved.smoothScrollTime > 0)
1094
+ this.smoothScrollBy(lines);
1095
+ else
1096
+ this.scrollBy(lines);
1097
+ }
1098
+ /** Rolagem suave: anda até o alvo ao longo de `smoothScrollTime`, linha a linha (a grade é por linhas). */
1099
+ smoothScrollBy(lines) {
1100
+ const b = this.core.buffer;
1101
+ const start = b.ydisp;
1102
+ this.smoothTarget = Math.max(0, Math.min(b.ybase, (this.smoothTarget ?? start) + lines));
1103
+ const target = this.smoothTarget;
1104
+ const win = this.element?.ownerDocument.defaultView;
1105
+ if (!win?.requestAnimationFrame) {
1106
+ this.smoothTarget = null;
1107
+ this.scrollBy(target - start);
1108
+ return;
1109
+ }
1110
+ win.cancelAnimationFrame(this.smoothFrame);
1111
+ const duration = this.resolved.smoothScrollTime;
1112
+ const began = win.performance.now();
1113
+ const step = (now) => {
1114
+ const t = Math.min(1, (now - began) / duration);
1115
+ const eased = 1 - (1 - t) ** 3;
1116
+ const next = Math.round(start + (target - start) * eased);
1117
+ this.scrollBy(next - this.core.buffer.ydisp);
1118
+ if (t < 1)
1119
+ this.smoothFrame = win.requestAnimationFrame(step);
1120
+ else
1121
+ this.smoothTarget = null;
1122
+ };
1123
+ this.smoothFrame = win.requestAnimationFrame(step);
1124
+ }
1125
+ // ---------------------------------------------------------------- barra de rolagem e régua
1126
+ applyScrollbar() {
1127
+ const el = this.element;
1128
+ if (!el)
1129
+ return;
1130
+ const sb = this.resolved.scrollbar ?? {};
1131
+ const show = sb.visible !== false;
1132
+ el.classList.toggle('hmt-no-scrollbar', !show);
1133
+ el.classList.toggle('hmt-scrollbar-sized', show && sb.width !== undefined);
1134
+ el.classList.toggle('hmt-scrollbar-arrows', show && !!sb.arrows);
1135
+ if (sb.width !== undefined)
1136
+ el.style.setProperty('--hmt-scrollbar-width', `${sb.width}px`);
1137
+ else
1138
+ el.style.removeProperty('--hmt-scrollbar-width');
1139
+ // A régua de visão geral liga com `width` e mostra as decorações que pedem uma marca.
1140
+ const ruler = show && sb.width !== undefined;
1141
+ if (ruler && !this.overviewRuler) {
1142
+ this.overviewRuler = el.ownerDocument.createElement('div');
1143
+ this.overviewRuler.className = 'hmt-overview-ruler';
1144
+ this.overviewRuler.setAttribute('aria-hidden', 'true');
1145
+ el.appendChild(this.overviewRuler);
1146
+ }
1147
+ else if (!ruler && this.overviewRuler) {
1148
+ this.overviewRuler.remove();
1149
+ this.overviewRuler = undefined;
1150
+ }
1151
+ if (this.overviewRuler) {
1152
+ this.overviewRuler.classList.toggle('hmt-ruler-top', !!sb.overview?.topBorder);
1153
+ this.overviewRuler.classList.toggle('hmt-ruler-bottom', !!sb.overview?.bottomBorder);
1154
+ const border = this.resolved.theme.overviewBorder;
1155
+ if (border)
1156
+ this.overviewRuler.style.setProperty('--hmt-ruler-border', border);
1157
+ }
1158
+ this.renderOverviewRuler();
1159
+ this.syncScrollArea();
1160
+ }
1161
+ renderOverviewRuler() {
1162
+ const ruler = this.overviewRuler;
1163
+ if (!ruler)
1164
+ return;
1165
+ ruler.textContent = '';
1166
+ const b = this.core.buffer;
1167
+ if (b !== this.core.normal)
1168
+ return;
1169
+ const total = Math.max(1, b.lines.length);
1170
+ const doc = ruler.ownerDocument;
1171
+ for (const decoration of this.decorations) {
1172
+ const o = decoration.config.overview;
1173
+ if (!o || decoration.marker.isDisposed)
1174
+ continue;
1175
+ const mark = doc.createElement('div');
1176
+ mark.className = 'hmt-ruler-mark';
1177
+ const lines = decoration.config.height ?? 1;
1178
+ mark.style.top = `${(decoration.marker.line / total) * 100}%`;
1179
+ mark.style.height = `${Math.max((lines / total) * 100, 0.4)}%`;
1180
+ const position = o.position ?? 'full';
1181
+ mark.style.left = position === 'right' ? '66%' : position === 'center' ? '33%' : '0';
1182
+ mark.style.width = position === 'full' ? '100%' : '34%';
1183
+ mark.style.background = o.color;
1184
+ ruler.appendChild(mark);
1185
+ }
1186
+ }
1187
+ /** Volta a piscar e agenda a parada por inatividade (5 minutos). */
1188
+ wakeBlink() {
1189
+ const r = this.renderer;
1190
+ if (!r)
1191
+ return;
1192
+ if (r.blinkIdle) {
1193
+ r.blinkIdle = false;
1194
+ r.refreshRows(0, -1);
1195
+ }
1196
+ clearTimeout(this.blinkTimer);
1197
+ this.blinkTimer = setTimeout(() => {
1198
+ r.blinkIdle = true;
1199
+ r.refreshRows(0, -1);
1200
+ }, BLINK_IDLE_MS);
1201
+ }
1202
+ // ---------------------------------------------------------------- links
1203
+ addLinkSource(source) {
1204
+ this.linkSources.push(source);
1205
+ return () => {
1206
+ const index = this.linkSources.indexOf(source);
1207
+ if (index >= 0)
1208
+ this.linkSources.splice(index, 1);
1209
+ };
1210
+ }
1211
+ handleHover(e) {
1212
+ if (this.selecting || !this.renderer || this.mouseButton >= 0)
1213
+ return;
1214
+ const point = this.bufferPoint(e, false);
1215
+ const hovered = this.hoveredLink;
1216
+ if (hovered && hovered.ranges.some((r) => r.y === point.y && point.x >= r.start && point.x < r.end))
1217
+ return;
1218
+ this.clearHoveredLink(e);
1219
+ const request = ++this.linkRequest;
1220
+ this.findLink(point, (link) => {
1221
+ if (request !== this.linkRequest || !link)
1222
+ return;
1223
+ const ranges = rowRanges(link.range, this.cols);
1224
+ this.hoveredLink = { link, ranges };
1225
+ const style = link.style ?? { pointer: true, underline: true };
1226
+ if (style.underline)
1227
+ this.renderer.linkRanges = ranges;
1228
+ this.element?.classList.toggle('hmt-link-hover', style.pointer);
1229
+ this.renderer.refreshRows(0, -1);
1230
+ link.hover?.(e, link.text);
1231
+ });
1232
+ }
1233
+ clearHoveredLink(e) {
1234
+ const hovered = this.hoveredLink;
1235
+ if (!hovered)
1236
+ return;
1237
+ this.hoveredLink = undefined;
1238
+ this.element?.classList.remove('hmt-link-hover');
1239
+ if (this.renderer) {
1240
+ this.renderer.linkRanges = [];
1241
+ this.renderer.refreshRows(0, -1);
1242
+ }
1243
+ hovered.link.leave?.(e, hovered.link.text);
1244
+ }
1245
+ openLinkAt(e) {
1246
+ const point = this.bufferPoint(e, false);
1247
+ const hovered = this.hoveredLink;
1248
+ if (hovered && hovered.ranges.some((r) => r.y === point.y && point.x >= r.start && point.x < r.end)) {
1249
+ hovered.link.open(e, hovered.link.text);
1250
+ return;
1251
+ }
1252
+ this.findLink(point, (link) => link?.open(e, link.text));
1253
+ }
1254
+ /** Procura o link sob `point`: primeiro os hiperlinks OSC 8, depois as fontes, na ordem de registro. */
1255
+ findLink(point, done) {
1256
+ const osc = this.hyperlinkAt(point);
1257
+ if (osc)
1258
+ return done(osc);
1259
+ const sources = [...this.linkSources];
1260
+ const next = (i) => {
1261
+ if (i >= sources.length)
1262
+ return done(undefined);
1263
+ sources[i].linksAt(point.y, (links) => {
1264
+ const hit = links?.find((link) => contains(link.range, point.x, point.y));
1265
+ if (hit)
1266
+ done(hit);
1267
+ else
1268
+ next(i + 1);
1269
+ });
1270
+ };
1271
+ next(0);
1272
+ }
1273
+ hyperlinkAt(point) {
1274
+ const line = this.core.buffer.lines.get(point.y);
1275
+ if (!line)
1276
+ return undefined;
1277
+ const id = line.getExtended(point.x).linkId;
1278
+ if (!id)
1279
+ return undefined;
1280
+ const link = this.core.linkFor(line.getExtended(point.x));
1281
+ if (!link)
1282
+ return undefined;
1283
+ let start = point.x;
1284
+ let end = point.x;
1285
+ while (start > 0 && line.getExtended(start - 1).linkId === id)
1286
+ start--;
1287
+ while (end < line.length - 1 && line.getExtended(end + 1).linkId === id)
1288
+ end++;
1289
+ const uri = link.uri;
1290
+ const range = { start: { col: start, row: point.y }, end: { col: end + 1, row: point.y } };
1291
+ const handler = () => this.resolved.hyperlinkHandler;
1292
+ return {
1293
+ range,
1294
+ text: uri,
1295
+ open: (event) => this.openLink(event, uri, range),
1296
+ hover: (event) => handler()?.hover?.(event, uri, range),
1297
+ leave: (event) => handler()?.leave?.(event, uri, range),
1298
+ };
1299
+ }
1300
+ openLink(event, uri, range) {
1301
+ const handler = this.resolved.hyperlinkHandler;
1302
+ if (handler) {
1303
+ const http = /^https?:/i.test(uri);
1304
+ if (http || handler.anyScheme)
1305
+ handler.open(event, uri, range);
1306
+ return;
1307
+ }
1308
+ if (!/^https?:/i.test(uri))
1309
+ return;
1310
+ const win = this.element?.ownerDocument.defaultView;
1311
+ win?.open(uri, '_blank', 'noopener,noreferrer');
1312
+ }
1313
+ // ---------------------------------------------------------------- marcadores e decorações
1314
+ addMarker(cursorOffset = 0) {
1315
+ return this.core.addMarker(cursorOffset);
1316
+ }
1317
+ decorate(options) {
1318
+ if (options.marker.isDisposed)
1319
+ return undefined;
1320
+ const decoration = new Decoration(options);
1321
+ this.decorations.push(decoration);
1322
+ const off = options.marker.onDispose(() => decoration.dispose());
1323
+ decoration.onDispose(() => {
1324
+ off();
1325
+ const index = this.decorations.indexOf(decoration);
1326
+ if (index >= 0)
1327
+ this.decorations.splice(index, 1);
1328
+ });
1329
+ this.renderer?.refreshRows(0, -1);
1330
+ this.renderOverviewRuler();
1331
+ return decoration;
1332
+ }
1333
+ renderDecorations() {
1334
+ const r = this.renderer;
1335
+ if (!r)
1336
+ return;
1337
+ const b = this.core.buffer;
1338
+ for (const decoration of this.decorations) {
1339
+ const o = decoration.config;
1340
+ const y = o.marker.line - b.ydisp;
1341
+ const visible = b === this.core.normal && y >= 0 && y < this.rows;
1342
+ if (!visible) {
1343
+ if (decoration.element)
1344
+ decoration.element.style.display = 'none';
1345
+ continue;
1346
+ }
1347
+ let el = decoration.element;
1348
+ if (!el) {
1349
+ el = this.element.ownerDocument.createElement('div');
1350
+ el.className = 'hmt-decoration';
1351
+ decoration.element = el;
1352
+ (o.layer === 'top' ? r.decorationsTop : r.decorationsBottom).appendChild(el);
1353
+ }
1354
+ el.style.display = '';
1355
+ el.style.top = `${y * r.cellHeight}px`;
1356
+ el.style.height = `${(o.height ?? 1) * r.cellHeight}px`;
1357
+ el.style.width = `${(o.width ?? 1) * r.cellWidth}px`;
1358
+ const x = (o.x ?? 0) * r.cellWidth;
1359
+ if (o.anchor === 'right') {
1360
+ el.style.right = `${x}px`;
1361
+ el.style.left = '';
1362
+ }
1363
+ else {
1364
+ el.style.left = `${x}px`;
1365
+ el.style.right = '';
1366
+ }
1367
+ if (o.background)
1368
+ el.style.backgroundColor = o.background;
1369
+ if (o.color)
1370
+ el.style.color = o.color;
1371
+ decoration.fireRender(el);
1372
+ }
1373
+ }
1374
+ // ---------------------------------------------------------------- leitor de tela
1375
+ setupA11y() {
1376
+ const el = this.element;
1377
+ if (!el)
1378
+ return;
1379
+ if (!this.resolved.screenReader) {
1380
+ this.a11yTree?.remove();
1381
+ this.liveRegion?.remove();
1382
+ this.a11yTree = this.liveRegion = undefined;
1383
+ return;
1384
+ }
1385
+ if (this.a11yTree)
1386
+ return;
1387
+ const doc = el.ownerDocument;
1388
+ this.a11yTree = doc.createElement('div');
1389
+ this.a11yTree.className = 'hmt-a11y-tree';
1390
+ this.a11yTree.setAttribute('role', 'list');
1391
+ this.liveRegion = doc.createElement('div');
1392
+ this.liveRegion.className = 'hmt-a11y-live';
1393
+ this.liveRegion.setAttribute('aria-live', 'polite');
1394
+ this.liveRegion.setAttribute('aria-atomic', 'false');
1395
+ el.appendChild(this.a11yTree);
1396
+ el.appendChild(this.liveRegion);
1397
+ this.updateA11yRows(0, this.rows - 1);
1398
+ }
1399
+ updateA11yRows(start, end) {
1400
+ const tree = this.a11yTree;
1401
+ if (!tree)
1402
+ return;
1403
+ const doc = tree.ownerDocument;
1404
+ while (tree.children.length < this.rows) {
1405
+ const row = doc.createElement('div');
1406
+ row.setAttribute('role', 'listitem');
1407
+ tree.appendChild(row);
1408
+ }
1409
+ while (tree.children.length > this.rows)
1410
+ tree.lastElementChild.remove();
1411
+ const b = this.core.buffer;
1412
+ for (let y = start; y <= end && y < this.rows; y++) {
1413
+ const line = b.lines.get(b.ydisp + y);
1414
+ const text = line ? line.translateToString(true) : '';
1415
+ const row = tree.children[y];
1416
+ row.textContent = text || ' ';
1417
+ row.setAttribute('aria-posinset', String(b.ydisp + y + 1));
1418
+ row.setAttribute('aria-setsize', String(b.lines.length));
1419
+ }
1420
+ }
1421
+ /** Anuncia o que foi escrito (o leitor de tela lê a região viva), em lotes. */
1422
+ announce() {
1423
+ if (!this.liveRegion)
1424
+ return;
1425
+ const b = this.core.buffer;
1426
+ const line = b.lines.get(b.ybase + b.y);
1427
+ const text = line?.translateToString(true) ?? '';
1428
+ if (!text || text === this.liveText)
1429
+ return;
1430
+ // Muitas linhas num instante: o leitor de tela não acompanha; avisa uma vez (`strings.tooMuchOutput`).
1431
+ const now = Date.now();
1432
+ if (now - this.announceWindow > 1000) {
1433
+ this.announceWindow = now;
1434
+ this.announcedLines = 0;
1435
+ }
1436
+ if (++this.announcedLines > 20) {
1437
+ if (this.announcedLines === 21) {
1438
+ this.liveText = this.resolved.strings.tooMuchOutput;
1439
+ clearTimeout(this.liveTimer);
1440
+ this.liveTimer = setTimeout(() => {
1441
+ if (this.liveRegion)
1442
+ this.liveRegion.textContent = this.liveText;
1443
+ }, 50);
1444
+ }
1445
+ return;
1446
+ }
1447
+ this.liveText = text;
1448
+ clearTimeout(this.liveTimer);
1449
+ this.liveTimer = setTimeout(() => {
1450
+ if (this.liveRegion)
1451
+ this.liveRegion.textContent = this.liveText;
1452
+ }, 50);
1453
+ }
1454
+ // ---------------------------------------------------------------- escrita e tamanho
1455
+ write(data, done) {
1456
+ if (this.loading)
1457
+ this.queued.push({ data, done });
1458
+ else
1459
+ this.core.write(data, done);
1460
+ }
1461
+ writeLine(data, done) {
1462
+ this.write(data);
1463
+ this.write('\r\n', done);
1464
+ }
1465
+ resize(cols, rows) {
1466
+ if (!Number.isFinite(cols) || !Number.isFinite(rows))
1467
+ return;
1468
+ this.core.resize(cols, rows);
1469
+ this.resolved.cols = this.core.cols;
1470
+ this.resolved.rows = this.core.rows;
1471
+ }
1472
+ fit() {
1473
+ return this.fitter.fit();
1474
+ }
1475
+ proposeSize() {
1476
+ return this.fitter.proposeSize();
1477
+ }
1478
+ redraw(start = 0, end = -1) {
1479
+ if (end < 0)
1480
+ this.renderer?.refreshAll();
1481
+ else
1482
+ this.renderer?.refreshRows(start, end);
1483
+ }
1484
+ reset() {
1485
+ this.core.reset();
1486
+ this.syncScrollArea();
1487
+ this.renderer?.refreshAll();
1488
+ }
1489
+ /** Apaga tudo, deixando a linha do cursor (o prompt) como a primeira. */
1490
+ clear() {
1491
+ const core = this.core;
1492
+ const b = core.buffer;
1493
+ if (b !== core.normal)
1494
+ return;
1495
+ const keep = b.lines.get(b.ybase + b.y);
1496
+ const keptLine = b.ybase + b.y;
1497
+ b.lines = new CircularList(b.lines.maxLength);
1498
+ b.lines.push(keep);
1499
+ b.ybase = 0;
1500
+ b.ydisp = 0;
1501
+ b.y = 0;
1502
+ b.fillViewport();
1503
+ for (const marker of [...core.markers]) {
1504
+ if (marker.line === keptLine)
1505
+ marker.line = 0;
1506
+ else
1507
+ marker.dispose();
1508
+ }
1509
+ core.clearSelection();
1510
+ this.syncScrollArea();
1511
+ this.renderer?.refreshAll();
1512
+ this.scrollEmitter.fire(0);
1513
+ }
1514
+ async remeasure() {
1515
+ const fonts = this.element?.ownerDocument.fonts;
1516
+ if (fonts?.ready)
1517
+ await fonts.ready;
1518
+ if (this.disposed || !this.renderer)
1519
+ return;
1520
+ this.renderer.measureCell();
1521
+ this.renderer.refreshAll();
1522
+ this.syncScrollArea();
1523
+ }
1524
+ // ---------------------------------------------------------------- rolagem
1525
+ scrollBy(lines) {
1526
+ const b = this.core.buffer;
1527
+ const target = Math.max(0, Math.min(b.ybase, b.ydisp + Math.trunc(lines)));
1528
+ if (target === b.ydisp)
1529
+ return;
1530
+ b.ydisp = target;
1531
+ this.syncScrollArea();
1532
+ this.renderer?.refreshAll();
1533
+ this.scrollEmitter.fire(target);
1534
+ }
1535
+ scrollByPages(pages) {
1536
+ this.scrollBy(pages * (this.rows - 1));
1537
+ }
1538
+ scrollToTop() {
1539
+ this.scrollBy(-this.core.buffer.ydisp);
1540
+ }
1541
+ scrollToBottom() {
1542
+ const b = this.core.buffer;
1543
+ this.scrollBy(b.ybase - b.ydisp);
1544
+ }
1545
+ scrollTo(line) {
1546
+ this.scrollBy(line - this.core.buffer.ydisp);
1547
+ }
1548
+ syncScrollArea() {
1549
+ const r = this.renderer;
1550
+ if (!r || !this.viewport || !this.scrollArea)
1551
+ return;
1552
+ const b = this.core.buffer;
1553
+ // O viewport pode ser mais alto que as linhas (sobra de pixels do ajuste): a área tem a altura dele mais o
1554
+ // histórico, para o `scrollTop` máximo cair exatamente no fim. Com `linhas × célula`, o navegador limita o
1555
+ // `scrollTop` abaixo do fim, o arredondamento descola a vista do fundo e a saída nova some embaixo.
1556
+ const viewportHeight = this.viewport.clientHeight || this.rows * r.cellHeight;
1557
+ this.scrollArea.style.height = `${(b.lines.length - this.rows) * r.cellHeight + viewportHeight}px`;
1558
+ const top = b.ydisp * r.cellHeight;
1559
+ if (Math.abs(this.viewport.scrollTop - top) >= 1)
1560
+ this.viewport.scrollTop = top;
1561
+ }
1562
+ // ---------------------------------------------------------------- WebSocket, serialização e descarte
1563
+ connect(socket, options = {}) {
1564
+ const connection = new Connection(socket, options);
1565
+ connection.attach(this);
1566
+ return () => connection.dispose();
1567
+ }
1568
+ serialize(options) {
1569
+ return this.serializer.serialize(this, options);
1570
+ }
1571
+ serializeHtml(options) {
1572
+ return this.serializer.serializeAsHTML(this, options);
1573
+ }
1574
+ dispose() {
1575
+ if (this.disposed)
1576
+ return;
1577
+ this.disposed = true;
1578
+ for (const feature of this.features.values())
1579
+ feature.dispose();
1580
+ this.features.clear();
1581
+ this.fitter.dispose();
1582
+ for (const decoration of [...this.decorations])
1583
+ decoration.dispose();
1584
+ clearTimeout(this.liveTimer);
1585
+ clearTimeout(this.blinkTimer);
1586
+ this.element?.ownerDocument.defaultView?.cancelAnimationFrame?.(this.smoothFrame);
1587
+ this.store.dispose();
1588
+ this.renderer?.dispose();
1589
+ this.element?.remove();
1590
+ this.core.dispose();
1591
+ for (const emitter of [
1592
+ this.keyEmitter, this.renderEmitter, this.scrollEmitter, this.selectionEmitter, this.screenEmitter, this.metricsEmitter,
1593
+ this.searchEmitter, this.progressEmitter, this.programStatusEmitter,
1594
+ ])
1595
+ emitter.dispose();
1596
+ }
1597
+ /** Para os testes: desenha já o que está pendente. */
1598
+ renderNow() {
1599
+ this.renderer?.renderNow();
1600
+ }
1601
+ /** Partes internas para os recursos deste pacote (imagens, GPU, serialização…). */
1602
+ get internals() {
1603
+ return {
1604
+ core: this.core,
1605
+ renderer: this.renderer,
1606
+ element: this.element,
1607
+ onFrame: (listener) => {
1608
+ this.renderer?.frameListeners.add(listener);
1609
+ return () => this.renderer?.frameListeners.delete(listener);
1610
+ },
1611
+ refreshAll: () => this.renderer?.refreshAll(),
1612
+ };
1613
+ }
1614
+ }
1615
+ function cssOr(css, fallback) {
1616
+ if (!css)
1617
+ return fallback;
1618
+ return parseCssColor(css) ?? fallback;
1619
+ }
1620
+ /** Mesmo valor de opção de recurso: objetos comparados campo a campo, para `[options]` recriado a cada render. */
1621
+ function sameValue(a, b) {
1622
+ if (a === b)
1623
+ return true;
1624
+ if (typeof a !== 'object' || typeof b !== 'object' || !a || !b)
1625
+ return false;
1626
+ const x = a;
1627
+ const y = b;
1628
+ const keys = Object.keys(x);
1629
+ if (keys.length !== Object.keys(y).length)
1630
+ return false;
1631
+ return keys.every((key) => {
1632
+ const p = x[key];
1633
+ const q = y[key];
1634
+ if (p instanceof RegExp && q instanceof RegExp)
1635
+ return p.source === q.source && p.flags === q.flags;
1636
+ return p === q;
1637
+ });
1638
+ }
1639
+ function contains(range, col, row) {
1640
+ const after = row > range.start.row || (row === range.start.row && col >= range.start.col);
1641
+ const before = row < range.end.row || (row === range.end.row && col < range.end.col);
1642
+ return after && before;
1643
+ }
1644
+ /** Faixa de células → faixas por linha da tela, `end` exclusivo. */
1645
+ function rowRanges(range, cols) {
1646
+ const out = [];
1647
+ for (let y = range.start.row; y <= range.end.row; y++) {
1648
+ const start = y === range.start.row ? range.start.col : 0;
1649
+ const end = y === range.end.row ? range.end.col : cols;
1650
+ out.push({ y, start, end });
1651
+ }
1652
+ return out;
1653
+ }
1654
+ //# sourceMappingURL=engine.js.map