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

surface.test.ts

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