afield 0.0.0-stage → 0.1.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 (43) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +165 -2
  3. package/afield +214 -0
  4. package/package.json +42 -4
  5. package/pi-extensions/afield-session.ts +59 -0
  6. package/pi-extensions/elastic-footer.ts +167 -0
  7. package/server/attach.js +264 -0
  8. package/server/auth.js +169 -0
  9. package/server/client.js +64 -0
  10. package/server/control.js +65 -0
  11. package/server/identity.js +45 -0
  12. package/server/index.js +375 -0
  13. package/server/mirror.js +159 -0
  14. package/server/origin.js +51 -0
  15. package/server/picker.js +187 -0
  16. package/server/places.js +348 -0
  17. package/server/protocol.js +51 -0
  18. package/server/quick-tunnel.js +40 -0
  19. package/server/registry.js +190 -0
  20. package/server/serve.js +100 -0
  21. package/server/session-main.js +27 -0
  22. package/server/session.js +112 -0
  23. package/server/supervisor.js +432 -0
  24. package/server/viewer.js +65 -0
  25. package/src/app.js +1683 -0
  26. package/src/apple-touch-icon.png +0 -0
  27. package/src/index.html +96 -0
  28. package/src/keys.js +59 -0
  29. package/src/pi-icon.svg +13 -0
  30. package/src/style.css +559 -0
  31. package/src/transport.js +153 -0
  32. package/src/ttyd.js +51 -0
  33. package/src/viewport.js +168 -0
  34. package/tsconfig.json +14 -0
  35. package/vendor/wterm/LICENSE +191 -0
  36. package/vendor/wterm/README.md +7 -0
  37. package/vendor/wterm/packages/@wterm/dom/src/debug.ts +347 -0
  38. package/vendor/wterm/packages/@wterm/dom/src/hyperlink.ts +8 -0
  39. package/vendor/wterm/packages/@wterm/dom/src/index.ts +13 -0
  40. package/vendor/wterm/packages/@wterm/dom/src/input.ts +662 -0
  41. package/vendor/wterm/packages/@wterm/dom/src/renderer.ts +725 -0
  42. package/vendor/wterm/packages/@wterm/dom/src/terminal.css +195 -0
  43. package/vendor/wterm/packages/@wterm/dom/src/wterm.ts +609 -0
@@ -0,0 +1,662 @@
1
+ // Modified for afield from upstream wterm; see vendor/wterm/README.md.
2
+ import type { TerminalCore } from "@wterm/core";
3
+ import { isLinkActivationModifier } from "./hyperlink.js";
4
+
5
+ const NORMAL_KEYS: Record<string, string> = {
6
+ ArrowUp: "\x1b[A",
7
+ ArrowDown: "\x1b[B",
8
+ ArrowRight: "\x1b[C",
9
+ ArrowLeft: "\x1b[D",
10
+ Home: "\x1b[H",
11
+ End: "\x1b[F",
12
+ };
13
+
14
+ const APP_KEYS: Record<string, string> = {
15
+ ArrowUp: "\x1bOA",
16
+ ArrowDown: "\x1bOB",
17
+ ArrowRight: "\x1bOC",
18
+ ArrowLeft: "\x1bOD",
19
+ Home: "\x1bOH",
20
+ End: "\x1bOF",
21
+ };
22
+
23
+ const FIXED_KEYS: Record<string, string> = {
24
+ Enter: "\r",
25
+ Backspace: "\x7f",
26
+ Tab: "\t",
27
+ Escape: "\x1b",
28
+ Insert: "\x1b[2~",
29
+ Delete: "\x1b[3~",
30
+ PageUp: "\x1b[5~",
31
+ PageDown: "\x1b[6~",
32
+ F1: "\x1bOP",
33
+ F2: "\x1bOQ",
34
+ F3: "\x1bOR",
35
+ F4: "\x1bOS",
36
+ F5: "\x1b[15~",
37
+ F6: "\x1b[17~",
38
+ F7: "\x1b[18~",
39
+ F8: "\x1b[19~",
40
+ F9: "\x1b[20~",
41
+ F10: "\x1b[21~",
42
+ F11: "\x1b[23~",
43
+ F12: "\x1b[24~",
44
+ };
45
+
46
+ export class InputHandler {
47
+ private element: HTMLElement;
48
+ private textarea: HTMLTextAreaElement;
49
+ private onData: (data: string) => void;
50
+ private getBridge: () => TerminalCore | null;
51
+ private getCellSize: () => {
52
+ charWidth: number;
53
+ rowHeight: number;
54
+ } | null;
55
+ private composing = false;
56
+ private readonly iosQuickPath =
57
+ /iPad|iPhone|iPod/.test(navigator.userAgent) ||
58
+ (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
59
+ private mouseButtons = 0;
60
+ private focused = false;
61
+ // The field is a mirror of the PTY's input line: `sent` is what this class
62
+ // has transmitted of the field's content. Every byte the PTY receives from
63
+ // anywhere else (bar keys, Enter, paste, PTY resets) must invalidate the
64
+ // mirror via resetMirror(), or the next diff sends bytes that double-apply.
65
+ private sent = "";
66
+ private idleClear: ReturnType<typeof setTimeout> | null = null;
67
+ private segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
68
+ /** True while the diff is transmitting, so consumers can exempt it from
69
+ * modifier chords and other send-side rewriting. */
70
+ inFlush = false;
71
+ /** Consulted when an insertText event adds exactly one grapheme to the
72
+ * field and removes nothing: a typed key, as far as the field can tell,
73
+ * and the only sign of one from keyboards whose keydowns are keyCode 229.
74
+ * Returns the bytes to send in its place (a modifier chord), or null to
75
+ * transmit it as typed. */
76
+ keyChord: ((key: string) => string | null) | null = null;
77
+
78
+ private _onKeyDown: (e: KeyboardEvent) => void;
79
+ private _onPaste: (e: ClipboardEvent) => void;
80
+ private _onCompositionStart: () => void;
81
+ private _onCompositionEnd: (e: CompositionEvent) => void;
82
+ private _onBeforeInput: (e: InputEvent) => void;
83
+ private _onInput: (e: InputEvent) => void;
84
+ private _onFocus: () => void;
85
+ private _onBlur: () => void;
86
+ private _onMouseDown: (e: MouseEvent) => void;
87
+ private _onMouseMove: (e: MouseEvent) => void;
88
+ private _onMouseUp: (e: MouseEvent) => void;
89
+ private _onWheel: (e: WheelEvent) => void;
90
+
91
+ constructor(
92
+ element: HTMLElement,
93
+ onData: (data: string) => void,
94
+ getBridge: () => TerminalCore | null,
95
+ getCellSize: () => { charWidth: number; rowHeight: number } | null = () =>
96
+ null,
97
+ ) {
98
+ this.element = element;
99
+ this.onData = onData;
100
+ this.getBridge = getBridge;
101
+ this.getCellSize = getCellSize;
102
+
103
+ this.textarea = document.createElement("textarea");
104
+ this.textarea.setAttribute("autocapitalize", "off");
105
+ this.textarea.setAttribute("autocomplete", "off");
106
+ this.textarea.setAttribute("autocorrect", "off");
107
+ this.textarea.setAttribute("spellcheck", "false");
108
+ this.textarea.setAttribute("enterkeyhint", "send");
109
+ this.textarea.setAttribute("tabindex", "0");
110
+ this.textarea.setAttribute("aria-hidden", "true");
111
+ const s = this.textarea.style;
112
+ // Sticky at the scrollport's bottom edge: the caret is always in view, so
113
+ // WebKit's reveal-the-caret scrolling (swipe, dictation, any real
114
+ // insertion) has nothing to correct and never drags the scroller to the
115
+ // top of history, where an absolutely-positioned field at top: 0 put it.
116
+ // The element is fully transparent, 1px wide and 0 tall, so being in view
117
+ // shows nothing and adds nothing to the scroll geometry; in flow it sits
118
+ // after the grid, which keeps it out of every row-height invariant.
119
+ s.position = "sticky";
120
+ s.bottom = "0";
121
+ s.left = "0";
122
+ s.top = "auto";
123
+ s.width = "1px";
124
+ s.height = "0";
125
+ s.opacity = "0";
126
+ s.overflow = "hidden";
127
+ s.border = "0";
128
+ s.padding = "0";
129
+ s.margin = "0";
130
+ s.outline = "none";
131
+ s.resize = "none";
132
+ s.pointerEvents = "none";
133
+ s.caretColor = "transparent";
134
+ s.color = "transparent";
135
+ s.background = "transparent";
136
+ element.appendChild(this.textarea);
137
+
138
+ this._onKeyDown = this.handleKeyDown.bind(this);
139
+ this._onPaste = this.handlePaste.bind(this);
140
+ this._onCompositionStart = this.handleCompositionStart.bind(this);
141
+ this._onCompositionEnd = this.handleCompositionEnd.bind(this);
142
+ this._onBeforeInput = this.handleBeforeInput.bind(this);
143
+ this._onInput = this.handleInput.bind(this);
144
+ this._onFocus = () => {
145
+ if (this.focused) return;
146
+ this.focused = true;
147
+ this.element.classList.add("focused");
148
+ if (this.getBridge()?.focusEvents?.()) this.onData("\x1b[I");
149
+ };
150
+ this._onBlur = () => {
151
+ this.focused = false;
152
+ this.element.classList.remove("focused");
153
+ this.stopMouseCapture();
154
+ if (this.getBridge()?.focusEvents?.()) this.onData("\x1b[O");
155
+ };
156
+ this._onMouseDown = (event) => this.handleMouse(event, "press");
157
+ this._onMouseMove = (event) => {
158
+ if (this.mouseButtons !== 0) this.handleMouse(event, "move");
159
+ };
160
+ this._onMouseUp = (event) => {
161
+ if (this.mouseButtons === 0) return;
162
+ this.handleMouse(event, "release");
163
+ this.mouseButtons = event.buttons & 7;
164
+ if (this.mouseButtons === 0) this.stopMouseCapture();
165
+ };
166
+ this._onWheel = (event) => this.handleMouse(event, "wheel");
167
+
168
+ this.textarea.addEventListener("keydown", this._onKeyDown);
169
+ this.textarea.addEventListener("paste", this._onPaste as EventListener);
170
+ this.textarea.addEventListener(
171
+ "compositionstart",
172
+ this._onCompositionStart,
173
+ );
174
+ this.textarea.addEventListener(
175
+ "compositionend",
176
+ this._onCompositionEnd as EventListener,
177
+ );
178
+ this.textarea.addEventListener("beforeinput", this._onBeforeInput);
179
+ this.textarea.addEventListener("input", this._onInput);
180
+ this.textarea.addEventListener("focus", this._onFocus);
181
+ this.textarea.addEventListener("blur", this._onBlur);
182
+ this.element.addEventListener("mousedown", this._onMouseDown);
183
+ this.element.addEventListener("wheel", this._onWheel, { passive: false });
184
+ }
185
+
186
+ focus(): void {
187
+ this.textarea.focus({ preventScroll: true });
188
+ }
189
+
190
+ destroy(): void {
191
+ if (this.idleClear !== null) clearTimeout(this.idleClear);
192
+ this.textarea.removeEventListener("keydown", this._onKeyDown);
193
+ this.textarea.removeEventListener("paste", this._onPaste as EventListener);
194
+ this.textarea.removeEventListener(
195
+ "compositionstart",
196
+ this._onCompositionStart,
197
+ );
198
+ this.textarea.removeEventListener(
199
+ "compositionend",
200
+ this._onCompositionEnd as EventListener,
201
+ );
202
+ this.textarea.removeEventListener("beforeinput", this._onBeforeInput);
203
+ this.textarea.removeEventListener("input", this._onInput);
204
+ this.textarea.removeEventListener("focus", this._onFocus);
205
+ this.textarea.removeEventListener("blur", this._onBlur);
206
+ this.element.removeEventListener("mousedown", this._onMouseDown);
207
+ this.stopMouseCapture();
208
+ this.element.removeEventListener("wheel", this._onWheel);
209
+ this.element.classList.remove("focused");
210
+ this.textarea.remove();
211
+ }
212
+
213
+ private handleKeyDown(e: KeyboardEvent): void {
214
+ if (e.isComposing || e.keyCode === 229) return;
215
+ // A non-composing event releases the latch if the IME omitted compositionend.
216
+ this.composing = false;
217
+
218
+ // A non-empty field lets the software keyboard drive deletion natively:
219
+ // repeats may arrive as deleteContentBackward input events, not keydowns,
220
+ // and preventDefault here would cancel that loop. Stand aside and let the
221
+ // diff turn the deletion into DEL bytes. Only for an unmodified Backspace:
222
+ // a modified one carries terminal meaning of its own -- alt+Backspace is
223
+ // esc+DEL (word delete), meta+Backspace kill-line -- and must keep the
224
+ // keydown path below, which resets the mirror for the line change it
225
+ // makes directly. An empty field leaves the keydown path as the
226
+ // deletion's owner even unmodified.
227
+ if (
228
+ e.key === "Backspace" &&
229
+ !e.altKey &&
230
+ !e.ctrlKey &&
231
+ !e.metaKey &&
232
+ this.textarea.value !== ""
233
+ )
234
+ return;
235
+ if ((e.metaKey || e.ctrlKey) && e.key === "c") {
236
+ const sel = window.getSelection();
237
+ if (sel && sel.toString().length > 0) return;
238
+ }
239
+ if ((e.metaKey || e.ctrlKey) && e.key === "v") {
240
+ this.textarea.focus();
241
+ return;
242
+ }
243
+ if (e.metaKey && !e.ctrlKey) {
244
+ if (e.key === "Backspace") {
245
+ e.preventDefault();
246
+ // Kill-line empties the PTY's line directly, so the mirror must go
247
+ // with it -- reachable now with a non-empty field, since modified
248
+ // Backspace no longer stands aside.
249
+ this.resetMirror();
250
+ this.onData("\x15");
251
+ } else if (e.key === "a") {
252
+ e.preventDefault();
253
+ const sel = window.getSelection();
254
+ if (sel) {
255
+ const range = document.createRange();
256
+ range.selectNodeContents(this.element);
257
+ sel.removeAllRanges();
258
+ sel.addRange(range);
259
+ }
260
+ }
261
+ return;
262
+ }
263
+
264
+ // Only preventDefault once a sequence is actually produced: keys with no
265
+ // terminal meaning (an emoji keydown carries the character as a 2-unit
266
+ // string, for one) must keep their default action, which is a real
267
+ // insertion into the field -- the input event then carries it through the
268
+ // diff. Suppressing it here is what made emoji presses do nothing.
269
+ const seq = this.keyToSequence(e);
270
+ if (!seq) return;
271
+ e.preventDefault();
272
+ // Everything a keydown sends either changes or consumes the PTY's line,
273
+ // so the mirror goes: arrows move the cursor (the diff transport assumes
274
+ // end-of-line), Enter consumes the line, a printable appends to it.
275
+ this.resetMirror();
276
+ this.onData(seq);
277
+ }
278
+
279
+ private handlePaste(e: ClipboardEvent): void {
280
+ e.preventDefault();
281
+ const text = e.clipboardData?.getData("text");
282
+ if (!text) return;
283
+
284
+ const bridge = this.getBridge();
285
+ if (bridge && bridge.bracketedPaste()) {
286
+ // Strip ESC bytes so clipboard payloads cannot inject \x1b[201~ to
287
+ // break out of bracketed paste mode and smuggle commands to the PTY.
288
+ const safe = text.replace(/\x1b/g, "");
289
+ this.onData("\x1b[200~" + safe + "\x1b[201~");
290
+ } else {
291
+ this.onData(text);
292
+ }
293
+ this.resetMirror();
294
+ }
295
+
296
+ private handleCompositionStart(): void {
297
+ this.composing = true;
298
+ }
299
+
300
+ private handleCompositionEnd(e: CompositionEvent): void {
301
+ this.composing = false;
302
+ this.separateCommittedText();
303
+ // Do not send e.data: engines disagree about whether the final `input`
304
+ // fires before or after `compositionend`, and the committed text is in
305
+ // the field either way -- flush() is idempotent, so whichever event
306
+ // carries it first transmits it exactly once.
307
+ this.flush();
308
+ }
309
+
310
+ /**
311
+ * The QuickPath separator rule, shared by both delivery paths: iOS emits
312
+ * its separator space only after an insertion it scored as a word, so a
313
+ * swiped single letter -- and whatever is swiped or dictated right after
314
+ * it -- arrives glued to the previous word. Tapped keys cannot confuse the
315
+ * rule: they are preventDefaulted in the keydown path and never reach the
316
+ * field as input events. An insertion of one or more letters landing
317
+ * directly against a word or number character therefore gets one separator
318
+ * space spliced in front of it, before the diff transmits. `insertAt` is
319
+ * where the inserted run begins, `caret` where the engine left the caret
320
+ * (after the run). Replacement events (autocorrect) and anything already
321
+ * spaced are exempt by the callers' gates. Unicode letters and numbers:
322
+ * dictation and swipe do not stop at ASCII.
323
+ */
324
+ private separateInsertedLetters(added: string, insertAt: number, caret: number): void {
325
+ if (insertAt <= 0 || !/^[\p{L}]+$/u.test(added)) return;
326
+ const before = this.textarea.value.slice(0, insertAt);
327
+ if (!/[\p{L}\p{N}]$/u.test(before)) return;
328
+ this.textarea.value = `${before} ${added}${this.textarea.value.slice(insertAt + added.length)}`;
329
+ this.textarea.setSelectionRange(caret + 1, caret + 1);
330
+ }
331
+
332
+ /** Applied at composition end: QuickPath may deliver through the
333
+ * marked-text pathway, where per-event interception is off-limits because
334
+ * the engine owns the field mid-composition. Once the composition
335
+ * commits, the text is ours again and the withheld space can be spliced
336
+ * in before the diff transmits. */
337
+ private separateCommittedText(): void {
338
+ if (!this.iosQuickPath) return;
339
+ const value = this.textarea.value;
340
+ let p = 0;
341
+ while (p < this.sent.length && p < value.length && this.sent[p] === value[p]) p++;
342
+ if (p < value.length) this.separateInsertedLetters(value.slice(p), p, value.length);
343
+ }
344
+
345
+ private separateSwipeInsertion(e: InputEvent): void {
346
+ if (!this.iosQuickPath || e.inputType !== "insertText" || !e.data) return;
347
+ const ta = this.textarea;
348
+ const start = ta.selectionStart;
349
+ const end = ta.selectionEnd;
350
+ if (start === null || start !== end) return;
351
+ this.separateInsertedLetters(e.data, end - e.data.length, end);
352
+ }
353
+
354
+ private handleBeforeInput(e: InputEvent): void {
355
+ if (e.inputType !== "deleteContentBackward" || e.isComposing) return;
356
+ this.composing = false;
357
+ if (this.textarea.value && !e.cancelable) return;
358
+ e.preventDefault();
359
+
360
+ if (!this.textarea.value) {
361
+ this.resetMirror();
362
+ this.sendDiff("\x7f");
363
+ return;
364
+ }
365
+
366
+ const graphemes = Array.from(
367
+ this.segmenter.segment(this.textarea.value),
368
+ (x) => x.segment,
369
+ );
370
+ this.textarea.value = graphemes.slice(0, -1).join("");
371
+ this.textarea.setSelectionRange(
372
+ this.textarea.value.length,
373
+ this.textarea.value.length,
374
+ );
375
+ this.flush();
376
+ }
377
+
378
+ private handleInput(e: InputEvent): void {
379
+ if (e.isComposing) return;
380
+ // A committed event releases the latch if an IME omitted compositionend
381
+ // after an external key reset the field.
382
+ this.composing = false;
383
+ this.separateSwipeInsertion(e);
384
+ this.flush(e.inputType === "insertText");
385
+ }
386
+
387
+ private sendDiff(data: string): void {
388
+ this.inFlush = true;
389
+ try {
390
+ this.onData(data);
391
+ } finally {
392
+ this.inFlush = false;
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Transmit the difference between the field and what has already been
398
+ * sent. The field is never wiped: iOS's text-insertion system (QuickPath,
399
+ * dictation, the emoji keyboard) reads it to decide things like the
400
+ * separator space between swiped words, and an empty field reads as
401
+ * "nothing to separate".
402
+ *
403
+ * Erase counts are graphemes -- that is what a terminal line editor removes
404
+ * per DEL (verified against pi) -- and the transport assumes the PTY's
405
+ * cursor is at end-of-line, which every mirror invalidation exists to
406
+ * protect. DEL erases from that end, so a change anywhere in the field
407
+ * erases everything after its start and sends it again.
408
+ *
409
+ * A newline inside the inserted text is translated to CR (dictation emits
410
+ * insertParagraph). Everything before a CR is consumed by the program, and
411
+ * the field's tail after the last CR is exactly the PTY's new line, so the
412
+ * mirror stays aligned without touching the field mid-dictation. Consumed
413
+ * lines cannot be unsent, so the diff covers only the lines after the ones
414
+ * already sent: an edit to an earlier line (dictation revising a word, or
415
+ * auto-punctuation before a newline) is dropped rather than resubmitted.
416
+ *
417
+ * `typed` marks an insertText event, the only kind that can be a key:
418
+ * composition commits and replacements are never offered to keyChord.
419
+ */
420
+ private flush(typed = false): void {
421
+ const value = this.textarea.value;
422
+ if (value === this.sent) {
423
+ this.caretToEnd();
424
+ return;
425
+ }
426
+ this.armIdleClear();
427
+ const consumed = this.sent.split("\n").length - 1;
428
+ const graphemes = (s: string) => Array.from(this.segmenter.segment(s), (x) => x.segment);
429
+ const before = graphemes(this.sent.split("\n")[consumed]);
430
+ const after = graphemes(value.split("\n").slice(consumed).join("\n"));
431
+ let p = 0;
432
+ while (p < before.length && p < after.length && before[p] === after[p]) p++;
433
+ const deleted = before.length - p;
434
+ const added = after.slice(p);
435
+ const inserted = added.join("").replace(/\n/g, "\r");
436
+ const chord =
437
+ typed && deleted === 0 && added.length === 1
438
+ ? this.keyChord?.(inserted)
439
+ : null;
440
+ if (chord) {
441
+ // A chord acts on the PTY's line (Ctrl-C drops it, Alt+b moves its
442
+ // cursor), so the line is no longer what the field holds.
443
+ this.resetMirror();
444
+ this.sendDiff(chord);
445
+ return;
446
+ }
447
+ if (deleted > 0 || inserted.length > 0) {
448
+ this.sendDiff("\x7f".repeat(deleted) + inserted);
449
+ }
450
+ this.sent = value;
451
+ // Bounded buffer: past the cap, forget immediately after transmitting.
452
+ if (value.length > 4096) this.resetMirror();
453
+ this.caretToEnd();
454
+ }
455
+
456
+ /**
457
+ * Keep the caret collapsed at the end of the field, where the PTY's cursor
458
+ * is, so the next insertion lands there. Chrome's Android IME path leaves
459
+ * it at 0 after inserting into a zero-size field (Chromium issue
460
+ * 349994195), and the next key would go in front of everything typed so
461
+ * far. Engines that already leave it there are not touched.
462
+ */
463
+ private caretToEnd(): void {
464
+ const ta = this.textarea;
465
+ const end = ta.value.length;
466
+ if (ta.selectionStart !== end || ta.selectionEnd !== end) ta.setSelectionRange(end, end);
467
+ }
468
+
469
+ /**
470
+ * Drop the mirror: the field is cleared and its content forgotten. Call
471
+ * whenever the PTY's line changes from outside this class, or the next
472
+ * diff sends bytes that double-apply over the new line state.
473
+ */
474
+ resetMirror(): void {
475
+ this.textarea.value = "";
476
+ this.sent = "";
477
+ if (this.idleClear !== null) {
478
+ clearTimeout(this.idleClear);
479
+ this.idleClear = null;
480
+ }
481
+ }
482
+
483
+ /**
484
+ * A long-lived field is a scratch buffer, not a diary: forget it after a
485
+ * generous idle, and keep it bounded during a continuous burst. Forgetting
486
+ * only drops separator context and re-send history; the next transmission
487
+ * is computed from an empty mirror and appends correctly.
488
+ */
489
+ private armIdleClear(): void {
490
+ if (this.idleClear !== null) clearTimeout(this.idleClear);
491
+ this.idleClear = setTimeout(() => {
492
+ if (!this.composing) this.resetMirror();
493
+ }, 30_000);
494
+ }
495
+
496
+ private handleMouse(
497
+ event: MouseEvent | WheelEvent,
498
+ kind: "press" | "move" | "release" | "wheel",
499
+ ): void {
500
+ const bridge = this.getBridge();
501
+ const tracking = bridge?.mouseTracking?.() ?? 0;
502
+ if (!bridge || tracking === 0 || !bridge.mouseSgr?.()) return;
503
+ if (
504
+ kind === "press" &&
505
+ isLinkActivationModifier(
506
+ event,
507
+ this.element.ownerDocument.defaultView?.navigator ?? navigator,
508
+ ) &&
509
+ event.target instanceof Element &&
510
+ event.target.closest(".term-link")
511
+ ) {
512
+ return;
513
+ }
514
+ if (kind === "press" && (event.shiftKey || event.button > 2)) return;
515
+ if (kind === "release" && event.button > 2) return;
516
+ const supportedButtons = event.buttons & 7;
517
+ if (kind === "move" && (tracking !== 1002 || supportedButtons === 0)) {
518
+ return;
519
+ }
520
+
521
+ const view = this.element.ownerDocument.defaultView;
522
+ if (!view) return;
523
+ const viewportRow = this.element.querySelector<HTMLElement>(
524
+ ".term-row:not(.term-scrollback-row)",
525
+ );
526
+ const hostRect = this.element.getBoundingClientRect();
527
+ const rowRect = viewportRow?.getBoundingClientRect();
528
+ const cellSize = this.getCellSize();
529
+ let left: number;
530
+ let top: number;
531
+ let charWidth: number;
532
+ let rowHeight: number;
533
+ if (rowRect && cellSize) {
534
+ left = rowRect.left;
535
+ top = rowRect.top;
536
+ charWidth = cellSize.charWidth;
537
+ rowHeight = cellSize.rowHeight;
538
+ } else {
539
+ const style = view.getComputedStyle(this.element);
540
+ const borderLeft = parseFloat(style.borderLeftWidth) || 0;
541
+ const borderRight = parseFloat(style.borderRightWidth) || 0;
542
+ const borderTop = parseFloat(style.borderTopWidth) || 0;
543
+ const borderBottom = parseFloat(style.borderBottomWidth) || 0;
544
+ const paddingLeft = parseFloat(style.paddingLeft) || 0;
545
+ const paddingRight = parseFloat(style.paddingRight) || 0;
546
+ const paddingTop = parseFloat(style.paddingTop) || 0;
547
+ const paddingBottom = parseFloat(style.paddingBottom) || 0;
548
+ left = rowRect?.left ?? hostRect.left + borderLeft + paddingLeft;
549
+ top = rowRect?.top ?? hostRect.top + borderTop + paddingTop;
550
+ charWidth =
551
+ (hostRect.width -
552
+ borderLeft -
553
+ borderRight -
554
+ paddingLeft -
555
+ paddingRight) /
556
+ bridge.getCols();
557
+ rowHeight =
558
+ (hostRect.height -
559
+ borderTop -
560
+ borderBottom -
561
+ paddingTop -
562
+ paddingBottom) /
563
+ bridge.getRows();
564
+ }
565
+ if (charWidth <= 0 || rowHeight <= 0) return;
566
+ if (kind === "press") {
567
+ this.textarea.focus({ preventScroll: true });
568
+ if (!this.focused) this._onFocus();
569
+ this.mouseButtons =
570
+ supportedButtons ||
571
+ (event.button === 1 ? 4 : event.button === 2 ? 2 : 1);
572
+ view.addEventListener("mousemove", this._onMouseMove);
573
+ view.addEventListener("mouseup", this._onMouseUp);
574
+ }
575
+ const col = Math.max(
576
+ 1,
577
+ Math.min(
578
+ bridge.getCols(),
579
+ Math.floor((event.clientX - left) / charWidth) + 1,
580
+ ),
581
+ );
582
+ const row = Math.max(
583
+ 1,
584
+ Math.min(
585
+ bridge.getRows(),
586
+ Math.floor((event.clientY - top) / rowHeight) + 1,
587
+ ),
588
+ );
589
+ const modifiers =
590
+ (event.shiftKey ? 4 : 0) |
591
+ (event.altKey ? 8 : 0) |
592
+ (event.ctrlKey ? 16 : 0);
593
+ let code: number;
594
+ let final = "M";
595
+ if (kind === "wheel") {
596
+ const wheel = event as WheelEvent;
597
+ if (Math.abs(wheel.deltaX) > Math.abs(wheel.deltaY)) {
598
+ if (wheel.deltaX === 0) return;
599
+ code = (wheel.deltaX < 0 ? 66 : 67) | modifiers;
600
+ } else {
601
+ if (wheel.deltaY === 0) return;
602
+ code = (wheel.deltaY < 0 ? 64 : 65) | modifiers;
603
+ }
604
+ } else {
605
+ const button =
606
+ kind === "move"
607
+ ? supportedButtons & 4
608
+ ? 1
609
+ : supportedButtons & 2
610
+ ? 2
611
+ : 0
612
+ : event.button === 1
613
+ ? 1
614
+ : event.button === 2
615
+ ? 2
616
+ : 0;
617
+ code = button | modifiers | (kind === "move" ? 32 : 0);
618
+ if (kind === "release") final = "m";
619
+ }
620
+ event.preventDefault();
621
+ this.onData(`\x1b[<${code};${col};${row}${final}`);
622
+ }
623
+
624
+ private stopMouseCapture(): void {
625
+ this.mouseButtons = 0;
626
+ const view = this.element.ownerDocument.defaultView;
627
+ view?.removeEventListener("mousemove", this._onMouseMove);
628
+ view?.removeEventListener("mouseup", this._onMouseUp);
629
+ }
630
+
631
+ private keyToSequence(e: KeyboardEvent): string | null {
632
+ if (e.ctrlKey && !e.altKey && !e.metaKey) {
633
+ if (e.key.length === 1) {
634
+ const code = e.key.toLowerCase().charCodeAt(0);
635
+ if (code >= 97 && code <= 122) return String.fromCharCode(code - 96);
636
+ }
637
+ if (e.key === "[") return "\x1b";
638
+ if (e.key === "\\") return "\x1c";
639
+ if (e.key === "]") return "\x1d";
640
+ if (e.key === "^") return "\x1e";
641
+ if (e.key === "_") return "\x1f";
642
+ }
643
+
644
+ if (e.key === "Enter" && e.shiftKey) return "\x1b[13;2u";
645
+ if (e.key === "Tab" && e.shiftKey) return "\x1b[Z";
646
+
647
+ const fixed = FIXED_KEYS[e.key];
648
+ if (fixed) return e.altKey ? "\x1b" + fixed : fixed;
649
+
650
+ const bridge = this.getBridge();
651
+ const appMode = bridge && bridge.cursorKeysApp();
652
+ const navMap = appMode ? APP_KEYS : NORMAL_KEYS;
653
+ const nav = navMap[e.key];
654
+ if (nav) return e.altKey ? "\x1b" + nav : nav;
655
+
656
+ if ([...e.key].length === 1 && !e.ctrlKey && !e.metaKey) {
657
+ return e.altKey ? "\x1b" + e.key : e.key;
658
+ }
659
+
660
+ return null;
661
+ }
662
+ }