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

surface.test.ts

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