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 function key(
46 surface: GhosttyTerminalSurface,
47 key: string,
48 code: string,
49 modifiers: Partial<
50 Pick<
51 KeyboardEvent,
52 | "altKey"
53 | "ctrlKey"
54 | "metaKey"
55 | "shiftKey"
56 | "isComposing"
57 | "keyCode"
58 | "getModifierState"
59 >
60 > = {},
61 type = "keydown",
62 ) {
63 const event = Object.assign(new Event(type, { cancelable: true }), {
64 key,
65 code,
66 altKey: false,
67 ctrlKey: false,
68 metaKey: false,
69 shiftKey: false,
70 isComposing: false,
71 keyCode: 0,
72 getModifierState: () => false,
73 ...modifiers,
74 });
75 surface.input.dispatchEvent(event);
76 return event;
77 }
78
79 // Keep the real surface, renderer, and WASM core. Only browser layout and
80 // scheduling are replaced so tests can count work while the terminal is hidden.
81 function createHarness() {
82 vi.useFakeTimers();
83 const frames = new Map<number, FrameRequestCallback>();
84 const resizeTargets = new Map<(entries: { target: Element }[]) => void, Set<Element>>();
85 const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
86 let frameId = 0;
87 const requestFrame = vi.fn((callback: FrameRequestCallback) => {
88 frames.set(++frameId, callback);
89 return frameId;
90 });
91
92 class TerminalTestElement extends EventTarget {
93 style: Record<string, string> = {};
94 parentElement: TerminalTestElement | null = null;
95 clientWidth = 168;
96 clientHeight = 104;
97 width = 300;
98 height = 150;
99 value = "";
100 private readonly captures = new Set<number>();
101
102 setAttribute() {}
103 append(...children: TerminalTestElement[]) {
104 for (const child of children) child.parentElement = this;
105 }
106 replaceChildren(...children: TerminalTestElement[]) {
107 this.append(...children);
108 }
109 remove() {
110 this.parentElement = null;
111 }
112 getContext() {
113 return context;
114 }
115 focus() {
116 this.dispatchEvent(new Event("focus"));
117 }
118 setPointerCapture(pointerId: number) {
119 this.captures.add(pointerId);
120 }
121 hasPointerCapture(pointerId: number) {
122 return this.captures.has(pointerId);
123 }
124 releasePointerCapture(pointerId: number) {
125 this.captures.delete(pointerId);
126 }
127 getBoundingClientRect() {
128 return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
129 }
130 }
131
132 const canvas = new TerminalTestElement();
133 const mount = new TerminalTestElement();
134 const context = {
135 canvas,
136 beginPath() {},
137 clip() {},
138 rect() {},
139 resetTransform() {},
140 restore() {},
141 save() {},
142 setTransform() {},
143 fillRect: (...args: number[]) => paint("fillRect", args),
144 strokeRect: (...args: number[]) => paint("strokeRect", args),
145 fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
146 measureText: (text: string) => ({
147 width: text.length * 8,
148 actualBoundingBoxAscent: 9,
149 actualBoundingBoxDescent: 3,
150 }),
151 };
152 vi.stubGlobal("document", {
153 createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
154 fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
155 });
156 vi.stubGlobal(
157 "window",
158 Object.assign(new EventTarget(), {
159 devicePixelRatio: 1,
160 requestAnimationFrame: requestFrame,
161 cancelAnimationFrame: (id: number) => frames.delete(id),
162 setTimeout,
163 clearTimeout,
164 setInterval,
165 clearInterval,
166 matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
167 }),
168 );
169 vi.stubGlobal(
170 "ResizeObserver",
171 class {
172 constructor(private readonly callback: (entries: { target: Element }[]) => void) {
173 resizeTargets.set(callback, new Set());
174 }
175 observe(target: Element) {
176 resizeTargets.get(this.callback)?.add(target);
177 }
178 unobserve(target: Element) {
179 resizeTargets.get(this.callback)?.delete(target);
180 }
181 disconnect() {
182 resizeTargets.delete(this.callback);
183 }
184 },
185 );
186 const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
187 const onData = vi.fn<(data: string) => void>();
188
189 return {
190 mount,
191 frames,
192 paint,
193 requestFrame,
194 snapshot,
195 onData,
196 get renderedSnapshot() {
197 const result = snapshot.mock.results.at(-1);
198 if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
199 return result.value;
200 },
201 flushFrame() {
202 const queued = [...frames.values()];
203 frames.clear();
204 for (const callback of queued) callback(0);
205 },
206 resize() {
207 for (const [callback, targets] of resizeTargets) {
208 callback([...targets].map((target) => ({ target })));
209 }
210 },
211 pointer(
212 type: string,
213 clientX: number,
214 buttons: number,
215 modifiers: boolean | Partial<Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">> = {},
216 button = 0,
217 ) {
218 canvas.dispatchEvent(
219 Object.assign(new Event(type, { cancelable: true }), {
220 clientX,
221 clientY: 5,
222 pointerId: 1,
223 button,
224 buttons,
225 ...(typeof modifiers === "boolean" ? { shiftKey: modifiers } : modifiers),
226 }),
227 );
228 },
229 async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
230 const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
231 theme: {
232 foreground: { r: 255, g: 255, b: 255 },
233 background: { r: 0, g: 0, b: 0 },
234 cursor: { r: 255, g: 255, b: 255 },
235 },
236 onData,
237 onResize() {},
238 onSelectionChange() {},
239 beforeKey: () => false,
240 onLinkActivate() {},
241 ...options,
242 get visible() {
243 return options.visible ?? true;
244 },
245 });
246 surfaces.add(surface);
247 return surface;
248 },
249 };
250 }
251
252 afterEach(() => {
253 for (const surface of surfaces) surface.dispose();
254 surfaces.clear();
255 vi.useRealTimers();
256 vi.unstubAllGlobals();
257 vi.restoreAllMocks();
258 });
259
260 it.each([
261 { platform: "Linux x86_64", primary: { ctrlKey: true } },
262 { platform: "MacIntel", primary: { metaKey: true } },
263 ])(
264 "navigates history from terminal input without sending keys ($platform)",
265 async ({ platform, primary }) => {
266 vi.stubGlobal("navigator", { platform });
267 const harness = createHarness();
268 const surface = await harness.create({ beforeKey: () => true });
269 surface.write(Array.from({ length: 20 }, (_, index) => `line ${index}`).join("\r\n"));
270 harness.flushFrame();
271 const latest = harness.renderedSnapshot.rowData[0]?.text;
272 expect(surface.isAtBottom()).toBe(true);
273
274 expect(key(surface, "PageUp", "PageUp", { shiftKey: true }).defaultPrevented).toBe(true);
275 harness.flushFrame();
276 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("line 8");
277 expect(surface.isAtBottom()).toBe(false);
278 key(surface, "PageDown", "PageDown", { shiftKey: true });
279 harness.flushFrame();
280 expect(harness.renderedSnapshot.rowData[0]?.text).toBe(latest);
281
282 key(surface, "Home", "Home", { ...primary, shiftKey: true });
283 harness.flushFrame();
284 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("line 0");
285 key(surface, "End", "End", { ...primary, shiftKey: true });
286 harness.flushFrame();
287 expect(harness.renderedSnapshot.rowData[0]?.text).toBe(latest);
288 expect(surface.isAtBottom()).toBe(true);
289 expect(harness.onData).not.toHaveBeenCalled();
290 },
291 );
292
293 it("forwards navigation presses and releases when scrollback state is unavailable", async () => {
294 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
295 const harness = createHarness();
296 const surface = await harness.create({ beforeKey: () => true });
297 surface.write("history\x1b[>31u");
298 vi.spyOn(GhosttyTerminalCore.prototype, "scrollbarState").mockReturnValue(null);
299
300 for (const [name, modifiers] of [
301 ["PageUp", { shiftKey: true }],
302 ["Home", { ctrlKey: true, shiftKey: true }],
303 ] as const) {
304 key(surface, name, name, modifiers);
305 key(surface, name, name, modifiers, "keyup");
306 }
307 expect(harness.onData).toHaveBeenCalledTimes(4);
308 expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");
309 expect(harness.onData.mock.calls[3]?.[0]).toContain(":3");
310 });
311
312 it("selects full history and keeps selection coordinates available outside the viewport", async () => {
313 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
314 const harness = createHarness();
315 const surface = await harness.create({ beforeKey: () => true });
316 const lines = Array.from({ length: 20 }, (_, index) => `line ${index}`);
317 surface.write(lines.join("\r\n"));
318 harness.flushFrame();
319 surface.selectAll();
320 harness.flushFrame();
321 expect(surface.getSelection()).toBe(lines.join("\n"));
322 expect(surface.getSelectionPosition()).toMatchObject({ start: { x: 0, y: 0 } });
323 expect(surface.getSelectionPosition()?.end.y).toBe(19);
324 expect(surface.getSelectionEndClientRect()).not.toBeNull();
325 expect(harness.renderedSnapshot.rowData.every((row) => row.cells[0]?.selected)).toBe(true);
326
327 key(surface, "Home", "Home", { ctrlKey: true, shiftKey: true });
328 harness.flushFrame();
329 surface.selectAll();
330 expect(surface.getSelection()).toBe(lines.join("\n"));
331 expect(surface.getSelectionPosition()?.end.y).toBe(19);
332 expect(surface.getSelectionEndClientRect()).toBeNull();
333 surface.clearSelection();
334 expect(surface.getSelection()).toBe("");
335 expect(surface.getSelectionPosition()).toBeNull();
336 });
337
338 it.each([
339 { platform: "Linux x86_64", modifiers: { ctrlKey: true, shiftKey: true } },
340 { platform: "MacIntel", modifiers: { metaKey: true } },
341 ])("selects all through the local shortcut ($platform)", async ({ platform, modifiers }) => {
342 vi.stubGlobal("navigator", { platform });
343 const harness = createHarness();
344 const surface = await harness.create({ beforeKey: () => true });
345 surface.write("hello\r\nworld");
346 harness.flushFrame();
347 expect(key(surface, "a", "KeyA", modifiers).defaultPrevented).toBe(true);
348 expect(surface.getSelection()).toBe("hello\nworld");
349 expect(surface.getSelectionPosition()).not.toBeNull();
350 expect(harness.onData).not.toHaveBeenCalled();
351 });
352
353 it("preserves shell Ctrl+A and ordinary application navigation", async () => {
354 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
355 const harness = createHarness();
356 const surface = await harness.create({ beforeKey: () => true });
357 key(surface, "a", "KeyA", { ctrlKey: true });
358 key(surface, "PageUp", "PageUp");
359 key(surface, "PageDown", "PageDown");
360 key(surface, "Home", "Home");
361 key(surface, "End", "End");
362 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
363 "\x01",
364 "\x1b[5~",
365 "\x1b[6~",
366 "\x1b[H",
367 "\x1b[F",
368 ]);
369 expect(surface.hasSelection()).toBe(false);
370 });
371
372 it("leaves modified history keys with alternate-screen applications", async () => {
373 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
374 const harness = createHarness();
375 const surface = await harness.create({ beforeKey: () => true });
376 surface.write("\x1b[?1049happ");
377 key(surface, "PageUp", "PageUp", { shiftKey: true });
378 key(surface, "End", "End", { ctrlKey: true, shiftKey: true });
379 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[5;2~", "\x1b[1;6F"]);
380 surface.selectAll();
381 expect(surface.getSelection()).toBe("app");
382 surface.write("\x1b[?1049l");
383 expect(surface.getSelection()).toBe("");
384 });
385
386 it("suppresses local shortcut releases in Kitty sessions, including read-only observers", async () => {
387 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
388 const harness = createHarness();
389 const surface = await harness.create({ beforeKey: () => true });
390 surface.input.readOnly = true;
391 surface.write("history\x1b[>31u");
392 for (const [name, code, modifiers] of [
393 ["PageUp", "PageUp", { shiftKey: true }],
394 ["Home", "Home", { ctrlKey: true, shiftKey: true }],
395 ["a", "KeyA", { ctrlKey: true, shiftKey: true }],
396 ] as const) {
397 key(surface, name, code, modifiers);
398 key(surface, name, code, modifiers, "keyup");
399 }
400 expect(surface.getSelection()).toBe("history");
401 expect(harness.onData).not.toHaveBeenCalled();
402
403 // An ordinary application key still has both press and release reports.
404 key(surface, "PageUp", "PageUp");
405 key(surface, "PageUp", "PageUp", {}, "keyup");
406 expect(harness.onData).toHaveBeenCalledTimes(2);
407 expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");
408 });
409
410 it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {
411 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
412 const harness = createHarness();
413 let allow = false;
414 const surface = await harness.create({ beforeKey: () => allow });
415 surface.write("hello\x1b[>31u");
416 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
417 key(surface, "a", "KeyA", {}, "keyup");
418 expect(surface.hasSelection()).toBe(false);
419 allow = true;
420 surface.input.value = "候補";
421 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, isComposing: true });
422 key(surface, "a", "KeyA", {}, "keyup");
423 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, keyCode: 229 });
424 key(surface, "a", "KeyA", {}, "keyup");
425 key(surface, "a", "KeyA", {
426 ctrlKey: true,
427 shiftKey: true,
428 altKey: true,
429 getModifierState: (modifier) => modifier === "AltGraph",
430 });
431 key(surface, "a", "KeyA", {}, "keyup");
432 expect(surface.input.value).toBe("候補");
433 expect(surface.hasSelection()).toBe(false);
434 expect(harness.onData).not.toHaveBeenCalled();
435 });
436
437 it.each([
438 { platform: "Linux x86_64", modifiers: { ctrlKey: true, metaKey: false } },
439 { platform: "MacIntel", modifiers: { ctrlKey: false, metaKey: true } },
440 ])(
441 "gates path links and preserves selection and URLs ($platform)",
442 async ({ platform, modifiers }) => {
443 vi.stubGlobal("navigator", { platform });
444 const harness = createHarness();
445 vi.spyOn(Event.prototype, "timeStamp", "get").mockImplementation(() => Date.now());
446 let canOpenPaths = false;
447 const openLink = vi.fn();
448 const surface = await harness.create({
449 canActivateLink: (text) => text.startsWith("https://") || canOpenPaths,
450 onLinkActivate: openLink,
451 });
452 surface.write("/repo/file.ts");
453 harness.flushFrame();
454 harness.pointer("pointermove", 5, 0, modifiers);
455 expect(surface.canvas.style.cursor).toBe("");
456 harness.pointer("pointerdown", 5, 1, modifiers);
457 harness.pointer("pointerup", 5, 0, modifiers);
458 expect(openLink).not.toHaveBeenCalled();
459
460 vi.advanceTimersByTime(501);
461 harness.pointer("pointerdown", 5, 1);
462 harness.pointer("pointermove", 37, 1);
463 harness.pointer("pointerup", 37, 0);
464 expect(surface.getSelection()).toBe("/repo");
465
466 vi.advanceTimersByTime(501);
467 harness.pointer("pointermove", 5, 0, modifiers);
468 canOpenPaths = true;
469 surface.refreshLinkActivation();
470 expect(surface.canvas.style.cursor).toBe("pointer");
471 harness.pointer("pointerdown", 5, 1, modifiers);
472 harness.pointer("pointerup", 5, 0, modifiers);
473 expect(openLink).toHaveBeenCalledExactlyOnceWith("/repo/file.ts", expect.any(Event));
474
475 vi.advanceTimersByTime(501);
476 harness.pointer("pointerdown", 5, 1, modifiers);
477 canOpenPaths = false;
478 surface.refreshLinkActivation();
479 expect(surface.canvas.style.cursor).toBe("");
480 harness.pointer("pointerup", 5, 0, modifiers);
481 expect(openLink).toHaveBeenCalledOnce();
482
483 vi.advanceTimersByTime(501);
484 surface.resetAndWrite("https://t3.codes");
485 harness.flushFrame();
486 harness.pointer("pointermove", 5, 0, modifiers);
487 expect(surface.canvas.style.cursor).toBe("pointer");
488 harness.pointer("pointerdown", 5, 1, modifiers);
489 harness.pointer("pointerup", 5, 0, modifiers);
490 expect(openLink).toHaveBeenLastCalledWith("https://t3.codes", expect.any(Event));
491 },
492 );
493
494 it("resends an unchanged grid when authorization and attachment become ready", async () => {
495 const harness = createHarness();
496 let canOperate = false;
497 let attached = false;
498 const resizePty = vi.fn<(cols: number, rows: number) => void>();
499 const surface = await harness.create({
500 onResize: (cols, rows) => {
501 if (canOperate && attached) resizePty(cols, rows);
502 },
503 });
504 vi.advanceTimersByTime(150);
505 expect(resizePty).not.toHaveBeenCalled();
506
507 canOperate = true;
508 surface.resendSize();
509 vi.advanceTimersByTime(150);
510 expect(resizePty).not.toHaveBeenCalled();
511
512 attached = true;
513 surface.resendSize();
514 vi.advanceTimersByTime(150);
515 expect(resizePty).toHaveBeenCalledExactlyOnceWith(20, 6);
516 surface.fit();
517 vi.advanceTimersByTime(150);
518 expect(resizePty).toHaveBeenCalledOnce();
519
520 canOperate = false;
521 harness.mount.clientWidth = 248;
522 surface.fit();
523 vi.advanceTimersByTime(150);
524 expect(resizePty).toHaveBeenCalledOnce();
525 });
526
527 it("replays the current grid on reveal when a hidden host becomes ready", async () => {
528 const harness = createHarness();
529 const onResize = vi.fn<(cols: number, rows: number) => void>();
530 const surface = await harness.create({ onResize });
531 vi.advanceTimersByTime(150);
532 onResize.mockClear();
533
534 surface.setVisible(false);
535 surface.resendSize();
536 vi.advanceTimersByTime(150);
537 expect(onResize).not.toHaveBeenCalled();
538
539 surface.setVisible(true);
540 vi.advanceTimersByTime(150);
541 expect(onResize).toHaveBeenCalledExactlyOnceWith(20, 6);
542 });
543
544 it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {
545 const harness = createHarness();
546 const surface = await harness.create();
547 surface.focus();
548 surface.write("ready\x1b[1 q");
549 harness.flushFrame();
550 vi.advanceTimersByTime(500);
551 harness.flushFrame();
552 surface.write("queued");
553 expect(harness.frames.size).toBe(1);
554 surface.setVisible(false);
555 expect(harness.frames.size).toBe(0);
556 expect(vi.getTimerCount()).toBe(0);
557 harness.snapshot.mockClear();
558 harness.paint.mockClear();
559 harness.requestFrame.mockClear();
560
561 surface.write("\x1b[2J\x1b[H\x1b[3");
562 surface.write("1mhidden");
563 surface.write("界🙂\x1b[0m\x1b[5n\x1b[6n");
564 surface.fit();
565 vi.advanceTimersByTime(2_000);
566 harness.flushFrame();
567
568 expect(harness.onData.mock.calls).toEqual([["\x1b[0n"], ["\x1b[1;11R"]]);
569 expect(harness.snapshot).not.toHaveBeenCalled();
570 expect(harness.paint).not.toHaveBeenCalled();
571 expect(harness.requestFrame).not.toHaveBeenCalled();
572
573 surface.setVisible(true);
574 expect(harness.snapshot).toHaveBeenCalledTimes(1);
575 expect(harness.renderedSnapshot).toMatchObject({ cursorX: 10, cursorY: 0 });
576 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("hidden");
577 expect(harness.paint.mock.calls).toContainEqual(["fillRect", [84, 4, 8, 16]]);
578 expect(harness.frames.size).toBe(0);
579 });
580
581 it("keeps the selection on reveal and applies a hidden selection clear", async () => {
582 const harness = createHarness();
583 const surface = await harness.create();
584 surface.write("hello world");
585 harness.flushFrame();
586 harness.pointer("pointerdown", 5, 1);
587 harness.pointer("pointermove", 37, 1);
588 harness.pointer("pointerup", 37, 0);
589 harness.flushFrame();
590 expect(surface.getSelection()).toBe("hello");
591 const position = surface.getSelectionPosition();
592
593 surface.setVisible(false);
594 harness.snapshot.mockClear();
595 surface.setVisible(true);
596 expect(harness.snapshot).toHaveBeenCalledTimes(1);
597 expect(surface.getSelectionPosition()).toEqual(position);
598 expect(
599 harness.renderedSnapshot.rowData[0]?.cells.slice(0, 5).every((cell) => cell.selected),
600 ).toBe(true);
601
602 surface.setVisible(false);
603 harness.snapshot.mockClear();
604 surface.clearSelection();
605 surface.write("!");
606 expect(harness.snapshot).not.toHaveBeenCalled();
607 surface.setVisible(true);
608 expect(harness.snapshot).toHaveBeenCalledTimes(1);
609 expect(surface.getSelection()).toBe("");
610 expect(surface.getSelectionPosition()).toBeNull();
611 expect(harness.renderedSnapshot.rowData[0]?.cells.some((cell) => cell.selected)).toBe(false);
612 });
613
614 it("pastes the terminal selection, and only that, on a Linux middle click", async () => {
615 const harness = createHarness();
616 const readText = vi.fn(async () => "clipboard text");
617 vi.stubGlobal("navigator", { platform: "Linux x86_64", clipboard: { readText } });
618 const surface = await harness.create();
619 surface.write("hello world");
620 harness.flushFrame();
621 harness.pointer("pointerdown", 5, 1);
622 harness.pointer("pointermove", 37, 1);
623 harness.pointer("pointerup", 37, 0);
624 expect(surface.getSelection()).toBe("hello");
625
626 harness.onData.mockClear();
627 harness.pointer("pointerdown", 5, 4, false, 1);
628 await vi.waitFor(() => expect(harness.onData).toHaveBeenCalled());
629 expect(harness.onData.mock.calls.at(-1)?.[0]).toBe("hello");
630 expect(surface.getSelection()).toBe("hello");
631
632 // Without a selection there is no primary buffer to paste; the clipboard
633 // holds what the user copied and must not be substituted.
634 surface.clearSelection();
635 harness.pointer("pointerdown", 5, 4, false, 1);
636 expect(readText).not.toHaveBeenCalled();
637 });
638
639 it("starts a selection when dragging from a link", async () => {
640 const harness = createHarness();
641 const onLinkActivate = vi.fn();
642 const surface = await harness.create({ onLinkActivate });
643 surface.write("https://example.com");
644 harness.flushFrame();
645
646 harness.pointer("pointerdown", 5, 1);
647 harness.pointer("pointermove", 37, 1);
648 harness.pointer("pointerup", 37, 0);
649
650 expect(onLinkActivate).not.toHaveBeenCalled();
651 expect(surface.getSelection()).toBe("https");
652 });
653
654 it("keeps a link click active through slight pointer movement", async () => {
655 const harness = createHarness();
656 const onLinkActivate = vi.fn();
657 const surface = await harness.create({ onLinkActivate });
658 surface.write("https://example.com");
659 harness.flushFrame();
660
661 harness.pointer("pointerdown", 5, 1);
662 harness.pointer("pointermove", 6, 1);
663 harness.pointer("pointerup", 6, 0);
664
665 expect(onLinkActivate).toHaveBeenCalledOnce();
666 });
667
668 it("uses repeated link clicks for word and line selection", async () => {
669 const harness = createHarness();
670 const onLinkActivate = vi.fn();
671 const surface = await harness.create({ onLinkActivate });
672 surface.write("https://example.com tail");
673 harness.flushFrame();
674
675 harness.pointer("pointerdown", 5, 1);
676 harness.pointer("pointerup", 5, 0);
677 harness.pointer("pointerdown", 5, 1);
678 harness.pointer("pointerup", 5, 0);
679 expect(onLinkActivate).toHaveBeenCalledOnce();
680 expect(surface.getSelection()).not.toBe("");
681
682 harness.pointer("pointerdown", 5, 1);
683 harness.pointer("pointerup", 5, 0);
684 expect(onLinkActivate).toHaveBeenCalledOnce();
685 expect(surface.getSelection()).toBe("https://example.com tail");
686 });
687
688 it("uses Shift drags over links for selection", async () => {
689 const harness = createHarness();
690 const onLinkActivate = vi.fn();
691 const surface = await harness.create({ onLinkActivate });
692 surface.write("https://example.com");
693 harness.flushFrame();
694
695 harness.pointer("pointerdown", 5, 1, true);
696 harness.pointer("pointermove", 37, 1, true);
697 harness.pointer("pointerup", 37, 0, true);
698 expect(onLinkActivate).not.toHaveBeenCalled();
699 expect(surface.getSelection()).toBe("https");
700 });
701
702 it("does not activate a link replaced before pointer release", async () => {
703 const harness = createHarness();
704 const onLinkActivate = vi.fn();
705 const surface = await harness.create({ onLinkActivate });
706 surface.write("https://first.example");
707 harness.flushFrame();
708
709 harness.pointer("pointerdown", 5, 1);
710 surface.write("\x1b[2J\x1b[Hhttps://second.example");
711 harness.flushFrame();
712 harness.pointer("pointerup", 5, 0);
713
714 expect(onLinkActivate).not.toHaveBeenCalled();
715 });
716
717 it("stops zero-size mounts and repaints when the same size returns", async () => {
718 const harness = createHarness();
719 const surface = await harness.create();
720 surface.focus();
721 surface.write("visible");
722 harness.flushFrame();
723 harness.snapshot.mockClear();
724 harness.paint.mockClear();
725 harness.mount.clientWidth = 0;
726 surface.write("!");
727 harness.flushFrame();
728 harness.requestFrame.mockClear();
729 for (let index = 0; index < 8; index += 1) surface.write("x");
730 vi.advanceTimersByTime(2_000);
731
732 expect(harness.snapshot).not.toHaveBeenCalled();
733 expect(harness.paint).not.toHaveBeenCalled();
734 expect(harness.requestFrame).not.toHaveBeenCalled();
735 harness.mount.clientWidth = 168;
736 harness.resize();
737 expect(harness.snapshot).toHaveBeenCalledTimes(1);
738 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("visible!xxxxxxxx");
739 expect(harness.paint).toHaveBeenCalled();
740 });
741
742 it.each([false, true])(
743 "uses visibility %s if it changes while WASM initializes",
744 async (visible) => {
745 const harness = createHarness();
746 let markCreated!: () => void;
747 const created = new Promise<void>((resolve) => {
748 markCreated = resolve;
749 });
750 let finishLoading!: () => void;
751 const release = new Promise<void>((resolve) => {
752 finishLoading = resolve;
753 });
754 const create = GhosttyTerminalCore.create;
755 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
756 const core = await create(...args);
757 markCreated();
758 await release;
759 return core;
760 });
761 let currentVisible = !visible;
762 const pending = harness.create({
763 get visible() {
764 return currentVisible;
765 },
766 });
767 await created;
768 currentVisible = visible;
769 harness.paint.mockClear();
770 finishLoading();
771 const surface = await pending;
772
773 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
774 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
775 surface.write("ready\x1b[5n");
776 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
777 if (!visible) {
778 expect(harness.frames.size).toBe(0);
779 surface.setVisible(true);
780 } else {
781 harness.flushFrame();
782 }
783 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
784 },
785 );
786});
787
788const cell = (text: string): GhosttyCell => ({
789 text,
790 wide: 0,
791 foreground: { r: 255, g: 255, b: 255 },
792 background: { r: 0, g: 0, b: 0 },
793 bold: false,
794 italic: false,
795 invisible: false,
796 strikethrough: false,
797 overline: false,
798 underline: false,
799 selected: false,
800});
801
802describe("isTerminalAltGraphText", () => {
803 it("defers printable AltGr output to the textarea input event", () => {
804 expect(
805 isTerminalAltGraphText({
806 key: "@",
807 getModifierState: (modifier) => modifier === "AltGraph",
808 }),
809 ).toBe(true);
810 expect(
811 isTerminalAltGraphText({
812 key: "ArrowRight",
813 getModifierState: (modifier) => modifier === "AltGraph",
814 }),
815 ).toBe(false);
816 });
817});
818
819describe("terminalGridCellAt", () => {
820 const options = {
821 bounds: { left: 100, top: 200 },
822 cols: 3,
823 rows: 2,
824 metrics: { width: 10, height: 20 },
825 padding: 4,
826 originY: 24,
827 };
828
829 it("maps points inside the rendered grid without clamping its padding", () => {
830 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
831 x: 0,
832 y: 0,
833 });
834 expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
835 x: 2,
836 y: 1,
837 });
838 expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
839 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
840 expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
841 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
842 });
843});
844
845describe("shouldBlinkTerminalCursor", () => {
846 const blinking = {
847 focused: true,
848 cursorBlinking: true,
849 cursorVisible: true,
850 reducedMotion: false,
851 };
852
853 it("blinks a focused visible cursor the terminal asked to blink", () => {
854 expect(shouldBlinkTerminalCursor(blinking)).toBe(true);
855 });
856
857 it("holds the cursor steady when blinking would be unwanted", () => {
858 // Unfocused surfaces draw a steady hollow cursor, DECSCUSR steady styles and
859 // DEC mode 12 turn blinking off, a hidden cursor has nothing to toggle, and
860 // reduced-motion readers get no permanently animating element.
861 expect(shouldBlinkTerminalCursor({ ...blinking, focused: false })).toBe(false);
862 expect(shouldBlinkTerminalCursor({ ...blinking, cursorBlinking: false })).toBe(false);
863 expect(shouldBlinkTerminalCursor({ ...blinking, cursorVisible: false })).toBe(false);
864 expect(shouldBlinkTerminalCursor({ ...blinking, reducedMotion: true })).toBe(false);
865 });
866});
867
868describe("terminalLinkAtPositionWithRange", () => {
869 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
870 const cells = [
871 cell("🙂"),
872 cell(""),
873 ...Array.from("https://t3.codes", (character) => cell(character)),
874 ];
875 const row: GhosttyRow = {
876 cells,
877 text: cells
878 .map((value) => value.text || " ")
879 .join("")
880 .trimEnd(),
881 isWrapContinuation: false,
882 wrapsToNext: false,
883 };
884
885 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
886 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
887 "https://t3.codes",
888 );
889 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
890 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
891 start: { x: 2, y: 0 },
892 end: { x: cells.length - 1, y: 0 },
893 });
894 });
895
896 it("uses shared path matching and reconstructs soft-wrapped links", () => {
897 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
898 cells: Array.from(text.padEnd(16), (character) => cell(character)),
899 text: text.trimEnd(),
900 isWrapContinuation,
901 wrapsToNext,
902 });
903 const rows = [
904 row("https://example.", false),
905 row("com/reference", true),
906 row("~/project/file", false),
907 row("C:\\repo\\file.ts", false),
908 ];
909
910 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
911 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
912 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
913 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
914 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
915 text: "https://example.com/reference",
916 range: {
917 start: { x: 0, y: 0 },
918 end: { x: 12, y: 1 },
919 },
920 });
921 });
922
923 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
924 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
925 cells: Array.from(text.padEnd(16), (character) => cell(character)),
926 text: text.trimEnd(),
927 isWrapContinuation,
928 wrapsToNext,
929 });
930 // The head of the wrapped line scrolled above the viewport.
931 const headCut = [row("ple.com/missing", true), row("head", true)];
932 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
933 // The bottom row soft-wraps on below the viewport.
934 const tailCut = [row("https://t3.codes", false, true)];
935 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
936 // A partial bottom row is provably complete and still resolves.
937 const complete = [row("https://t3.codes", false), row("", false)];
938 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
939 // A wide grapheme earlier in the row must not break truncation detection:
940 // the soft-wrap flag decides, not string-length-versus-cell-count.
941 const wideFull: GhosttyRow = {
942 cells: [
943 { ...cell("🙂"), wide: 1 },
944 { ...cell(""), wide: 2 },
945 ...Array.from("https://t3.code", (character) => cell(character)),
946 ],
947 text: "🙂 https://t3.code",
948 isWrapContinuation: false,
949 wrapsToNext: true,
950 };
951 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
952 // Unwritten trailing cells prove the bottom row is complete.
953 const unwrittenTail: GhosttyRow = {
954 cells: [
955 ...Array.from("https://t3.codes", (character) => cell(character)),
956 cell(""),
957 cell(""),
958 ],
959 text: "https://t3.codes",
960 isWrapContinuation: false,
961 wrapsToNext: false,
962 };
963 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
964 });
965});
966
967describe("isTerminalCopyShortcut", () => {
968 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
969 ctrlKey: false,
970 key: "c",
971 metaKey: false,
972 shiftKey: false,
973 ...overrides,
974 });
975
976 it("keeps Ctrl+C available for SIGINT on macOS", () => {
977 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
978 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
979 });
980
981 it("copies with Ctrl+C and Ctrl+Shift+C elsewhere", () => {
982 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(true);
983 expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
984 true,
985 );
986 expect(isTerminalCopyShortcut(event({}), "Linux x86_64")).toBe(false);
987 });
988
989 it("uses the produced character instead of the physical key position", () => {
990 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
991 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
992 });
993
994 it("supports the conventional Ctrl+Insert copy shortcut", () => {
995 expect(isTerminalCopyShortcut(event({ key: "Insert", ctrlKey: true }), "Linux x86_64")).toBe(
996 true,
997 );
998 expect(isTerminalCopyShortcut(event({ key: "Insert" }), "Linux x86_64")).toBe(false);
999 expect(
1000 isTerminalCopyShortcut(
1001 event({ key: "Insert", ctrlKey: true, shiftKey: true }),
1002 "Linux x86_64",
1003 ),
1004 ).toBe(false);
1005 expect(isTerminalCopyShortcut(event({ key: "Insert", ctrlKey: true }), "MacIntel")).toBe(false);
1006 });
1007});
1008
1009describe("applyTerminalCopyEvent", () => {
1010 it("writes the selection and claims the fallback when clipboardData is present", () => {
1011 const setData = vi.fn();
1012 expect(applyTerminalCopyEvent("ls -la", { setData })).toEqual({
1013 preventDefault: true,
1014 claimWriteFallback: true,
1015 });
1016 expect(setData).toHaveBeenCalledWith("text/plain", "ls -la");
1017 });
1018
1019 it("leaves the writeText fallback alive when clipboardData is missing", () => {
1020 // Electron's edit-menu Copy often delivers a copy event with no
1021 // clipboardData. Claiming that event used to skip writeText and copy the
1022 // empty IME textarea, which is the blank clipboard users paste.
1023 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
1024 preventDefault: false,
1025 claimWriteFallback: false,
1026 });
1027 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
1028 preventDefault: false,
1029 claimWriteFallback: false,
1030 });
1031 });
1032
1033 it("primes the current selection before a copy event with no clipboardData", () => {
1034 const input = {
1035 value: "stale",
1036 selectionStart: 0,
1037 selectionEnd: 0,
1038 select() {
1039 this.selectionStart = 0;
1040 this.selectionEnd = this.value.length;
1041 },
1042 };
1043 primeTerminalCopyInput(input, "git status");
1044 expect(applyTerminalCopyEvent("git status", null)).toEqual({
1045 preventDefault: false,
1046 claimWriteFallback: false,
1047 });
1048 expect(input.value).toBe("git status");
1049 expect(input.selectionStart).toBe(0);
1050 expect(input.selectionEnd).toBe(10);
1051 });
1052});
1053
1054describe("primeTerminalCopyInput", () => {
1055 it("selects the Ghostty selection in the hidden textarea so native copy has text", () => {
1056 const input = {
1057 value: "",
1058 selectionStart: 0,
1059 selectionEnd: 0,
1060 select() {
1061 this.selectionStart = 0;
1062 this.selectionEnd = this.value.length;
1063 },
1064 };
1065 primeTerminalCopyInput(input, "git status");
1066 expect(input.value).toBe("git status");
1067 expect(input.selectionStart).toBe(0);
1068 expect(input.selectionEnd).toBe(10);
1069 clearPrimedTerminalCopyInput(input, "git status");
1070 expect(input.value).toBe("");
1071 });
1072
1073 it("does not wipe an IME candidate that replaced the primed copy", () => {
1074 const input = { value: "", select() {} };
1075 primeTerminalCopyInput(input, "git status");
1076 input.value = "あ";
1077 clearPrimedTerminalCopyInput(input, "git status");
1078 expect(input.value).toBe("あ");
1079 });
1080});
1081
1082describe("isTerminalPasteShortcut", () => {
1083 const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
1084 ctrlKey: false,
1085 key: "v",
1086 metaKey: false,
1087 shiftKey: false,
1088 ...overrides,
1089 });
1090
1091 it("uses Cmd+V on macOS", () => {
1092 expect(isTerminalPasteShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
1093 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
1094 });
1095
1096 it("preserves Ctrl+V and uses Ctrl+Shift+V elsewhere", () => {
1097 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
1098 expect(isTerminalPasteShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
1099 true,
1100 );
1101 });
1102
1103 it("supports the conventional Shift+Insert paste shortcut", () => {
1104 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "Linux x86_64")).toBe(
1105 true,
1106 );
1107 expect(isTerminalPasteShortcut(event({ key: "Insert" }), "Linux x86_64")).toBe(false);
1108 expect(
1109 isTerminalPasteShortcut(
1110 event({ key: "Insert", ctrlKey: true, shiftKey: true }),
1111 "Linux x86_64",
1112 ),
1113 ).toBe(false);
1114 expect(isTerminalPasteShortcut(event({ key: "Insert", shiftKey: true }), "MacIntel")).toBe(
1115 false,
1116 );
1117 });
1118});
1119
1120describe("isTerminalCompositionCommitInput", () => {
1121 it("identifies browser composition follow-up input", () => {
1122 expect(isTerminalCompositionCommitInput({ inputType: "" })).toBe(true);
1123 expect(isTerminalCompositionCommitInput({ inputType: "insertCompositionText" })).toBe(true);
1124 expect(isTerminalCompositionCommitInput({ inputType: "insertFromComposition" })).toBe(true);
1125 });
1126
1127 it("keeps a fast repeated input as legitimate text", () => {
1128 expect(isTerminalCompositionCommitInput({ inputType: "insertText" })).toBe(false);
1129 });
1130});
1131
1132describe("isTerminalCompositionKey", () => {
1133 const event = (
1134 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
1135 ) => ({
1136 isComposing: false,
1137 key: "a",
1138 keyCode: 65,
1139 ...overrides,
1140 });
1141
1142 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
1143 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
1144 expect(isTerminalCompositionKey(event(), true)).toBe(true);
1145 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
1146 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
1147 });
1148
1149 it("lets ordinary keydowns clear a primed copy", () => {
1150 expect(isTerminalCompositionKey(event(), false)).toBe(false);
1151 });
1152});
1153
1154describe("application mouse reporting", () => {
1155 const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
1156 ctrlKey: false,
1157 metaKey: false,
1158 shiftKey: false,
1159 ...overrides,
1160 });
1161
1162 it("keeps Shift and link activation modifiers available to the browser", () => {
1163 expect(shouldReportTerminalMouse(true, event())).toBe(true);
1164 expect(shouldReportTerminalMouse(true, event({ shiftKey: true }))).toBe(false);
1165 expect(shouldReportTerminalMouse(true, event({ ctrlKey: true }))).toBe(false);
1166 expect(shouldReportTerminalMouse(true, event({ metaKey: true }))).toBe(false);
1167 expect(shouldReportTerminalMouse(false, event())).toBe(false);
1168 });
1169
1170 it("maps browser buttons to Ghostty's button enum", () => {
1171 expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
1172 });
1173
1174 it("drops repeated motion reports until another mouse action resets the cell", () => {
1175 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
1176 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
1177
1178 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
1179 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
1180
1181 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
1182 expect(press).toEqual({ send: true, nextMotionData: "" });
1183
1184 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
1185 send: true,
1186 nextMotionData: "\u001b[<35;8;4M",
1187 });
1188 });
1189
1190 it("clears the motion baseline when application mouse tracking changes", () => {
1191 expect(resolveTerminalMouseTrackingState(true, false, "\u001b[<35;8;4M")).toEqual({
1192 tracking: false,
1193 motionData: "",
1194 });
1195 expect(resolveTerminalMouseTrackingState(false, true, "\u001b[<35;8;4M")).toEqual({
1196 tracking: true,
1197 motionData: "",
1198 });
1199 expect(resolveTerminalMouseTrackingState(true, true, "\u001b[<35;8;4M")).toEqual({
1200 tracking: true,
1201 motionData: "\u001b[<35;8;4M",
1202 });
1203 expect(resolveTerminalMouseTrackingState(false, false, "\u001b[<35;8;4M")).toEqual({
1204 tracking: false,
1205 motionData: "\u001b[<35;8;4M",
1206 });
1207 });
1208});
1209
1210describe("terminal font resolution", () => {
1211 it("validates the requested face after its styles load", async () => {
1212 let loaded = false;
1213 const load = vi.fn(async () => {
1214 loaded = true;
1215 return [];
1216 });
1217 const resolve = vi.fn(() => {
1218 expect(loaded).toBe(true);
1219 return DEFAULT_TERMINAL_FONT_FAMILY;
1220 });
1221
1222 await expect(
1223 loadTerminalFontFamily("Proportional Test", 12, {
1224 load,
1225 resolve,
1226 }),
1227 ).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
1228 expect(load).toHaveBeenCalledTimes(4);
1229 expect(resolve).toHaveBeenCalledWith("Proportional Test");
1230 });
1231
1232 it("keeps the glyph fallbacks behind a custom text face", () => {
1233 expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
1234 expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
1235 const custom = terminalFontFamily('"Fira Code"');
1236 expect(custom.startsWith('"Fira Code", ')).toBe(true);
1237 expect(custom).toContain('"Symbols Nerd Font Mono"');
1238 expect(custom.endsWith("monospace")).toBe(true);
1239 });
1240
1241 it("ignores proportional families the cell grid cannot lay out", () => {
1242 // jsdom has no canvas metrics, so the probe answers "monospace" and the
1243 // family is kept; the guard is exercised in the browser instead. Assert the
1244 // shape stays intact so a rejected face still yields a usable stack.
1245 const stack = terminalFontFamily("Helvetica Neue");
1246 expect(stack.endsWith("monospace")).toBe(true);
1247 });
1248
1249 it("quotes families the canvas font shorthand would otherwise reject", () => {
1250 expect(terminalFontFamily("3270 Nerd Font").startsWith('"3270 Nerd Font", ')).toBe(true);
1251 expect(terminalFontFamily("M+ 1m").startsWith('"M+ 1m", ')).toBe(true);
1252 expect(terminalFontFamily("Cascadia Code, Menlo").startsWith('"Cascadia Code", Menlo, ')).toBe(
1253 true,
1254 );
1255 expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
1256 });
1257
1258 it("clamps requested font sizes to the supported range", () => {
1259 expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
1260 expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
1261 expect(terminalFontSize(13.4)).toBe(13);
1262 expect(terminalFontSize(2)).toBe(6);
1263 expect(terminalFontSize(90)).toBe(32);
1264 });
1265});
1266
1267describe("terminalContentOriginY", () => {
1268 it("stays top-anchored like a fresh terminal until scrollback exists", () => {
1269 expect(terminalContentOriginY(100, 4, 5, 16, false)).toBe(4);
1270 });
1271
1272 it("pins the grid to the bottom by moving the sub-row slack above row 0", () => {
1273 // 100px mount, 4px padding, 5 rows of 16px: 92 - 80 = 12px slack on top.
1274 expect(terminalContentOriginY(100, 4, 5, 16, true)).toBe(16);
1275 // Exact fit keeps the origin at the padding.
1276 expect(terminalContentOriginY(88, 4, 5, 16, true)).toBe(4);
1277 // A mount smaller than the grid never pushes the origin above the padding.
1278 expect(terminalContentOriginY(80, 4, 5, 16, true)).toBe(4);
1279 });
1280
1281 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
1282 // Growing the mount pixel by pixel: the bottom edge (origin + rows*cell)
1283 // tracks the mount bottom exactly until a new row fits.
1284 for (let height = 88; height < 104; height += 1) {
1285 const rows = Math.max(1, Math.floor((height - 8) / 16));
1286 const origin = terminalContentOriginY(height, 4, rows, 16, true);
1287 expect(origin + rows * 16).toBe(height - 4);
1288 }
1289 });
1290});
1291
1292describe("terminalWheelDeltaRows", () => {
1293 it("converts line-mode deltas into whole rows", () => {
1294 const result = terminalWheelDeltaRows({ deltaY: 3, deltaMode: 1 }, 16, 24, 0);
1295 expect(result.rows).toBe(3);
1296 expect(result.remainder).toBe(0);
1297 });
1298
1299 it("accumulates fractional pixel deltas across events", () => {
1300 let remainder = 0;
1301 let scrolled = 0;
1302 for (let index = 0; index < 4; index += 1) {
1303 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
1304 remainder = result.remainder;
1305 scrolled += result.rows;
1306 }
1307 expect(scrolled).toBe(1);
1308 expect(remainder).toBeCloseTo(4 / 16);
1309 });
1310
1311 it("keeps direction for negative page-mode deltas", () => {
1312 const result = terminalWheelDeltaRows({ deltaY: -1, deltaMode: 2 }, 16, 24, 0);
1313 expect(result.rows).toBe(-24);
1314 expect(result.remainder).toBe(0);
1315 });
1316});
1317
1318describe("terminalWheelArrowData", () => {
1319 it("emits one arrow per row honoring application cursor keys", () => {
1320 expect(terminalWheelArrowData(-2, false)).toBe("\u001b[A\u001b[A");
1321 expect(terminalWheelArrowData(3, false)).toBe("\u001b[B\u001b[B\u001b[B");
1322 expect(terminalWheelArrowData(-1, true)).toBe("\u001bOA");
1323 expect(terminalWheelArrowData(0, true)).toBe("");
1324 });
1325});
1326
1327describe("advanceTerminalSelectionClickSequence", () => {
1328 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
1329 const first = advanceTerminalSelectionClickSequence(null, {
1330 clientX: 20,
1331 clientY: 30,
1332 timeStamp: 1_000,
1333 });
1334 const second = advanceTerminalSelectionClickSequence(first, {
1335 clientX: 22,
1336 clientY: 29,
1337 timeStamp: 1_200,
1338 });
1339 const third = advanceTerminalSelectionClickSequence(second, {
1340 clientX: 21,
1341 clientY: 31,
1342 timeStamp: 1_400,
1343 });
1344
1345 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
1346 });
1347
1348 it("starts over after movement, delay, or a completed triple click", () => {
1349 const previous = { count: 3, time: 1_000, x: 20, y: 30 };
1350 expect(
1351 advanceTerminalSelectionClickSequence(previous, {
1352 clientX: 20,
1353 clientY: 30,
1354 timeStamp: 1_100,
1355 }).count,
1356 ).toBe(1);
1357 expect(
1358 advanceTerminalSelectionClickSequence(previous, {
1359 clientX: 30,
1360 clientY: 30,
1361 timeStamp: 1_100,
1362 }).count,
1363 ).toBe(1);
1364 expect(
1365 advanceTerminalSelectionClickSequence(previous, {
1366 clientX: 20,
1367 clientY: 30,
1368 timeStamp: 1_501,
1369 }).count,
1370 ).toBe(1);
1371 });
1372});
1373
1374describe("terminal scrollbar", () => {
1375 it("maps Ghostty's viewport state to a proportional thumb", () => {
1376 expect(terminalScrollbarGeometry({ total: 100, offset: 40, len: 20 }, 200)).toEqual({
1377 thumbHeight: 40,
1378 thumbTop: 80,
1379 maxOffset: 80,
1380 });
1381 expect(terminalScrollbarGeometry({ total: 100, offset: 0, len: 100 }, 200)).toBeNull();
1382 });
1383
1384 it("keeps the thumb usable for large scrollback and maps dragging back to rows", () => {
1385 const state = { total: 10_000, offset: 0, len: 20 };
1386 expect(terminalScrollbarGeometry(state, 200)).toEqual({
1387 thumbHeight: 18,
1388 thumbTop: 0,
1389 maxOffset: 9_980,
1390 });
1391 expect(terminalScrollbarOffsetAtPointer(state, 200, 191, 9)).toBe(9_980);
1392 });
1393});