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

surface.test.ts

1,386 lines49.5 KB

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