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

surface.test.ts

958 lines33.3 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 terminalLinkAtPositionWithRange,
27 terminalContentOriginY,
28 terminalFontFamily,
29 terminalFontSize,
30 terminalWheelArrowData,
31 terminalWheelDeltaRows,
32 GhosttyTerminalSurface,
33 type GhosttyTerminalSurfaceOptions,
34} from "./surface";
35​
36vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
37 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
38}));
39vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
40 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
41}));
42​
43describe("GhosttyTerminalSurface visibility", () => {
44 const surfaces = new Set<GhosttyTerminalSurface>();
45​
46 // Keep the real surface, renderer, and WASM core. Only browser layout and
47 // scheduling are replaced so tests can count work while the terminal is hidden.
48 function createHarness() {
49 vi.useFakeTimers();
50 const frames = new Map<number, FrameRequestCallback>();
51 const resizeCallbacks = new Set<() => void>();
52 const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
53 let frameId = 0;
54 const requestFrame = vi.fn((callback: FrameRequestCallback) => {
55 frames.set(++frameId, callback);
56 return frameId;
57 });
58​
59 class TerminalTestElement extends EventTarget {
60 style: Record<string, string> = {};
61 parentElement: TerminalTestElement | null = null;
62 clientWidth = 168;
63 clientHeight = 104;
64 width = 300;
65 height = 150;
66 value = "";
67 private readonly captures = new Set<number>();
68​
69 setAttribute() {}
70 append(...children: TerminalTestElement[]) {
71 for (const child of children) child.parentElement = this;
72 }
73 replaceChildren(...children: TerminalTestElement[]) {
74 this.append(...children);
75 }
76 remove() {
77 this.parentElement = null;
78 }
79 getContext() {
80 return context;
81 }
82 focus() {
83 this.dispatchEvent(new Event("focus"));
84 }
85 setPointerCapture(pointerId: number) {
86 this.captures.add(pointerId);
87 }
88 hasPointerCapture(pointerId: number) {
89 return this.captures.has(pointerId);
90 }
91 releasePointerCapture(pointerId: number) {
92 this.captures.delete(pointerId);
93 }
94 getBoundingClientRect() {
95 return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
96 }
97 }
98​
99 const canvas = new TerminalTestElement();
100 const mount = new TerminalTestElement();
101 const context = {
102 canvas,
103 beginPath() {},
104 clip() {},
105 rect() {},
106 resetTransform() {},
107 restore() {},
108 save() {},
109 setTransform() {},
110 fillRect: (...args: number[]) => paint("fillRect", args),
111 strokeRect: (...args: number[]) => paint("strokeRect", args),
112 fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
113 measureText: (text: string) => ({
114 width: text.length * 8,
115 actualBoundingBoxAscent: 9,
116 actualBoundingBoxDescent: 3,
117 }),
118 };
119 vi.stubGlobal("document", {
120 createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
121 fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
122 });
123 vi.stubGlobal(
124 "window",
125 Object.assign(new EventTarget(), {
126 devicePixelRatio: 1,
127 requestAnimationFrame: requestFrame,
128 cancelAnimationFrame: (id: number) => frames.delete(id),
129 setTimeout,
130 clearTimeout,
131 setInterval,
132 clearInterval,
133 matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
134 }),
135 );
136 vi.stubGlobal(
137 "ResizeObserver",
138 class {
139 constructor(private readonly callback: () => void) {
140 resizeCallbacks.add(callback);
141 }
142 observe() {}
143 disconnect() {
144 resizeCallbacks.delete(this.callback);
145 }
146 },
147 );
148 const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
149 const onData = vi.fn<(data: string) => void>();
150​
151 return {
152 mount,
153 frames,
154 paint,
155 requestFrame,
156 snapshot,
157 onData,
158 get renderedSnapshot() {
159 const result = snapshot.mock.results.at(-1);
160 if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
161 return result.value;
162 },
163 flushFrame() {
164 const queued = [...frames.values()];
165 frames.clear();
166 for (const callback of queued) callback(0);
167 },
168 resize() {
169 for (const callback of resizeCallbacks) callback();
170 },
171 pointer(type: string, clientX: number, buttons: number) {
172 canvas.dispatchEvent(
173 Object.assign(new Event(type, { cancelable: true }), {
174 clientX,
175 clientY: 5,
176 pointerId: 1,
177 button: 0,
178 buttons,
179 }),
180 );
181 },
182 async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
183 const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
184 theme: {
185 foreground: { r: 255, g: 255, b: 255 },
186 background: { r: 0, g: 0, b: 0 },
187 cursor: { r: 255, g: 255, b: 255 },
188 },
189 onData,
190 onResize() {},
191 onSelectionChange() {},
192 beforeKey: () => false,
193 onLinkActivate() {},
194 ...options,
195 get visible() {
196 return options.visible ?? true;
197 },
198 });
199 surfaces.add(surface);
200 return surface;
201 },
202 };
203 }
204​
205 afterEach(() => {
206 for (const surface of surfaces) surface.dispose();
207 surfaces.clear();
208 vi.useRealTimers();
209 vi.unstubAllGlobals();
210 vi.restoreAllMocks();
211 });
212​
213 it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {
214 const harness = createHarness();
215 const surface = await harness.create();
216 surface.focus();
217 surface.write("ready\x1b[1 q");
218 harness.flushFrame();
219 vi.advanceTimersByTime(500);
220 harness.flushFrame();
221 surface.write("queued");
222 expect(harness.frames.size).toBe(1);
223 surface.setVisible(false);
224 expect(harness.frames.size).toBe(0);
225 expect(vi.getTimerCount()).toBe(0);
226 harness.snapshot.mockClear();
227 harness.paint.mockClear();
228 harness.requestFrame.mockClear();
229​
230 surface.write("\x1b[2J\x1b[H\x1b[3");
231 surface.write("1mhidden");
232 surface.write("η•ŒπŸ™‚\x1b[0m\x1b[5n\x1b[6n");
233 surface.fit();
234 vi.advanceTimersByTime(2_000);
235 harness.flushFrame();
236​
237 expect(harness.onData.mock.calls).toEqual([["\x1b[0n"], ["\x1b[1;11R"]]);
238 expect(harness.snapshot).not.toHaveBeenCalled();
239 expect(harness.paint).not.toHaveBeenCalled();
240 expect(harness.requestFrame).not.toHaveBeenCalled();
241​
242 surface.setVisible(true);
243 expect(harness.snapshot).toHaveBeenCalledTimes(1);
244 expect(harness.renderedSnapshot).toMatchObject({ cursorX: 10, cursorY: 0 });
245 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("hidden");
246 expect(harness.paint.mock.calls).toContainEqual(["fillRect", [84, 4, 8, 16]]);
247 expect(harness.frames.size).toBe(0);
248 });
249​
250 it("keeps the selection on reveal and applies a hidden selection clear", async () => {
251 const harness = createHarness();
252 const surface = await harness.create();
253 surface.write("hello world");
254 harness.flushFrame();
255 harness.pointer("pointerdown", 5, 1);
256 harness.pointer("pointermove", 37, 1);
257 harness.pointer("pointerup", 37, 0);
258 harness.flushFrame();
259 expect(surface.getSelection()).toBe("hello");
260 const position = surface.getSelectionPosition();
261​
262 surface.setVisible(false);
263 harness.snapshot.mockClear();
264 surface.setVisible(true);
265 expect(harness.snapshot).toHaveBeenCalledTimes(1);
266 expect(surface.getSelectionPosition()).toEqual(position);
267 expect(
268 harness.renderedSnapshot.rowData[0]?.cells.slice(0, 5).every((cell) => cell.selected),
269 ).toBe(true);
270​
271 surface.setVisible(false);
272 harness.snapshot.mockClear();
273 surface.clearSelection();
274 surface.write("!");
275 expect(harness.snapshot).not.toHaveBeenCalled();
276 surface.setVisible(true);
277 expect(harness.snapshot).toHaveBeenCalledTimes(1);
278 expect(surface.getSelection()).toBe("");
279 expect(surface.getSelectionPosition()).toBeNull();
280 expect(harness.renderedSnapshot.rowData[0]?.cells.some((cell) => cell.selected)).toBe(false);
281 });
282​
283 it("stops zero-size mounts and repaints when the same size returns", async () => {
284 const harness = createHarness();
285 const surface = await harness.create();
286 surface.focus();
287 surface.write("visible");
288 harness.flushFrame();
289 harness.snapshot.mockClear();
290 harness.paint.mockClear();
291 harness.mount.clientWidth = 0;
292 surface.write("!");
293 harness.flushFrame();
294 harness.requestFrame.mockClear();
295 for (let index = 0; index < 8; index += 1) surface.write("x");
296 vi.advanceTimersByTime(2_000);
297​
298 expect(harness.snapshot).not.toHaveBeenCalled();
299 expect(harness.paint).not.toHaveBeenCalled();
300 expect(harness.requestFrame).not.toHaveBeenCalled();
301 harness.mount.clientWidth = 168;
302 harness.resize();
303 expect(harness.snapshot).toHaveBeenCalledTimes(1);
304 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("visible!xxxxxxxx");
305 expect(harness.paint).toHaveBeenCalled();
306 });
307​
308 it.each([false, true])(
309 "uses visibility %s if it changes while WASM initializes",
310 async (visible) => {
311 const harness = createHarness();
312 let markCreated!: () => void;
313 const created = new Promise<void>((resolve) => {
314 markCreated = resolve;
315 });
316 let finishLoading!: () => void;
317 const release = new Promise<void>((resolve) => {
318 finishLoading = resolve;
319 });
320 const create = GhosttyTerminalCore.create;
321 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
322 const core = await create(...args);
323 markCreated();
324 await release;
325 return core;
326 });
327 let currentVisible = !visible;
328 const pending = harness.create({
329 get visible() {
330 return currentVisible;
331 },
332 });
333 await created;
334 currentVisible = visible;
335 harness.paint.mockClear();
336 finishLoading();
337 const surface = await pending;
338​
339 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
340 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
341 surface.write("ready\x1b[5n");
342 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
343 if (!visible) {
344 expect(harness.frames.size).toBe(0);
345 surface.setVisible(true);
346 } else {
347 harness.flushFrame();
348 }
349 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
350 },
351 );
352});
353​
354const cell = (text: string): GhosttyCell => ({
355 text,
356 wide: 0,
357 foreground: { r: 255, g: 255, b: 255 },
358 background: { r: 0, g: 0, b: 0 },
359 bold: false,
360 italic: false,
361 invisible: false,
362 strikethrough: false,
363 overline: false,
364 underline: false,
365 selected: false,
366});
367​
368describe("isTerminalAltGraphText", () => {
369 it("defers printable AltGr output to the textarea input event", () => {
370 expect(
371 isTerminalAltGraphText({
372 key: "@",
373 getModifierState: (modifier) => modifier === "AltGraph",
374 }),
375 ).toBe(true);
376 expect(
377 isTerminalAltGraphText({
378 key: "ArrowRight",
379 getModifierState: (modifier) => modifier === "AltGraph",
380 }),
381 ).toBe(false);
382 });
383});
384​
385describe("terminalGridCellAt", () => {
386 const options = {
387 bounds: { left: 100, top: 200 },
388 cols: 3,
389 rows: 2,
390 metrics: { width: 10, height: 20 },
391 padding: 4,
392 originY: 24,
393 };
394​
395 it("maps points inside the rendered grid without clamping its padding", () => {
396 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
397 x: 0,
398 y: 0,
399 });
400 expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
401 x: 2,
402 y: 1,
403 });
404 expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
405 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
406 expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
407 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
408 });
409});
410​
411describe("shouldBlinkTerminalCursor", () => {
412 const blinking = {
413 focused: true,
414 cursorBlinking: true,
415 cursorVisible: true,
416 reducedMotion: false,
417 };
418​
419 it("blinks a focused visible cursor the terminal asked to blink", () => {
420 expect(shouldBlinkTerminalCursor(blinking)).toBe(true);
421 });
422​
423 it("holds the cursor steady when blinking would be unwanted", () => {
424 // Unfocused surfaces draw a steady hollow cursor, DECSCUSR steady styles and
425 // DEC mode 12 turn blinking off, a hidden cursor has nothing to toggle, and
426 // reduced-motion readers get no permanently animating element.
427 expect(shouldBlinkTerminalCursor({ ...blinking, focused: false })).toBe(false);
428 expect(shouldBlinkTerminalCursor({ ...blinking, cursorBlinking: false })).toBe(false);
429 expect(shouldBlinkTerminalCursor({ ...blinking, cursorVisible: false })).toBe(false);
430 expect(shouldBlinkTerminalCursor({ ...blinking, reducedMotion: true })).toBe(false);
431 });
432});
433​
434describe("terminalLinkAtPositionWithRange", () => {
435 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
436 const cells = [
437 cell("πŸ™‚"),
438 cell(""),
439 ...Array.from("https://t3.codes", (character) => cell(character)),
440 ];
441 const row: GhosttyRow = {
442 cells,
443 text: cells
444 .map((value) => value.text || " ")
445 .join("")
446 .trimEnd(),
447 isWrapContinuation: false,
448 wrapsToNext: false,
449 };
450​
451 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
452 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
453 "https://t3.codes",
454 );
455 expect(terminalLinkAtPositionWithRange([row], 0, 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(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
477 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
478 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
479 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).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(terminalLinkAtPositionWithRange(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(terminalLinkAtPositionWithRange(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(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).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(terminalLinkAtPositionWithRange([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(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).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});