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