Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

surface.test.ts

958 lines33.1 KB

1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
4import {
5 DEFAULT_TERMINAL_FONT_FAMILY,
6 DEFAULT_TERMINAL_FONT_SIZE,
7 advanceTerminalSelectionClickSequence,
8 applyTerminalCopyEvent,
9 clearPrimedTerminalCopyInput,
10 ghosttyMouseButton,
11 isTerminalAltGraphText,
12 isTerminalCompositionCommitInput,
13 isTerminalCompositionKey,
14 isTerminalCopyShortcut,
15 isTerminalLinkPointerGesture,
16 isTerminalPasteShortcut,
17 loadTerminalFontFamily,
18 primeTerminalCopyInput,
19 resolveTerminalMouseData,
20 resolveTerminalMouseTrackingState,
21 shouldBlinkTerminalCursor,
22 shouldReportTerminalMouse,
23 terminalGridCellAt,
24 terminalScrollbarGeometry,
25 terminalScrollbarOffsetAtPointer,
26 terminalLinkAtColumn,
27 terminalLinkAtPosition,
28 terminalLinkAtPositionWithRange,
29 terminalContentOriginY,
30 terminalFontFamily,
31 terminalFontSize,
32 terminalWheelArrowData,
33 terminalWheelDeltaRows,
34 GhosttyTerminalSurface,
35 type GhosttyTerminalSurfaceOptions,
36} from "./surface";
37​
38vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
39 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
40}));
41vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
42 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
43}));
44​
45describe("GhosttyTerminalSurface visibility", () => {
46 const surfaces = new Set<GhosttyTerminalSurface>();
47​
48 // Keep the real surface, renderer, and WASM core. Only browser layout and
49 // scheduling are replaced so tests can count work while the terminal is hidden.
50 function createHarness() {
51 vi.useFakeTimers();
52 const frames = new Map<number, FrameRequestCallback>();
53 const resizeCallbacks = new Set<() => void>();
54 const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
55 let frameId = 0;
56 const requestFrame = vi.fn((callback: FrameRequestCallback) => {
57 frames.set(++frameId, callback);
58 return frameId;
59 });
60​
61 class TerminalTestElement extends EventTarget {
62 style: Record<string, string> = {};
63 parentElement: TerminalTestElement | null = null;
64 clientWidth = 168;
65 clientHeight = 104;
66 width = 300;
67 height = 150;
68 value = "";
69 private readonly captures = new Set<number>();
70​
71 setAttribute() {}
72 append(...children: TerminalTestElement[]) {
73 for (const child of children) child.parentElement = this;
74 }
75 replaceChildren(...children: TerminalTestElement[]) {
76 this.append(...children);
77 }
78 remove() {
79 this.parentElement = null;
80 }
81 getContext() {
82 return context;
83 }
84 focus() {
85 this.dispatchEvent(new Event("focus"));
86 }
87 setPointerCapture(pointerId: number) {
88 this.captures.add(pointerId);
89 }
90 hasPointerCapture(pointerId: number) {
91 return this.captures.has(pointerId);
92 }
93 releasePointerCapture(pointerId: number) {
94 this.captures.delete(pointerId);
95 }
96 getBoundingClientRect() {
97 return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
98 }
99 }
100​
101 const canvas = new TerminalTestElement();
102 const mount = new TerminalTestElement();
103 const context = {
104 canvas,
105 beginPath() {},
106 clip() {},
107 rect() {},
108 resetTransform() {},
109 restore() {},
110 save() {},
111 setTransform() {},
112 fillRect: (...args: number[]) => paint("fillRect", args),
113 strokeRect: (...args: number[]) => paint("strokeRect", args),
114 fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
115 measureText: (text: string) => ({
116 width: text.length * 8,
117 actualBoundingBoxAscent: 9,
118 actualBoundingBoxDescent: 3,
119 }),
120 };
121 vi.stubGlobal("document", {
122 createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
123 fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
124 });
125 vi.stubGlobal(
126 "window",
127 Object.assign(new EventTarget(), {
128 devicePixelRatio: 1,
129 requestAnimationFrame: requestFrame,
130 cancelAnimationFrame: (id: number) => frames.delete(id),
131 setTimeout,
132 clearTimeout,
133 setInterval,
134 clearInterval,
135 matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
136 }),
137 );
138 vi.stubGlobal(
139 "ResizeObserver",
140 class {
141 constructor(private readonly callback: () => void) {
142 resizeCallbacks.add(callback);
143 }
144 observe() {}
145 disconnect() {
146 resizeCallbacks.delete(this.callback);
147 }
148 },
149 );
150 const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
151 const onData = vi.fn<(data: string) => void>();
152​
153 return {
154 mount,
155 frames,
156 paint,
157 requestFrame,
158 snapshot,
159 onData,
160 get renderedSnapshot() {
161 const result = snapshot.mock.results.at(-1);
162 if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
163 return result.value;
164 },
165 flushFrame() {
166 const queued = [...frames.values()];
167 frames.clear();
168 for (const callback of queued) callback(0);
169 },
170 resize() {
171 for (const callback of resizeCallbacks) callback();
172 },
173 pointer(type: string, clientX: number, buttons: number) {
174 canvas.dispatchEvent(
175 Object.assign(new Event(type, { cancelable: true }), {
176 clientX,
177 clientY: 5,
178 pointerId: 1,
179 button: 0,
180 buttons,
181 }),
182 );
183 },
184 async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
185 const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
186 theme: {
187 foreground: { r: 255, g: 255, b: 255 },
188 background: { r: 0, g: 0, b: 0 },
189 cursor: { r: 255, g: 255, b: 255 },
190 },
191 onData,
192 onResize() {},
193 onSelectionChange() {},
194 beforeKey: () => false,
195 onLinkActivate() {},
196 ...options,
197 get visible() {
198 return options.visible ?? true;
199 },
200 });
201 surfaces.add(surface);
202 return surface;
203 },
204 };
205 }
206​
207 afterEach(() => {
208 for (const surface of surfaces) surface.dispose();
209 surfaces.clear();
210 vi.useRealTimers();
211 vi.unstubAllGlobals();
212 vi.restoreAllMocks();
213 });
214​
215 it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {
216 const harness = createHarness();
217 const surface = await harness.create();
218 surface.focus();
219 surface.write("ready\x1b[1 q");
220 harness.flushFrame();
221 vi.advanceTimersByTime(500);
222 harness.flushFrame();
223 surface.write("queued");
224 expect(harness.frames.size).toBe(1);
225 surface.setVisible(false);
226 expect(harness.frames.size).toBe(0);
227 expect(vi.getTimerCount()).toBe(0);
228 harness.snapshot.mockClear();
229 harness.paint.mockClear();
230 harness.requestFrame.mockClear();
231​
232 surface.write("\x1b[2J\x1b[H\x1b[3");
233 surface.write("1mhidden");
234 surface.write("η•ŒπŸ™‚\x1b[0m\x1b[5n\x1b[6n");
235 surface.fit();
236 vi.advanceTimersByTime(2_000);
237 harness.flushFrame();
238​
239 expect(harness.onData.mock.calls).toEqual([["\x1b[0n"], ["\x1b[1;11R"]]);
240 expect(harness.snapshot).not.toHaveBeenCalled();
241 expect(harness.paint).not.toHaveBeenCalled();
242 expect(harness.requestFrame).not.toHaveBeenCalled();
243​
244 surface.setVisible(true);
245 expect(harness.snapshot).toHaveBeenCalledTimes(1);
246 expect(harness.renderedSnapshot).toMatchObject({ cursorX: 10, cursorY: 0 });
247 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("hidden");
248 expect(harness.paint.mock.calls).toContainEqual(["fillRect", [84, 4, 8, 16]]);
249 expect(harness.frames.size).toBe(0);
250 });
251​
252 it("keeps the selection on reveal and applies a hidden selection clear", async () => {
253 const harness = createHarness();
254 const surface = await harness.create();
255 surface.write("hello world");
256 harness.flushFrame();
257 harness.pointer("pointerdown", 5, 1);
258 harness.pointer("pointermove", 37, 1);
259 harness.pointer("pointerup", 37, 0);
260 harness.flushFrame();
261 expect(surface.getSelection()).toBe("hello");
262 const position = surface.getSelectionPosition();
263​
264 surface.setVisible(false);
265 harness.snapshot.mockClear();
266 surface.setVisible(true);
267 expect(harness.snapshot).toHaveBeenCalledTimes(1);
268 expect(surface.getSelectionPosition()).toEqual(position);
269 expect(
270 harness.renderedSnapshot.rowData[0]?.cells.slice(0, 5).every((cell) => cell.selected),
271 ).toBe(true);
272​
273 surface.setVisible(false);
274 harness.snapshot.mockClear();
275 surface.clearSelection();
276 surface.write("!");
277 expect(harness.snapshot).not.toHaveBeenCalled();
278 surface.setVisible(true);
279 expect(harness.snapshot).toHaveBeenCalledTimes(1);
280 expect(surface.getSelection()).toBe("");
281 expect(surface.getSelectionPosition()).toBeNull();
282 expect(harness.renderedSnapshot.rowData[0]?.cells.some((cell) => cell.selected)).toBe(false);
283 });
284​
285 it("stops zero-size mounts and repaints when the same size returns", async () => {
286 const harness = createHarness();
287 const surface = await harness.create();
288 surface.focus();
289 surface.write("visible");
290 harness.flushFrame();
291 harness.snapshot.mockClear();
292 harness.paint.mockClear();
293 harness.mount.clientWidth = 0;
294 surface.write("!");
295 harness.flushFrame();
296 harness.requestFrame.mockClear();
297 for (let index = 0; index < 8; index += 1) surface.write("x");
298 vi.advanceTimersByTime(2_000);
299​
300 expect(harness.snapshot).not.toHaveBeenCalled();
301 expect(harness.paint).not.toHaveBeenCalled();
302 expect(harness.requestFrame).not.toHaveBeenCalled();
303 harness.mount.clientWidth = 168;
304 harness.resize();
305 expect(harness.snapshot).toHaveBeenCalledTimes(1);
306 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("visible!xxxxxxxx");
307 expect(harness.paint).toHaveBeenCalled();
308 });
309​
310 it.each([false, true])(
311 "uses visibility %s if it changes while WASM initializes",
312 async (visible) => {
313 const harness = createHarness();
314 let markCreated!: () => void;
315 const created = new Promise<void>((resolve) => {
316 markCreated = resolve;
317 });
318 let finishLoading!: () => void;
319 const release = new Promise<void>((resolve) => {
320 finishLoading = resolve;
321 });
322 const create = GhosttyTerminalCore.create;
323 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
324 const core = await create(...args);
325 markCreated();
326 await release;
327 return core;
328 });
329 let currentVisible = !visible;
330 const pending = harness.create({
331 get visible() {
332 return currentVisible;
333 },
334 });
335 await created;
336 currentVisible = visible;
337 harness.paint.mockClear();
338 finishLoading();
339 const surface = await pending;
340​
341 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
342 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
343 surface.write("ready\x1b[5n");
344 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
345 if (!visible) {
346 expect(harness.frames.size).toBe(0);
347 surface.setVisible(true);
348 } else {
349 harness.flushFrame();
350 }
351 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
352 },
353 );
354});
355​
356const cell = (text: string): GhosttyCell => ({
357 text,
358 wide: 0,
359 foreground: { r: 255, g: 255, b: 255 },
360 background: { r: 0, g: 0, b: 0 },
361 bold: false,
362 italic: false,
363 invisible: false,
364 strikethrough: false,
365 overline: false,
366 underline: false,
367 selected: false,
368});
369​
370describe("isTerminalAltGraphText", () => {
371 it("defers printable AltGr output to the textarea input event", () => {
372 expect(
373 isTerminalAltGraphText({
374 key: "@",
375 getModifierState: (modifier) => modifier === "AltGraph",
376 }),
377 ).toBe(true);
378 expect(
379 isTerminalAltGraphText({
380 key: "ArrowRight",
381 getModifierState: (modifier) => modifier === "AltGraph",
382 }),
383 ).toBe(false);
384 });
385});
386​
387describe("terminalGridCellAt", () => {
388 const options = {
389 bounds: { left: 100, top: 200 },
390 cols: 3,
391 rows: 2,
392 metrics: { width: 10, height: 20 },
393 padding: 4,
394 originY: 24,
395 };
396​
397 it("maps points inside the rendered grid without clamping its padding", () => {
398 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
399 x: 0,
400 y: 0,
401 });
402 expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
403 x: 2,
404 y: 1,
405 });
406 expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
407 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
408 expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
409 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
410 });
411});
412​
413describe("shouldBlinkTerminalCursor", () => {
414 const blinking = {
415 focused: true,
416 cursorBlinking: true,
417 cursorVisible: true,
418 reducedMotion: false,
419 };
420​
421 it("blinks a focused visible cursor the terminal asked to blink", () => {
422 expect(shouldBlinkTerminalCursor(blinking)).toBe(true);
423 });
424​
425 it("holds the cursor steady when blinking would be unwanted", () => {
426 // Unfocused surfaces draw a steady hollow cursor, DECSCUSR steady styles and
427 // DEC mode 12 turn blinking off, a hidden cursor has nothing to toggle, and
428 // reduced-motion readers get no permanently animating element.
429 expect(shouldBlinkTerminalCursor({ ...blinking, focused: false })).toBe(false);
430 expect(shouldBlinkTerminalCursor({ ...blinking, cursorBlinking: false })).toBe(false);
431 expect(shouldBlinkTerminalCursor({ ...blinking, cursorVisible: false })).toBe(false);
432 expect(shouldBlinkTerminalCursor({ ...blinking, reducedMotion: true })).toBe(false);
433 });
434});
435​
436describe("terminalLinkAtColumn", () => {
437 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
438 const cells = [
439 cell("πŸ™‚"),
440 cell(""),
441 ...Array.from("https://t3.codes", (character) => cell(character)),
442 ];
443 const row: GhosttyRow = {
444 cells,
445 text: cells
446 .map((value) => value.text || " ")
447 .join("")
448 .trimEnd(),
449 isWrapContinuation: false,
450 wrapsToNext: false,
451 };
452​
453 expect(terminalLinkAtColumn(row, 2)).toBe("https://t3.codes");
454 expect(terminalLinkAtColumn(row, cells.length - 1)).toBe("https://t3.codes");
455 expect(terminalLinkAtColumn(row, 0)).toBeNull();
456 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
457 start: { x: 2, y: 0 },
458 end: { x: cells.length - 1, y: 0 },
459 });
460 });
461​
462 it("uses shared path matching and reconstructs soft-wrapped links", () => {
463 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
464 cells: Array.from(text.padEnd(16), (character) => cell(character)),
465 text: text.trimEnd(),
466 isWrapContinuation,
467 wrapsToNext,
468 });
469 const rows = [
470 row("https://example.", false),
471 row("com/reference", true),
472 row("~/project/file", false),
473 row("C:\\repo\\file.ts", false),
474 ];
475​
476 expect(terminalLinkAtPosition(rows, 0, 8)).toBe("https://example.com/reference");
477 expect(terminalLinkAtPosition(rows, 1, 4)).toBe("https://example.com/reference");
478 expect(terminalLinkAtPosition(rows, 2, 2)).toBe("~/project/file");
479 expect(terminalLinkAtPosition(rows, 3, 4)).toBe("C:\\repo\\file.ts");
480 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
481 text: "https://example.com/reference",
482 range: {
483 start: { x: 0, y: 0 },
484 end: { x: 12, y: 1 },
485 },
486 });
487 });
488​
489 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
490 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
491 cells: Array.from(text.padEnd(16), (character) => cell(character)),
492 text: text.trimEnd(),
493 isWrapContinuation,
494 wrapsToNext,
495 });
496 // The head of the wrapped line scrolled above the viewport.
497 const headCut = [row("ple.com/missing", true), row("head", true)];
498 expect(terminalLinkAtPosition(headCut, 0, 4)).toBeNull();
499 // The bottom row soft-wraps on below the viewport.
500 const tailCut = [row("https://t3.codes", false, true)];
501 expect(terminalLinkAtPosition(tailCut, 0, 8)).toBeNull();
502 // A partial bottom row is provably complete and still resolves.
503 const complete = [row("https://t3.codes", false), row("", false)];
504 expect(terminalLinkAtPosition(complete, 0, 8)).toBe("https://t3.codes");
505 // A wide grapheme earlier in the row must not break truncation detection:
506 // the soft-wrap flag decides, not string-length-versus-cell-count.
507 const wideFull: GhosttyRow = {
508 cells: [
509 { ...cell("πŸ™‚"), wide: 1 },
510 { ...cell(""), wide: 2 },
511 ...Array.from("https://t3.code", (character) => cell(character)),
512 ],
513 text: "πŸ™‚ https://t3.code",
514 isWrapContinuation: false,
515 wrapsToNext: true,
516 };
517 expect(terminalLinkAtPosition([wideFull], 0, 8)).toBeNull();
518 // Unwritten trailing cells prove the bottom row is complete.
519 const unwrittenTail: GhosttyRow = {
520 cells: [
521 ...Array.from("https://t3.codes", (character) => cell(character)),
522 cell(""),
523 cell(""),
524 ],
525 text: "https://t3.codes",
526 isWrapContinuation: false,
527 wrapsToNext: false,
528 };
529 expect(terminalLinkAtPosition([unwrittenTail], 0, 8)).toBe("https://t3.codes");
530 });
531});
532​
533describe("isTerminalCopyShortcut", () => {
534 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
535 ctrlKey: false,
536 key: "c",
537 metaKey: false,
538 shiftKey: false,
539 ...overrides,
540 });
541​
542 it("keeps Ctrl+C available for SIGINT on macOS", () => {
543 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
544 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
545 });
546​
547 it("copies with Ctrl+C and Ctrl+Shift+C elsewhere", () => {
548 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(true);
549 expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
550 true,
551 );
552 expect(isTerminalCopyShortcut(event({}), "Linux x86_64")).toBe(false);
553 });
554​
555 it("uses the produced character instead of the physical key position", () => {
556 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
557 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
558 });
559});
560​
561describe("applyTerminalCopyEvent", () => {
562 it("writes the selection and claims the fallback when clipboardData is present", () => {
563 const setData = vi.fn();
564 expect(applyTerminalCopyEvent("ls -la", { setData })).toEqual({
565 preventDefault: true,
566 claimWriteFallback: true,
567 });
568 expect(setData).toHaveBeenCalledWith("text/plain", "ls -la");
569 });
570​
571 it("leaves the writeText fallback alive when clipboardData is missing", () => {
572 // Electron's edit-menu Copy often delivers a copy event with no
573 // clipboardData. Claiming that event used to skip writeText and copy the
574 // empty IME textarea, which is the blank clipboard users paste.
575 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
576 preventDefault: false,
577 claimWriteFallback: false,
578 });
579 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
580 preventDefault: false,
581 claimWriteFallback: false,
582 });
583 });
584​
585 it("primes the current selection before a copy event with no clipboardData", () => {
586 const input = {
587 value: "stale",
588 selectionStart: 0,
589 selectionEnd: 0,
590 select() {
591 this.selectionStart = 0;
592 this.selectionEnd = this.value.length;
593 },
594 };
595 primeTerminalCopyInput(input, "git status");
596 expect(applyTerminalCopyEvent("git status", null)).toEqual({
597 preventDefault: false,
598 claimWriteFallback: false,
599 });
600 expect(input.value).toBe("git status");
601 expect(input.selectionStart).toBe(0);
602 expect(input.selectionEnd).toBe(10);
603 });
604});
605​
606describe("primeTerminalCopyInput", () => {
607 it("selects the Ghostty selection in the hidden textarea so native copy has text", () => {
608 const input = {
609 value: "",
610 selectionStart: 0,
611 selectionEnd: 0,
612 select() {
613 this.selectionStart = 0;
614 this.selectionEnd = this.value.length;
615 },
616 };
617 primeTerminalCopyInput(input, "git status");
618 expect(input.value).toBe("git status");
619 expect(input.selectionStart).toBe(0);
620 expect(input.selectionEnd).toBe(10);
621 clearPrimedTerminalCopyInput(input, "git status");
622 expect(input.value).toBe("");
623 });
624​
625 it("does not wipe an IME candidate that replaced the primed copy", () => {
626 const input = { value: "", select() {} };
627 primeTerminalCopyInput(input, "git status");
628 input.value = "あ";
629 clearPrimedTerminalCopyInput(input, "git status");
630 expect(input.value).toBe("あ");
631 });
632});
633​
634describe("isTerminalPasteShortcut", () => {
635 const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
636 ctrlKey: false,
637 key: "v",
638 metaKey: false,
639 shiftKey: false,
640 ...overrides,
641 });
642​
643 it("uses Cmd+V on macOS", () => {
644 expect(isTerminalPasteShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
645 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
646 });
647​
648 it("preserves Ctrl+V and uses Ctrl+Shift+V elsewhere", () => {
649 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
650 expect(isTerminalPasteShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
651 true,
652 );
653 });
654​
655 it("supports the conventional Shift+Insert paste shortcut", () => {
656 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "Linux x86_64")).toBe(
657 true,
658 );
659 expect(isTerminalPasteShortcut(event({ key: "Insert" }), "Linux x86_64")).toBe(false);
660 expect(
661 isTerminalPasteShortcut(
662 event({ key: "Insert", ctrlKey: true, shiftKey: true }),
663 "Linux x86_64",
664 ),
665 ).toBe(false);
666 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "MacIntel")).toBe(
667 false,
668 );
669 });
670});
671​
672describe("isTerminalCompositionCommitInput", () => {
673 it("identifies browser composition follow-up input", () => {
674 expect(isTerminalCompositionCommitInput({ inputType: "" })).toBe(true);
675 expect(isTerminalCompositionCommitInput({ inputType: "insertCompositionText" })).toBe(true);
676 expect(isTerminalCompositionCommitInput({ inputType: "insertFromComposition" })).toBe(true);
677 });
678​
679 it("keeps a fast repeated input as legitimate text", () => {
680 expect(isTerminalCompositionCommitInput({ inputType: "insertText" })).toBe(false);
681 });
682});
683​
684describe("isTerminalCompositionKey", () => {
685 const event = (
686 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
687 ) => ({
688 isComposing: false,
689 key: "a",
690 keyCode: 65,
691 ...overrides,
692 });
693​
694 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
695 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
696 expect(isTerminalCompositionKey(event(), true)).toBe(true);
697 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
698 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
699 });
700​
701 it("lets ordinary keydowns clear a primed copy", () => {
702 expect(isTerminalCompositionKey(event(), false)).toBe(false);
703 });
704});
705​
706describe("application mouse reporting", () => {
707 const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
708 ctrlKey: false,
709 metaKey: false,
710 shiftKey: false,
711 ...overrides,
712 });
713​
714 it("keeps Shift and link activation modifiers available to the browser", () => {
715 expect(shouldReportTerminalMouse(true, event())).toBe(true);
716 expect(shouldReportTerminalMouse(true, event({ shiftKey: true }))).toBe(false);
717 expect(shouldReportTerminalMouse(true, event({ ctrlKey: true }))).toBe(false);
718 expect(shouldReportTerminalMouse(true, event({ metaKey: true }))).toBe(false);
719 expect(shouldReportTerminalMouse(false, event())).toBe(false);
720 });
721​
722 it("maps browser buttons to Ghostty's button enum", () => {
723 expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
724 });
725​
726 it("drops repeated motion reports until another mouse action resets the cell", () => {
727 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
728 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
729​
730 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
731 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
732​
733 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
734 expect(press).toEqual({ send: true, nextMotionData: "" });
735​
736 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
737 send: true,
738 nextMotionData: "\u001b[<35;8;4M",
739 });
740 });
741​
742 it("clears the motion baseline when application mouse tracking changes", () => {
743 expect(resolveTerminalMouseTrackingState(true, false, "\u001b[<35;8;4M")).toEqual({
744 tracking: false,
745 motionData: "",
746 });
747 expect(resolveTerminalMouseTrackingState(false, true, "\u001b[<35;8;4M")).toEqual({
748 tracking: true,
749 motionData: "",
750 });
751 expect(resolveTerminalMouseTrackingState(true, true, "\u001b[<35;8;4M")).toEqual({
752 tracking: true,
753 motionData: "\u001b[<35;8;4M",
754 });
755 expect(resolveTerminalMouseTrackingState(false, false, "\u001b[<35;8;4M")).toEqual({
756 tracking: false,
757 motionData: "\u001b[<35;8;4M",
758 });
759 });
760});
761​
762describe("terminal font resolution", () => {
763 it("validates the requested face after its styles load", async () => {
764 let loaded = false;
765 const load = vi.fn(async () => {
766 loaded = true;
767 return [];
768 });
769 const resolve = vi.fn(() => {
770 expect(loaded).toBe(true);
771 return DEFAULT_TERMINAL_FONT_FAMILY;
772 });
773​
774 await expect(
775 loadTerminalFontFamily("Proportional Test", 12, {
776 load,
777 resolve,
778 }),
779 ).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
780 expect(load).toHaveBeenCalledTimes(4);
781 expect(resolve).toHaveBeenCalledWith("Proportional Test");
782 });
783​
784 it("keeps the glyph fallbacks behind a custom text face", () => {
785 expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
786 expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
787 const custom = terminalFontFamily('"Fira Code"');
788 expect(custom.startsWith('"Fira Code", ')).toBe(true);
789 expect(custom).toContain('"Symbols Nerd Font Mono"');
790 expect(custom.endsWith("monospace")).toBe(true);
791 });
792​
793 it("ignores proportional families the cell grid cannot lay out", () => {
794 // jsdom has no canvas metrics, so the probe answers "monospace" and the
795 // family is kept; the guard is exercised in the browser instead. Assert the
796 // shape stays intact so a rejected face still yields a usable stack.
797 const stack = terminalFontFamily("Helvetica Neue");
798 expect(stack.endsWith("monospace")).toBe(true);
799 });
800​
801 it("quotes families the canvas font shorthand would otherwise reject", () => {
802 expect(terminalFontFamily("3270 Nerd Font").startsWith('"3270 Nerd Font", ')).toBe(true);
803 expect(terminalFontFamily("M+ 1m").startsWith('"M+ 1m", ')).toBe(true);
804 expect(terminalFontFamily("Cascadia Code, Menlo").startsWith('"Cascadia Code", Menlo, ')).toBe(
805 true,
806 );
807 expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
808 });
809​
810 it("clamps requested font sizes to the supported range", () => {
811 expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
812 expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
813 expect(terminalFontSize(13.4)).toBe(13);
814 expect(terminalFontSize(2)).toBe(6);
815 expect(terminalFontSize(90)).toBe(32);
816 });
817});
818​
819describe("terminalContentOriginY", () => {
820 it("stays top-anchored like a fresh terminal until scrollback exists", () => {
821 expect(terminalContentOriginY(100, 4, 5, 16, false)).toBe(4);
822 });
823​
824 it("pins the grid to the bottom by moving the sub-row slack above row 0", () => {
825 // 100px mount, 4px padding, 5 rows of 16px: 92 - 80 = 12px slack on top.
826 expect(terminalContentOriginY(100, 4, 5, 16, true)).toBe(16);
827 // Exact fit keeps the origin at the padding.
828 expect(terminalContentOriginY(88, 4, 5, 16, true)).toBe(4);
829 // A mount smaller than the grid never pushes the origin above the padding.
830 expect(terminalContentOriginY(80, 4, 5, 16, true)).toBe(4);
831 });
832​
833 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
834 // Growing the mount pixel by pixel: the bottom edge (origin + rows*cell)
835 // tracks the mount bottom exactly until a new row fits.
836 for (let height = 88; height < 104; height += 1) {
837 const rows = Math.max(1, Math.floor((height - 8) / 16));
838 const origin = terminalContentOriginY(height, 4, rows, 16, true);
839 expect(origin + rows * 16).toBe(height - 4);
840 }
841 });
842});
843​
844describe("terminalWheelDeltaRows", () => {
845 it("converts line-mode deltas into whole rows", () => {
846 const result = terminalWheelDeltaRows({ deltaY: 3, deltaMode: 1 }, 16, 24, 0);
847 expect(result.rows).toBe(3);
848 expect(result.remainder).toBe(0);
849 });
850​
851 it("accumulates fractional pixel deltas across events", () => {
852 let remainder = 0;
853 let scrolled = 0;
854 for (let index = 0; index < 4; index += 1) {
855 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
856 remainder = result.remainder;
857 scrolled += result.rows;
858 }
859 expect(scrolled).toBe(1);
860 expect(remainder).toBeCloseTo(4 / 16);
861 });
862​
863 it("keeps direction for negative page-mode deltas", () => {
864 const result = terminalWheelDeltaRows({ deltaY: -1, deltaMode: 2 }, 16, 24, 0);
865 expect(result.rows).toBe(-24);
866 expect(result.remainder).toBe(0);
867 });
868});
869​
870describe("terminalWheelArrowData", () => {
871 it("emits one arrow per row honoring application cursor keys", () => {
872 expect(terminalWheelArrowData(-2, false)).toBe("\u001b[A\u001b[A");
873 expect(terminalWheelArrowData(3, false)).toBe("\u001b[B\u001b[B\u001b[B");
874 expect(terminalWheelArrowData(-1, true)).toBe("\u001bOA");
875 expect(terminalWheelArrowData(0, true)).toBe("");
876 });
877});
878​
879describe("isTerminalLinkPointerGesture", () => {
880 it("uses Command on macOS and Control elsewhere", () => {
881 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "MacIntel")).toBe(true);
882 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "MacIntel")).toBe(false);
883 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "Linux x86_64")).toBe(
884 true,
885 );
886 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "Linux x86_64")).toBe(
887 false,
888 );
889 });
890});
891​
892describe("advanceTerminalSelectionClickSequence", () => {
893 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
894 const first = advanceTerminalSelectionClickSequence(null, {
895 clientX: 20,
896 clientY: 30,
897 timeStamp: 1_000,
898 });
899 const second = advanceTerminalSelectionClickSequence(first, {
900 clientX: 22,
901 clientY: 29,
902 timeStamp: 1_200,
903 });
904 const third = advanceTerminalSelectionClickSequence(second, {
905 clientX: 21,
906 clientY: 31,
907 timeStamp: 1_400,
908 });
909​
910 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
911 });
912​
913 it("starts over after movement, delay, or a completed triple click", () => {
914 const previous = { count: 3, time: 1_000, x: 20, y: 30 };
915 expect(
916 advanceTerminalSelectionClickSequence(previous, {
917 clientX: 20,
918 clientY: 30,
919 timeStamp: 1_100,
920 }).count,
921 ).toBe(1);
922 expect(
923 advanceTerminalSelectionClickSequence(previous, {
924 clientX: 30,
925 clientY: 30,
926 timeStamp: 1_100,
927 }).count,
928 ).toBe(1);
929 expect(
930 advanceTerminalSelectionClickSequence(previous, {
931 clientX: 20,
932 clientY: 30,
933 timeStamp: 1_501,
934 }).count,
935 ).toBe(1);
936 });
937});
938​
939describe("terminal scrollbar", () => {
940 it("maps Ghostty's viewport state to a proportional thumb", () => {
941 expect(terminalScrollbarGeometry({ total: 100, offset: 40, len: 20 }, 200)).toEqual({
942 thumbHeight: 40,
943 thumbTop: 80,
944 maxOffset: 80,
945 });
946 expect(terminalScrollbarGeometry({ total: 100, offset: 0, len: 100 }, 200)).toBeNull();
947 });
948​
949 it("keeps the thumb usable for large scrollback and maps dragging back to rows", () => {
950 const state = { total: 10_000, offset: 0, len: 20 };
951 expect(terminalScrollbarGeometry(state, 200)).toEqual({
952 thumbHeight: 18,
953 thumbTop: 0,
954 maxOffset: 9_980,
955 });
956 expect(terminalScrollbarOffsetAtPointer(state, 200, 191, 9)).toBe(9_980);
957 });
958});