termigan 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.
@@ -0,0 +1,870 @@
1
+ import { WasmTerminalEngine, encodeModifiers } from "./wasm-bridge.js";
2
+ import { CanvasRenderer, DEFAULT_THEME } from "./canvas-renderer.js";
3
+ import { ViewportController } from "./viewport-controller.js";
4
+ import { InputController } from "./input-controller.js";
5
+ export { attachPtySocket } from "./pty-socket.js";
6
+
7
+ const textEncoder = new TextEncoder();
8
+ const DEFAULT_WASM_URL = new URL("../dist/termigan.wasm", import.meta.url);
9
+
10
+ function detectMac() {
11
+ if (typeof navigator === "undefined") {
12
+ return false;
13
+ }
14
+ const platform = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || "";
15
+ return /mac|iphone|ipad|ipod/i.test(platform);
16
+ }
17
+
18
+ export async function createTermiganViewer(container, options = {}) {
19
+ const wasmUrl = options.wasmUrl || DEFAULT_WASM_URL;
20
+ const initialCols = Math.max(1, (options.cols || 80) | 0);
21
+ const initialRows = Math.max(2, (options.rows || 24) | 0);
22
+ const scrollbackCap = options.scrollbackCap ?? 10000;
23
+ const baseFontSize = options.fontSize || 13;
24
+ const minFontSize = options.minFontSize || 6;
25
+ const isMac = options.isMac !== undefined ? Boolean(options.isMac) : detectMac();
26
+
27
+ const engine = await WasmTerminalEngine.create(wasmUrl, {
28
+ cols: initialCols,
29
+ rows: initialRows,
30
+ scrollbackCap,
31
+ });
32
+
33
+ const viewport = new ViewportController({
34
+ remoteCols: initialCols,
35
+ remoteRows: initialRows,
36
+ baseFontSize,
37
+ minFontSize,
38
+ });
39
+
40
+ const input = new InputController({ isMac });
41
+ if (typeof options.shouldHandleKey === "function") {
42
+ input.setKeyInterceptor(options.shouldHandleKey);
43
+ }
44
+
45
+ const root = document.createElement("div");
46
+ root.className = "termigan-root";
47
+ root.style.position = "relative";
48
+ root.style.overflow = "hidden";
49
+ root.style.width = "100%";
50
+ root.style.height = "100%";
51
+ root.style.boxSizing = "border-box";
52
+ root.style.outline = "none";
53
+ root.style.background = (options.theme && options.theme.background) || DEFAULT_THEME.background;
54
+ root.style.userSelect = "none";
55
+ root.style.cursor = "text";
56
+
57
+ const canvas = document.createElement("canvas");
58
+ canvas.style.display = "block";
59
+ root.appendChild(canvas);
60
+
61
+ const textarea = document.createElement("textarea");
62
+ textarea.className = "termigan-input";
63
+ textarea.setAttribute("aria-label", "Terminal input");
64
+ textarea.setAttribute("autocapitalize", "off");
65
+ textarea.setAttribute("autocomplete", "off");
66
+ textarea.setAttribute("autocorrect", "off");
67
+ textarea.setAttribute("spellcheck", "false");
68
+ textarea.rows = 1;
69
+ textarea.cols = 1;
70
+ textarea.style.position = "absolute";
71
+ textarea.style.top = "0";
72
+ textarea.style.left = "0";
73
+ textarea.style.width = "1px";
74
+ textarea.style.height = "1px";
75
+ textarea.style.padding = "0";
76
+ textarea.style.border = "0";
77
+ textarea.style.margin = "0";
78
+ textarea.style.opacity = "0";
79
+ textarea.style.overflow = "hidden";
80
+ textarea.style.resize = "none";
81
+ textarea.style.pointerEvents = "none";
82
+ textarea.style.zIndex = "-1";
83
+ root.appendChild(textarea);
84
+
85
+ container.appendChild(root);
86
+
87
+ const renderer = new CanvasRenderer(canvas, {
88
+ fontFamily: options.fontFamily,
89
+ fontSize: baseFontSize,
90
+ theme: options.theme,
91
+ });
92
+
93
+ const listeners = {
94
+ input: new Set(),
95
+ focus: new Set(),
96
+ blur: new Set(),
97
+ resize: new Set(),
98
+ expanded: new Set(),
99
+ title: new Set(),
100
+ };
101
+
102
+ let rafId = 0;
103
+ let forceFull = true;
104
+ let disposed = false;
105
+ let lastTitleSeq = 0;
106
+ let currentCols = initialCols;
107
+ let currentRows = initialRows;
108
+ let lastFrame = null;
109
+ let draggingScrollbar = false;
110
+ let mouseButtonDown = -1;
111
+ let selecting = false;
112
+ let selection = null;
113
+ let lastCopiedText = "";
114
+
115
+ function emit(kind, ...args) {
116
+ for (const fn of listeners[kind]) {
117
+ fn(...args);
118
+ }
119
+ }
120
+
121
+ function absRowFromVisible(visRow) {
122
+ if (!lastFrame || lastFrame.altScreen) {
123
+ return visRow;
124
+ }
125
+ return lastFrame.scrollbackLen - lastFrame.scrollOffset + visRow;
126
+ }
127
+
128
+ function hasActiveSelection() {
129
+ if (!selection) {
130
+ return false;
131
+ }
132
+ return (
133
+ selection.startAbsRow !== selection.endAbsRow ||
134
+ selection.startCol !== selection.endCol ||
135
+ selection.dragged
136
+ );
137
+ }
138
+
139
+ function getSelectedText() {
140
+ if (!hasActiveSelection()) {
141
+ return "";
142
+ }
143
+ return engine.getText(
144
+ selection.startAbsRow,
145
+ selection.startCol,
146
+ selection.endAbsRow,
147
+ selection.endCol,
148
+ );
149
+ }
150
+
151
+ function clearSelection() {
152
+ if (!selection) {
153
+ return;
154
+ }
155
+ selection = null;
156
+ renderer.setSelection(null);
157
+ renderer.repaintCached();
158
+ }
159
+
160
+ function positionTextareaAtCursor(frame) {
161
+ const m = renderer.metrics;
162
+ const rect = canvas.getBoundingClientRect();
163
+ const rootRect = root.getBoundingClientRect();
164
+ const scaleX = rect.width > 0 ? rect.width / Math.max(1, m.padX * 2 + m.scrollbarWidth + frame.cols * m.cellWidth) : 1;
165
+ const scaleY = rect.height > 0 ? rect.height / Math.max(1, m.padY * 2 + frame.rows * m.cellHeight) : 1;
166
+ const x = Math.max(0, Math.round((m.padX + frame.cursorCol * m.cellWidth) * scaleX));
167
+ const y = Math.max(0, Math.round((m.padY + frame.cursorRow * m.cellHeight) * scaleY));
168
+ const maxX = Math.max(0, Math.floor(rootRect.width - 2));
169
+ const maxY = Math.max(0, Math.floor(rootRect.height - 2));
170
+ textarea.style.left = `${Math.min(x, maxX)}px`;
171
+ textarea.style.top = `${Math.min(y, maxY)}px`;
172
+ }
173
+
174
+ async function copySelectionToClipboard() {
175
+ const text = getSelectedText();
176
+ if (!text) {
177
+ return false;
178
+ }
179
+ lastCopiedText = text;
180
+ if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
181
+ try {
182
+ await navigator.clipboard.writeText(text);
183
+ return true;
184
+ } catch {}
185
+ }
186
+ return true;
187
+ }
188
+
189
+ async function pasteFromClipboardApi() {
190
+ if (navigator.clipboard && typeof navigator.clipboard.readText === "function") {
191
+ try {
192
+ const text = await navigator.clipboard.readText();
193
+ if (text) {
194
+ const bytes = engine.encodePaste(text);
195
+ if (bytes.byteLength > 0) {
196
+ emit("input", bytes);
197
+ }
198
+ }
199
+ } catch {}
200
+ }
201
+ }
202
+
203
+ function measureBox() {
204
+ if (viewport.expanded) {
205
+ return {
206
+ width: Math.max(1, window.innerWidth),
207
+ height: Math.max(1, window.innerHeight),
208
+ };
209
+ }
210
+ const rect = root.getBoundingClientRect();
211
+ if (rect.width > 0 && rect.height > 0) {
212
+ return { width: rect.width, height: rect.height };
213
+ }
214
+ const parentRect = container.getBoundingClientRect();
215
+ if (parentRect.width > 0 && parentRect.height > 0) {
216
+ return { width: parentRect.width, height: parentRect.height };
217
+ }
218
+ return null;
219
+ }
220
+
221
+ function syncLayout() {
222
+ if (disposed) {
223
+ return;
224
+ }
225
+ const box = measureBox();
226
+ if (!box) {
227
+ return;
228
+ }
229
+ const layout = viewport.computeLayout(box.width, box.height, renderer.baseMetrics);
230
+ const fontChanged = renderer.setFontSize(layout.fontSize);
231
+ const gridChanged = layout.cols !== currentCols || layout.rows !== currentRows;
232
+ if (gridChanged) {
233
+ currentCols = layout.cols;
234
+ currentRows = layout.rows;
235
+ engine.resize(currentCols, currentRows);
236
+ clearSelection();
237
+ }
238
+ renderer.resizeCanvas(currentCols, currentRows, window.devicePixelRatio || 1);
239
+ const actualW = renderer.metrics.padX * 2 + renderer.metrics.scrollbarWidth + currentCols * renderer.metrics.cellWidth;
240
+ const actualH = renderer.metrics.padY * 2 + currentRows * renderer.metrics.cellHeight;
241
+ const cssScale = viewport.sizeMode === "mirror"
242
+ ? Math.min(1, box.width / Math.max(1, actualW), box.height / Math.max(1, actualH))
243
+ : 1;
244
+ renderer.setCssScale(cssScale);
245
+ if (layout.emitResize) {
246
+ emit("resize", currentCols, currentRows);
247
+ }
248
+ if (fontChanged || gridChanged) {
249
+ scheduleRender(true);
250
+ } else {
251
+ scheduleRender(false);
252
+ }
253
+ }
254
+
255
+ function flushRender() {
256
+ rafId = 0;
257
+ if (disposed) {
258
+ return;
259
+ }
260
+ const prevScrollbackLen = viewport.scrollbackLen;
261
+ const probeFrame = engine.render(viewport.scrollOffset, forceFull);
262
+ if (!probeFrame) {
263
+ return;
264
+ }
265
+ viewport.onScrollbackUpdated(probeFrame.scrollbackLen, probeFrame.altScreen);
266
+ let frame = probeFrame;
267
+ if (!probeFrame.altScreen && probeFrame.scrollbackLen !== prevScrollbackLen && viewport.scrollOffset !== probeFrame.scrollOffset) {
268
+ frame = engine.render(viewport.scrollOffset, true) || probeFrame;
269
+ }
270
+ lastFrame = frame;
271
+ renderer.renderFrame(frame, forceFull || frame.scrollOffset > 0);
272
+ positionTextareaAtCursor(frame);
273
+ forceFull = false;
274
+ if (frame.titleSeq !== lastTitleSeq) {
275
+ lastTitleSeq = frame.titleSeq;
276
+ emit("title", engine.getTitle());
277
+ }
278
+ }
279
+
280
+ function scheduleRender(full = false) {
281
+ if (disposed) {
282
+ return;
283
+ }
284
+ if (full) {
285
+ forceFull = true;
286
+ }
287
+ if (rafId === 0) {
288
+ rafId = requestAnimationFrame(flushRender);
289
+ }
290
+ }
291
+
292
+ function onTextareaFocus() {
293
+ if (input.onFocus()) {
294
+ renderer.setFocused(true);
295
+ renderer.repaintCached();
296
+ emit("focus");
297
+ }
298
+ }
299
+
300
+ function onTextareaBlur() {
301
+ if (input.onBlur()) {
302
+ textarea.value = "";
303
+ renderer.setFocused(false);
304
+ renderer.repaintCached();
305
+ emit("blur");
306
+ }
307
+ }
308
+
309
+ function onTextareaKeyDown(event) {
310
+ if (disposed) {
311
+ return;
312
+ }
313
+ const decision = input.routeKeyDown(event, { hasSelection: hasActiveSelection() });
314
+ if (decision.action === "ignore" || decision.action === "host" || decision.action === "native_paste" || decision.action === "textarea") {
315
+ return;
316
+ }
317
+ if (decision.action === "copy") {
318
+ if (hasActiveSelection()) {
319
+ event.preventDefault();
320
+ copySelectionToClipboard();
321
+ clearSelection();
322
+ }
323
+ return;
324
+ }
325
+ if (decision.action === "paste_clipboard") {
326
+ event.preventDefault();
327
+ pasteFromClipboardApi();
328
+ return;
329
+ }
330
+ if (decision.action === "encode_key") {
331
+ const bytes = engine.encodeKey(decision.keySpec);
332
+ if (bytes.byteLength > 0) {
333
+ event.preventDefault();
334
+ clearSelection();
335
+ if (viewport.scrollOffset > 0) {
336
+ viewport.scrollToBottom();
337
+ scheduleRender(true);
338
+ }
339
+ emit("input", bytes);
340
+ }
341
+ }
342
+ }
343
+
344
+ function onTextareaInput(event) {
345
+ if (disposed) {
346
+ return;
347
+ }
348
+ const text = textarea.value;
349
+ textarea.value = "";
350
+ if (!input.shouldEmitTextareaInput(Boolean(event.isComposing))) {
351
+ return;
352
+ }
353
+ if (!text) {
354
+ return;
355
+ }
356
+ clearSelection();
357
+ if (viewport.scrollOffset > 0) {
358
+ viewport.scrollToBottom();
359
+ scheduleRender(true);
360
+ }
361
+ emit("input", textEncoder.encode(text));
362
+ }
363
+
364
+ function onCompositionStart() {
365
+ if (disposed) {
366
+ return;
367
+ }
368
+ input.onCompositionStart();
369
+ }
370
+
371
+ function onCompositionEnd(event) {
372
+ if (disposed) {
373
+ return;
374
+ }
375
+ const committed = input.onCompositionEnd(event.data || textarea.value);
376
+ textarea.value = "";
377
+ if (!committed) {
378
+ return;
379
+ }
380
+ clearSelection();
381
+ if (viewport.scrollOffset > 0) {
382
+ viewport.scrollToBottom();
383
+ scheduleRender(true);
384
+ }
385
+ emit("input", textEncoder.encode(committed));
386
+ }
387
+
388
+ function onPaste(event) {
389
+ if (disposed || !input.focused) {
390
+ return;
391
+ }
392
+ const text = event.clipboardData ? event.clipboardData.getData("text/plain") : "";
393
+ event.preventDefault();
394
+ textarea.value = "";
395
+ if (!text) {
396
+ return;
397
+ }
398
+ clearSelection();
399
+ if (viewport.scrollOffset > 0) {
400
+ viewport.scrollToBottom();
401
+ scheduleRender(true);
402
+ }
403
+ const bytes = engine.encodePaste(text);
404
+ if (bytes.byteLength > 0) {
405
+ emit("input", bytes);
406
+ }
407
+ }
408
+
409
+ function onCopy(event) {
410
+ if (disposed || !hasActiveSelection()) {
411
+ return;
412
+ }
413
+ const text = getSelectedText();
414
+ if (!text) {
415
+ return;
416
+ }
417
+ lastCopiedText = text;
418
+ if (event.clipboardData) {
419
+ event.clipboardData.setData("text/plain", text);
420
+ event.preventDefault();
421
+ }
422
+ }
423
+
424
+ function onWheel(event) {
425
+ if (disposed) {
426
+ return;
427
+ }
428
+ event.preventDefault();
429
+ const rawLines = event.deltaMode === 1
430
+ ? Math.round(event.deltaY)
431
+ : event.deltaMode === 2
432
+ ? Math.round(event.deltaY * currentRows)
433
+ : Math.round(event.deltaY / 28) || (event.deltaY < 0 ? -1 : event.deltaY > 0 ? 1 : 0);
434
+ const altScreen = Boolean(lastFrame && lastFrame.altScreen);
435
+ const outcome = viewport.handleWheel(rawLines, altScreen);
436
+ if (outcome.handledAsNormalScroll) {
437
+ if (outcome.changed) {
438
+ scheduleRender(true);
439
+ }
440
+ } else if (outcome.forwardWheelLines !== 0) {
441
+ const cell = renderer.clientToCell(event.clientX, event.clientY);
442
+ const bytes = engine.encodeWheel(outcome.forwardWheelLines, cell.col, cell.row);
443
+ if (bytes.byteLength > 0) {
444
+ emit("input", bytes);
445
+ }
446
+ }
447
+ }
448
+
449
+ function selectWordAt(absRow, col) {
450
+ const line = engine.getText(absRow, 0, absRow, currentCols - 1);
451
+ const chars = Array.from(line);
452
+ const isWord = (ch) => Boolean(ch && /[A-Za-z0-9_./:-]/.test(ch));
453
+ let start = Math.min(col, Math.max(0, chars.length - 1));
454
+ let end = start;
455
+ if (isWord(chars[start])) {
456
+ while (start > 0 && isWord(chars[start - 1])) {
457
+ start--;
458
+ }
459
+ while (end + 1 < chars.length && isWord(chars[end + 1])) {
460
+ end++;
461
+ }
462
+ }
463
+ selection = {
464
+ startAbsRow: absRow,
465
+ startCol: start,
466
+ endAbsRow: absRow,
467
+ endCol: Math.min(currentCols - 1, end),
468
+ dragged: true,
469
+ };
470
+ renderer.setSelection(selection);
471
+ renderer.repaintCached();
472
+ }
473
+
474
+ function mouseEventMods(event) {
475
+ return encodeModifiers({
476
+ shift: event.shiftKey,
477
+ alt: event.altKey,
478
+ ctrl: event.ctrlKey,
479
+ meta: event.metaKey,
480
+ });
481
+ }
482
+
483
+ function onMouseDown(event) {
484
+ if (disposed) {
485
+ return;
486
+ }
487
+ event.preventDefault();
488
+ textarea.focus({ preventScroll: true });
489
+ if (event.button === 0 && renderer.isInScrollbar(event.clientX, event.clientY)) {
490
+ draggingScrollbar = true;
491
+ const offset = renderer.clientYToScrollOffset(event.clientY);
492
+ if (viewport.setScrollOffset(offset)) {
493
+ scheduleRender(true);
494
+ }
495
+ return;
496
+ }
497
+ const cell = renderer.clientToCell(event.clientX, event.clientY);
498
+ if (lastFrame && lastFrame.mouseActive && !event.shiftKey) {
499
+ const btn = event.button === 0 ? 0 : event.button === 1 ? 1 : 2;
500
+ mouseButtonDown = btn;
501
+ const bytes = engine.encodeMouse(btn, cell.col, cell.row, 0, mouseEventMods(event));
502
+ if (bytes.byteLength > 0) {
503
+ emit("input", bytes);
504
+ }
505
+ return;
506
+ }
507
+ if (event.button !== 0) {
508
+ return;
509
+ }
510
+ const absRow = absRowFromVisible(cell.row);
511
+ if (event.detail === 2) {
512
+ selectWordAt(absRow, cell.col);
513
+ selecting = false;
514
+ return;
515
+ }
516
+ if (event.detail >= 3) {
517
+ selection = {
518
+ startAbsRow: absRow,
519
+ startCol: 0,
520
+ endAbsRow: absRow,
521
+ endCol: currentCols - 1,
522
+ dragged: true,
523
+ };
524
+ renderer.setSelection(selection);
525
+ renderer.repaintCached();
526
+ selecting = false;
527
+ return;
528
+ }
529
+ selecting = true;
530
+ selection = {
531
+ startAbsRow: absRow,
532
+ startCol: cell.col,
533
+ endAbsRow: absRow,
534
+ endCol: cell.col,
535
+ dragged: false,
536
+ };
537
+ renderer.setSelection(null);
538
+ renderer.repaintCached();
539
+ }
540
+
541
+ function onWindowMouseMove(event) {
542
+ if (disposed) {
543
+ return;
544
+ }
545
+ if (draggingScrollbar) {
546
+ const offset = renderer.clientYToScrollOffset(event.clientY);
547
+ if (viewport.setScrollOffset(offset)) {
548
+ scheduleRender(true);
549
+ }
550
+ return;
551
+ }
552
+ if (mouseButtonDown >= 0 && lastFrame && lastFrame.mouseActive && !event.shiftKey) {
553
+ const cell = renderer.clientToCell(event.clientX, event.clientY);
554
+ const bytes = engine.encodeMouse(mouseButtonDown, cell.col, cell.row, 2, mouseEventMods(event));
555
+ if (bytes.byteLength > 0) {
556
+ emit("input", bytes);
557
+ }
558
+ return;
559
+ }
560
+ if (selecting && selection) {
561
+ const cell = renderer.clientToCell(event.clientX, event.clientY);
562
+ const absRow = absRowFromVisible(cell.row);
563
+ if (absRow !== selection.endAbsRow || cell.col !== selection.endCol) {
564
+ selection.endAbsRow = absRow;
565
+ selection.endCol = cell.col;
566
+ selection.dragged = true;
567
+ renderer.setSelection(selection);
568
+ renderer.repaintCached();
569
+ }
570
+ }
571
+ }
572
+
573
+ function onWindowMouseUp(event) {
574
+ if (draggingScrollbar) {
575
+ draggingScrollbar = false;
576
+ }
577
+ if (mouseButtonDown >= 0) {
578
+ const btn = mouseButtonDown;
579
+ mouseButtonDown = -1;
580
+ if (lastFrame && lastFrame.mouseActive && !disposed) {
581
+ const cell = renderer.clientToCell(event.clientX, event.clientY);
582
+ const bytes = engine.encodeMouse(btn, cell.col, cell.row, 1, mouseEventMods(event));
583
+ if (bytes.byteLength > 0) {
584
+ emit("input", bytes);
585
+ }
586
+ }
587
+ return;
588
+ }
589
+ if (selecting) {
590
+ selecting = false;
591
+ if (selection && !selection.dragged) {
592
+ clearSelection();
593
+ }
594
+ }
595
+ }
596
+
597
+ function applyExpandedStyle(expanded) {
598
+ const wasFocused = input.focused;
599
+ if (expanded) {
600
+ root.setAttribute("popover", "manual");
601
+ if (typeof root.showPopover === "function") {
602
+ try {
603
+ root.showPopover();
604
+ } catch {}
605
+ }
606
+ root.style.position = "fixed";
607
+ root.style.inset = "0";
608
+ root.style.width = "100vw";
609
+ root.style.height = "100vh";
610
+ root.style.maxWidth = "none";
611
+ root.style.maxHeight = "none";
612
+ root.style.margin = "0";
613
+ root.style.padding = "0";
614
+ root.style.border = "none";
615
+ root.style.zIndex = "2147483647";
616
+ } else {
617
+ if (typeof root.hidePopover === "function") {
618
+ try {
619
+ root.hidePopover();
620
+ } catch {}
621
+ }
622
+ root.removeAttribute("popover");
623
+ root.style.position = "relative";
624
+ root.style.inset = "";
625
+ root.style.width = "100%";
626
+ root.style.height = "100%";
627
+ root.style.maxWidth = "";
628
+ root.style.maxHeight = "";
629
+ root.style.margin = "";
630
+ root.style.padding = "";
631
+ root.style.border = "";
632
+ root.style.zIndex = "";
633
+ }
634
+ if (wasFocused) {
635
+ textarea.focus({ preventScroll: true });
636
+ }
637
+ }
638
+
639
+ const resizeObserver = new ResizeObserver(() => syncLayout());
640
+ resizeObserver.observe(root);
641
+
642
+ function onWindowResize() {
643
+ if (viewport.expanded) {
644
+ syncLayout();
645
+ }
646
+ }
647
+
648
+ textarea.addEventListener("focus", onTextareaFocus);
649
+ textarea.addEventListener("blur", onTextareaBlur);
650
+ textarea.addEventListener("keydown", onTextareaKeyDown);
651
+ textarea.addEventListener("input", onTextareaInput);
652
+ textarea.addEventListener("compositionstart", onCompositionStart);
653
+ textarea.addEventListener("compositionend", onCompositionEnd);
654
+ textarea.addEventListener("paste", onPaste);
655
+ textarea.addEventListener("copy", onCopy);
656
+ root.addEventListener("wheel", onWheel, { passive: false });
657
+ root.addEventListener("mousedown", onMouseDown);
658
+ window.addEventListener("mousemove", onWindowMouseMove);
659
+ window.addEventListener("mouseup", onWindowMouseUp);
660
+ window.addEventListener("resize", onWindowResize);
661
+
662
+ syncLayout();
663
+ flushRender();
664
+
665
+ return {
666
+ element: root,
667
+ write(bytes) {
668
+ if (disposed) {
669
+ return;
670
+ }
671
+ engine.write(bytes);
672
+ const replies = engine.takeReplies();
673
+ if (replies.byteLength > 0) {
674
+ emit("input", replies);
675
+ }
676
+ scheduleRender(false);
677
+ },
678
+ reset() {
679
+ if (disposed) {
680
+ return;
681
+ }
682
+ engine.reset();
683
+ clearSelection();
684
+ viewport.onScrollbackUpdated(0, false);
685
+ viewport.scrollToBottom();
686
+ scheduleRender(true);
687
+ },
688
+ scrollToBottom() {
689
+ if (disposed) {
690
+ return;
691
+ }
692
+ if (viewport.scrollToBottom()) {
693
+ scheduleRender(true);
694
+ }
695
+ },
696
+ setRemoteSize(cols, rows) {
697
+ if (disposed) {
698
+ return;
699
+ }
700
+ if (viewport.setRemoteSize(cols, rows)) {
701
+ syncLayout();
702
+ }
703
+ },
704
+ setSizeMode(mode) {
705
+ if (disposed) {
706
+ return;
707
+ }
708
+ if (viewport.setSizeMode(mode)) {
709
+ syncLayout();
710
+ }
711
+ },
712
+ setExpanded(expanded) {
713
+ if (disposed) {
714
+ return;
715
+ }
716
+ const next = Boolean(expanded);
717
+ if (!viewport.setExpanded(next)) {
718
+ return;
719
+ }
720
+ applyExpandedStyle(next);
721
+ syncLayout();
722
+ flushRender();
723
+ emit("expanded", next);
724
+ },
725
+ setKeyInterceptor(fn) {
726
+ input.setKeyInterceptor(fn);
727
+ },
728
+ sendKey(keySpec) {
729
+ if (disposed) {
730
+ return;
731
+ }
732
+ const bytes = engine.encodeKey(keySpec);
733
+ if (bytes.byteLength > 0) {
734
+ emit("input", bytes);
735
+ }
736
+ },
737
+ proposeFitSize() {
738
+ const box = measureBox();
739
+ if (!box) {
740
+ return { cols: currentCols, rows: currentRows };
741
+ }
742
+ return viewport.proposeFitSize(box.width, box.height, renderer.baseMetrics);
743
+ },
744
+ focus() {
745
+ if (!disposed) {
746
+ textarea.focus({ preventScroll: true });
747
+ }
748
+ },
749
+ blur() {
750
+ if (!disposed) {
751
+ textarea.blur();
752
+ }
753
+ },
754
+ onInput(fn) {
755
+ listeners.input.add(fn);
756
+ return () => listeners.input.delete(fn);
757
+ },
758
+ onFocus(fn) {
759
+ listeners.focus.add(fn);
760
+ return () => listeners.focus.delete(fn);
761
+ },
762
+ onBlur(fn) {
763
+ listeners.blur.add(fn);
764
+ return () => listeners.blur.delete(fn);
765
+ },
766
+ onResize(fn) {
767
+ listeners.resize.add(fn);
768
+ return () => listeners.resize.delete(fn);
769
+ },
770
+ onExpandedChange(fn) {
771
+ listeners.expanded.add(fn);
772
+ return () => listeners.expanded.delete(fn);
773
+ },
774
+ onTitleChange(fn) {
775
+ listeners.title.add(fn);
776
+ return () => listeners.title.delete(fn);
777
+ },
778
+ getSelectedText() {
779
+ return getSelectedText();
780
+ },
781
+ getLastCopiedText() {
782
+ return lastCopiedText;
783
+ },
784
+ getState() {
785
+ return {
786
+ cols: currentCols,
787
+ rows: currentRows,
788
+ sizeMode: viewport.sizeMode,
789
+ expanded: viewport.expanded,
790
+ scrollOffset: viewport.scrollOffset,
791
+ scrollbackLen: viewport.scrollbackLen,
792
+ fontSize: renderer.metrics.fontSize,
793
+ altScreen: Boolean(lastFrame && lastFrame.altScreen),
794
+ focused: input.focused,
795
+ };
796
+ },
797
+ dispose() {
798
+ if (disposed) {
799
+ return;
800
+ }
801
+ disposed = true;
802
+ if (rafId !== 0) {
803
+ cancelAnimationFrame(rafId);
804
+ rafId = 0;
805
+ }
806
+ resizeObserver.disconnect();
807
+ textarea.removeEventListener("focus", onTextareaFocus);
808
+ textarea.removeEventListener("blur", onTextareaBlur);
809
+ textarea.removeEventListener("keydown", onTextareaKeyDown);
810
+ textarea.removeEventListener("input", onTextareaInput);
811
+ textarea.removeEventListener("compositionstart", onCompositionStart);
812
+ textarea.removeEventListener("compositionend", onCompositionEnd);
813
+ textarea.removeEventListener("paste", onPaste);
814
+ textarea.removeEventListener("copy", onCopy);
815
+ root.removeEventListener("wheel", onWheel);
816
+ root.removeEventListener("mousedown", onMouseDown);
817
+ window.removeEventListener("mousemove", onWindowMouseMove);
818
+ window.removeEventListener("mouseup", onWindowMouseUp);
819
+ window.removeEventListener("resize", onWindowResize);
820
+ engine.dispose();
821
+ root.remove();
822
+ },
823
+ };
824
+ }
825
+
826
+ export class TermiganViewerElement extends HTMLElement {
827
+ constructor() {
828
+ super();
829
+ this._viewer = null;
830
+ this._readyPromise = null;
831
+ this._disconnected = false;
832
+ }
833
+
834
+ connectedCallback() {
835
+ this._disconnected = false;
836
+ if (!this._readyPromise) {
837
+ this.style.display = this.style.display || "block";
838
+ this.style.overflow = "hidden";
839
+ const wasmUrl = this.getAttribute("wasm-url") || DEFAULT_WASM_URL;
840
+ const cols = Number(this.getAttribute("cols")) || 80;
841
+ const rows = Number(this.getAttribute("rows")) || 24;
842
+ const fontSize = Number(this.getAttribute("font-size")) || 13;
843
+ this._readyPromise = createTermiganViewer(this, { wasmUrl, cols, rows, fontSize }).then((v) => {
844
+ if (this._disconnected) {
845
+ v.dispose();
846
+ return null;
847
+ }
848
+ this._viewer = v;
849
+ return v;
850
+ });
851
+ }
852
+ }
853
+
854
+ disconnectedCallback() {
855
+ this._disconnected = true;
856
+ if (this._viewer) {
857
+ this._viewer.dispose();
858
+ this._viewer = null;
859
+ }
860
+ this._readyPromise = null;
861
+ }
862
+
863
+ ready() {
864
+ return this._readyPromise;
865
+ }
866
+ }
867
+
868
+ if (typeof customElements !== "undefined" && !customElements.get("termigan-viewer")) {
869
+ customElements.define("termigan-viewer", TermiganViewerElement);
870
+ }