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