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 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 it("supports the conventional Ctrl+Insert copy shortcut", () => {
561 expect(isTerminalCopyShortcut(event({ key: "Insert", ctrlKey: true }), "Linux x86_64")).toBe(
562 true,
563 );
564 expect(isTerminalCopyShortcut(event({ key: "Insert" }), "Linux x86_64")).toBe(false);
565 expect(
566 isTerminalCopyShortcut(
567 event({ key: "Insert", ctrlKey: true, shiftKey: true }),
568 "Linux x86_64",
569 ),
570 ).toBe(false);
571 expect(isTerminalCopyShortcut(event({ key: "Insert", ctrlKey: true }), "MacIntel")).toBe(false);
572 });
573});
574β
575describe("applyTerminalCopyEvent", () => {
576 it("writes the selection and claims the fallback when clipboardData is present", () => {
577 const setData = vi.fn();
578 expect(applyTerminalCopyEvent("ls -la", { setData })).toEqual({
579 preventDefault: true,
580 claimWriteFallback: true,
581 });
582 expect(setData).toHaveBeenCalledWith("text/plain", "ls -la");
583 });
584β
585 it("leaves the writeText fallback alive when clipboardData is missing", () => {
586 // Electron's edit-menu Copy often delivers a copy event with no
587 // clipboardData. Claiming that event used to skip writeText and copy the
588 // empty IME textarea, which is the blank clipboard users paste.
589 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
590 preventDefault: false,
591 claimWriteFallback: false,
592 });
593 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
594 preventDefault: false,
595 claimWriteFallback: false,
596 });
597 });
598β
599 it("primes the current selection before a copy event with no clipboardData", () => {
600 const input = {
601 value: "stale",
602 selectionStart: 0,
603 selectionEnd: 0,
604 select() {
605 this.selectionStart = 0;
606 this.selectionEnd = this.value.length;
607 },
608 };
609 primeTerminalCopyInput(input, "git status");
610 expect(applyTerminalCopyEvent("git status", null)).toEqual({
611 preventDefault: false,
612 claimWriteFallback: false,
613 });
614 expect(input.value).toBe("git status");
615 expect(input.selectionStart).toBe(0);
616 expect(input.selectionEnd).toBe(10);
617 });
618});
619β
620describe("primeTerminalCopyInput", () => {
621 it("selects the Ghostty selection in the hidden textarea so native copy has text", () => {
622 const input = {
623 value: "",
624 selectionStart: 0,
625 selectionEnd: 0,
626 select() {
627 this.selectionStart = 0;
628 this.selectionEnd = this.value.length;
629 },
630 };
631 primeTerminalCopyInput(input, "git status");
632 expect(input.value).toBe("git status");
633 expect(input.selectionStart).toBe(0);
634 expect(input.selectionEnd).toBe(10);
635 clearPrimedTerminalCopyInput(input, "git status");
636 expect(input.value).toBe("");
637 });
638β
639 it("does not wipe an IME candidate that replaced the primed copy", () => {
640 const input = { value: "", select() {} };
641 primeTerminalCopyInput(input, "git status");
642 input.value = "γ";
643 clearPrimedTerminalCopyInput(input, "git status");
644 expect(input.value).toBe("γ");
645 });
646});
647β
648describe("isTerminalPasteShortcut", () => {
649 const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
650 ctrlKey: false,
651 key: "v",
652 metaKey: false,
653 shiftKey: false,
654 ...overrides,
655 });
656β
657 it("uses Cmd+V on macOS", () => {
658 expect(isTerminalPasteShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
659 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
660 });
661β
662 it("preserves Ctrl+V and uses Ctrl+Shift+V elsewhere", () => {
663 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
664 expect(isTerminalPasteShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
665 true,
666 );
667 });
668β
669 it("supports the conventional Shift+Insert paste shortcut", () => {
670 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "Linux x86_64")).toBe(
671 true,
672 );
673 expect(isTerminalPasteShortcut(event({ key: "Insert" }), "Linux x86_64")).toBe(false);
674 expect(
675 isTerminalPasteShortcut(
676 event({ key: "Insert", ctrlKey: true, shiftKey: true }),
677 "Linux x86_64",
678 ),
679 ).toBe(false);
680 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "MacIntel")).toBe(
681 false,
682 );
683 });
684});
685β
686describe("isTerminalCompositionCommitInput", () => {
687 it("identifies browser composition follow-up input", () => {
688 expect(isTerminalCompositionCommitInput({ inputType: "" })).toBe(true);
689 expect(isTerminalCompositionCommitInput({ inputType: "insertCompositionText" })).toBe(true);
690 expect(isTerminalCompositionCommitInput({ inputType: "insertFromComposition" })).toBe(true);
691 });
692β
693 it("keeps a fast repeated input as legitimate text", () => {
694 expect(isTerminalCompositionCommitInput({ inputType: "insertText" })).toBe(false);
695 });
696});
697β
698describe("isTerminalCompositionKey", () => {
699 const event = (
700 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
701 ) => ({
702 isComposing: false,
703 key: "a",
704 keyCode: 65,
705 ...overrides,
706 });
707β
708 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
709 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
710 expect(isTerminalCompositionKey(event(), true)).toBe(true);
711 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
712 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
713 });
714β
715 it("lets ordinary keydowns clear a primed copy", () => {
716 expect(isTerminalCompositionKey(event(), false)).toBe(false);
717 });
718});
719β
720describe("application mouse reporting", () => {
721 const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
722 ctrlKey: false,
723 metaKey: false,
724 shiftKey: false,
725 ...overrides,
726 });
727β
728 it("keeps Shift and link activation modifiers available to the browser", () => {
729 expect(shouldReportTerminalMouse(true, event())).toBe(true);
730 expect(shouldReportTerminalMouse(true, event({ shiftKey: true }))).toBe(false);
731 expect(shouldReportTerminalMouse(true, event({ ctrlKey: true }))).toBe(false);
732 expect(shouldReportTerminalMouse(true, event({ metaKey: true }))).toBe(false);
733 expect(shouldReportTerminalMouse(false, event())).toBe(false);
734 });
735β
736 it("maps browser buttons to Ghostty's button enum", () => {
737 expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
738 });
739β
740 it("drops repeated motion reports until another mouse action resets the cell", () => {
741 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
742 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
743β
744 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
745 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
746β
747 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
748 expect(press).toEqual({ send: true, nextMotionData: "" });
749β
750 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
751 send: true,
752 nextMotionData: "\u001b[<35;8;4M",
753 });
754 });
755β
756 it("clears the motion baseline when application mouse tracking changes", () => {
757 expect(resolveTerminalMouseTrackingState(true, false, "\u001b[<35;8;4M")).toEqual({
758 tracking: false,
759 motionData: "",
760 });
761 expect(resolveTerminalMouseTrackingState(false, true, "\u001b[<35;8;4M")).toEqual({
762 tracking: true,
763 motionData: "",
764 });
765 expect(resolveTerminalMouseTrackingState(true, true, "\u001b[<35;8;4M")).toEqual({
766 tracking: true,
767 motionData: "\u001b[<35;8;4M",
768 });
769 expect(resolveTerminalMouseTrackingState(false, false, "\u001b[<35;8;4M")).toEqual({
770 tracking: false,
771 motionData: "\u001b[<35;8;4M",
772 });
773 });
774});
775β
776describe("terminal font resolution", () => {
777 it("validates the requested face after its styles load", async () => {
778 let loaded = false;
779 const load = vi.fn(async () => {
780 loaded = true;
781 return [];
782 });
783 const resolve = vi.fn(() => {
784 expect(loaded).toBe(true);
785 return DEFAULT_TERMINAL_FONT_FAMILY;
786 });
787β
788 await expect(
789 loadTerminalFontFamily("Proportional Test", 12, {
790 load,
791 resolve,
792 }),
793 ).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
794 expect(load).toHaveBeenCalledTimes(4);
795 expect(resolve).toHaveBeenCalledWith("Proportional Test");
796 });
797β
798 it("keeps the glyph fallbacks behind a custom text face", () => {
799 expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
800 expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
801 const custom = terminalFontFamily('"Fira Code"');
802 expect(custom.startsWith('"Fira Code", ')).toBe(true);
803 expect(custom).toContain('"Symbols Nerd Font Mono"');
804 expect(custom.endsWith("monospace")).toBe(true);
805 });
806β
807 it("ignores proportional families the cell grid cannot lay out", () => {
808 // jsdom has no canvas metrics, so the probe answers "monospace" and the
809 // family is kept; the guard is exercised in the browser instead. Assert the
810 // shape stays intact so a rejected face still yields a usable stack.
811 const stack = terminalFontFamily("Helvetica Neue");
812 expect(stack.endsWith("monospace")).toBe(true);
813 });
814β
815 it("quotes families the canvas font shorthand would otherwise reject", () => {
816 expect(terminalFontFamily("3270 Nerd Font").startsWith('"3270 Nerd Font", ')).toBe(true);
817 expect(terminalFontFamily("M+ 1m").startsWith('"M+ 1m", ')).toBe(true);
818 expect(terminalFontFamily("Cascadia Code, Menlo").startsWith('"Cascadia Code", Menlo, ')).toBe(
819 true,
820 );
821 expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
822 });
823β
824 it("clamps requested font sizes to the supported range", () => {
825 expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
826 expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
827 expect(terminalFontSize(13.4)).toBe(13);
828 expect(terminalFontSize(2)).toBe(6);
829 expect(terminalFontSize(90)).toBe(32);
830 });
831});
832β
833describe("terminalContentOriginY", () => {
834 it("stays top-anchored like a fresh terminal until scrollback exists", () => {
835 expect(terminalContentOriginY(100, 4, 5, 16, false)).toBe(4);
836 });
837β
838 it("pins the grid to the bottom by moving the sub-row slack above row 0", () => {
839 // 100px mount, 4px padding, 5 rows of 16px: 92 - 80 = 12px slack on top.
840 expect(terminalContentOriginY(100, 4, 5, 16, true)).toBe(16);
841 // Exact fit keeps the origin at the padding.
842 expect(terminalContentOriginY(88, 4, 5, 16, true)).toBe(4);
843 // A mount smaller than the grid never pushes the origin above the padding.
844 expect(terminalContentOriginY(80, 4, 5, 16, true)).toBe(4);
845 });
846β
847 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
848 // Growing the mount pixel by pixel: the bottom edge (origin + rows*cell)
849 // tracks the mount bottom exactly until a new row fits.
850 for (let height = 88; height < 104; height += 1) {
851 const rows = Math.max(1, Math.floor((height - 8) / 16));
852 const origin = terminalContentOriginY(height, 4, rows, 16, true);
853 expect(origin + rows * 16).toBe(height - 4);
854 }
855 });
856});
857β
858describe("terminalWheelDeltaRows", () => {
859 it("converts line-mode deltas into whole rows", () => {
860 const result = terminalWheelDeltaRows({ deltaY: 3, deltaMode: 1 }, 16, 24, 0);
861 expect(result.rows).toBe(3);
862 expect(result.remainder).toBe(0);
863 });
864β
865 it("accumulates fractional pixel deltas across events", () => {
866 let remainder = 0;
867 let scrolled = 0;
868 for (let index = 0; index < 4; index += 1) {
869 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
870 remainder = result.remainder;
871 scrolled += result.rows;
872 }
873 expect(scrolled).toBe(1);
874 expect(remainder).toBeCloseTo(4 / 16);
875 });
876β
877 it("keeps direction for negative page-mode deltas", () => {
878 const result = terminalWheelDeltaRows({ deltaY: -1, deltaMode: 2 }, 16, 24, 0);
879 expect(result.rows).toBe(-24);
880 expect(result.remainder).toBe(0);
881 });
882});
883β
884describe("terminalWheelArrowData", () => {
885 it("emits one arrow per row honoring application cursor keys", () => {
886 expect(terminalWheelArrowData(-2, false)).toBe("\u001b[A\u001b[A");
887 expect(terminalWheelArrowData(3, false)).toBe("\u001b[B\u001b[B\u001b[B");
888 expect(terminalWheelArrowData(-1, true)).toBe("\u001bOA");
889 expect(terminalWheelArrowData(0, true)).toBe("");
890 });
891});
892β
893describe("isTerminalLinkPointerGesture", () => {
894 it("uses Command on macOS and Control elsewhere", () => {
895 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "MacIntel")).toBe(true);
896 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "MacIntel")).toBe(false);
897 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "Linux x86_64")).toBe(
898 true,
899 );
900 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "Linux x86_64")).toBe(
901 false,
902 );
903 });
904});
905β
906describe("advanceTerminalSelectionClickSequence", () => {
907 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
908 const first = advanceTerminalSelectionClickSequence(null, {
909 clientX: 20,
910 clientY: 30,
911 timeStamp: 1_000,
912 });
913 const second = advanceTerminalSelectionClickSequence(first, {
914 clientX: 22,
915 clientY: 29,
916 timeStamp: 1_200,
917 });
918 const third = advanceTerminalSelectionClickSequence(second, {
919 clientX: 21,
920 clientY: 31,
921 timeStamp: 1_400,
922 });
923β
924 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
925 });
926β
927 it("starts over after movement, delay, or a completed triple click", () => {
928 const previous = { count: 3, time: 1_000, x: 20, y: 30 };
929 expect(
930 advanceTerminalSelectionClickSequence(previous, {
931 clientX: 20,
932 clientY: 30,
933 timeStamp: 1_100,
934 }).count,
935 ).toBe(1);
936 expect(
937 advanceTerminalSelectionClickSequence(previous, {
938 clientX: 30,
939 clientY: 30,
940 timeStamp: 1_100,
941 }).count,
942 ).toBe(1);
943 expect(
944 advanceTerminalSelectionClickSequence(previous, {
945 clientX: 20,
946 clientY: 30,
947 timeStamp: 1_501,
948 }).count,
949 ).toBe(1);
950 });
951});
952β
953describe("terminal scrollbar", () => {
954 it("maps Ghostty's viewport state to a proportional thumb", () => {
955 expect(terminalScrollbarGeometry({ total: 100, offset: 40, len: 20 }, 200)).toEqual({
956 thumbHeight: 40,
957 thumbTop: 80,
958 maxOffset: 80,
959 });
960 expect(terminalScrollbarGeometry({ total: 100, offset: 0, len: 100 }, 200)).toBeNull();
961 });
962β
963 it("keeps the thumb usable for large scrollback and maps dragging back to rows", () => {
964 const state = { total: 10_000, offset: 0, len: 20 };
965 expect(terminalScrollbarGeometry(state, 200)).toEqual({
966 thumbHeight: 18,
967 thumbTop: 0,
968 maxOffset: 9_980,
969 });
970 expect(terminalScrollbarOffsetAtPointer(state, 200, 191, 9)).toBe(9_980);
971 });
972});