Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
4import {
5 advanceTerminalSelectionClickSequence,
6 applyTerminalCopyEvent,
7 clearPrimedTerminalCopyInput,
8 isTerminalCompositionKey,
9 isTerminalCopyShortcut,
10 primeTerminalCopyInput,
11 resolveTerminalMouseData,
12 terminalLinkAtPositionWithRange,
13 terminalContentOriginY,
14 terminalWheelDeltaRows,
15 GhosttyTerminalSurface,
16 type GhosttyTerminalSurfaceOptions,
17} from "./surface";
18
19vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
20 default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
21}));
22vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
23 default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
24}));
25
26describe("GhosttyTerminalSurface visibility", () => {
27 const surfaces = new Set<GhosttyTerminalSurface>();
28
29 function key(
30 surface: GhosttyTerminalSurface,
31 key: string,
32 code: string,
33 modifiers: Partial<
34 Pick<
35 KeyboardEvent,
36 | "altKey"
37 | "ctrlKey"
38 | "metaKey"
39 | "shiftKey"
40 | "isComposing"
41 | "repeat"
42 | "keyCode"
43 | "getModifierState"
44 >
45 > = {},
46 type = "keydown",
47 target: EventTarget = surface.input,
48 ) {
49 const event = Object.assign(new Event(type, { cancelable: true }), {
50 key,
51 code,
52 altKey: false,
53 ctrlKey: false,
54 metaKey: false,
55 shiftKey: false,
56 isComposing: false,
57 repeat: false,
58 keyCode: 0,
59 getModifierState: () => false,
60 ...modifiers,
61 });
62 target.dispatchEvent(event);
63 return event;
64 }
65
66 function createHarness() {
67 vi.useFakeTimers();
68 const frames = new Map<number, FrameRequestCallback>();
69 const resizeTargets = new Map<(entries: { target: Element }[]) => void, Set<Element>>();
70 const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
71 let frameId = 0;
72 const requestFrame = vi.fn((callback: FrameRequestCallback) => {
73 frames.set(++frameId, callback);
74 return frameId;
75 });
76
77 class TerminalTestElement extends EventTarget {
78 style: Record<string, string> = {};
79 parentElement: TerminalTestElement | null = null;
80 clientWidth = 168;
81 clientHeight = 104;
82 width = 300;
83 height = 150;
84 value = "";
85 private readonly captures = new Set<number>();
86
87 setAttribute() {}
88 append(...children: TerminalTestElement[]) {
89 for (const child of children) child.parentElement = this;
90 }
91 replaceChildren(...children: TerminalTestElement[]) {
92 this.append(...children);
93 }
94 remove() {
95 this.parentElement = null;
96 }
97 getContext() {
98 return context;
99 }
100 focus() {
101 this.dispatchEvent(new Event("focus"));
102 }
103 setPointerCapture(pointerId: number) {
104 this.captures.add(pointerId);
105 }
106 hasPointerCapture(pointerId: number) {
107 return this.captures.has(pointerId);
108 }
109 releasePointerCapture(pointerId: number) {
110 this.captures.delete(pointerId);
111 }
112 getBoundingClientRect() {
113 return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
114 }
115 }
116
117 const canvas = new TerminalTestElement();
118 const mount = new TerminalTestElement();
119 const context = {
120 canvas,
121 beginPath() {},
122 clip() {},
123 rect() {},
124 resetTransform() {},
125 restore() {},
126 save() {},
127 setTransform() {},
128 fillRect: (...args: number[]) => paint("fillRect", args),
129 strokeRect: (...args: number[]) => paint("strokeRect", args),
130 fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
131 measureText: (text: string) => ({
132 width: text.length * 8,
133 actualBoundingBoxAscent: 9,
134 actualBoundingBoxDescent: 3,
135 }),
136 };
137 vi.stubGlobal("document", {
138 createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
139 fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
140 });
141 vi.stubGlobal(
142 "window",
143 Object.assign(new EventTarget(), {
144 devicePixelRatio: 1,
145 innerHeight: 104,
146 requestAnimationFrame: requestFrame,
147 cancelAnimationFrame: (id: number) => frames.delete(id),
148 setTimeout,
149 clearTimeout,
150 setInterval,
151 clearInterval,
152 matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
153 }),
154 );
155 vi.stubGlobal(
156 "ResizeObserver",
157 class {
158 constructor(private readonly callback: (entries: { target: Element }[]) => void) {
159 resizeTargets.set(callback, new Set());
160 }
161 observe(target: Element) {
162 resizeTargets.get(this.callback)?.add(target);
163 }
164 unobserve(target: Element) {
165 resizeTargets.get(this.callback)?.delete(target);
166 }
167 disconnect() {
168 resizeTargets.delete(this.callback);
169 }
170 },
171 );
172 const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
173 const onData = vi.fn<(data: string) => void>();
174
175 return {
176 canvas,
177 mount,
178 frames,
179 paint,
180 requestFrame,
181 snapshot,
182 onData,
183 get renderedSnapshot() {
184 const result = snapshot.mock.results.at(-1);
185 if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
186 return result.value;
187 },
188 flushFrame() {
189 const queued = [...frames.values()];
190 frames.clear();
191 for (const callback of queued) callback(0);
192 },
193 resize() {
194 for (const [callback, targets] of resizeTargets) {
195 callback([...targets].map((target) => ({ target })));
196 }
197 },
198 pointer(
199 type: string,
200 clientX: number,
201 buttons: number,
202 modifiers: boolean | Partial<Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">> = {},
203 button = 0,
204 clientY = 5,
205 ) {
206 canvas.dispatchEvent(
207 Object.assign(new Event(type, { cancelable: true }), {
208 clientX,
209 clientY,
210 pointerId: 1,
211 button,
212 buttons,
213 ...(typeof modifiers === "boolean" ? { shiftKey: modifiers } : modifiers),
214 }),
215 );
216 },
217 touch(type: string, clientY: number, pointerId = 2) {
218 canvas.dispatchEvent(
219 Object.assign(new Event(type, { cancelable: true }), {
220 clientX: 40,
221 clientY,
222 pointerId,
223 pointerType: "touch",
224 isPrimary: pointerId === 2,
225 button: 0,
226 buttons: type === "pointerup" ? 0 : 1,
227 shiftKey: false,
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("preserves shell Ctrl+A and ordinary application navigation", async () => {
263 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
264 const harness = createHarness();
265 const surface = await harness.create({ beforeKey: () => true });
266 key(surface, "a", "KeyA", { ctrlKey: true });
267 key(surface, "PageUp", "PageUp");
268 key(surface, "PageDown", "PageDown");
269 key(surface, "Home", "Home");
270 key(surface, "End", "End");
271 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
272 "\x01",
273 "\x1b[5~",
274 "\x1b[6~",
275 "\x1b[H",
276 "\x1b[F",
277 ]);
278 expect(surface.hasSelection()).toBe(false);
279 });
280
281 it("leaves modified history keys with alternate-screen applications", async () => {
282 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
283 const harness = createHarness();
284 const surface = await harness.create({ beforeKey: () => true });
285 surface.write("\x1b[?1049happ");
286 key(surface, "PageUp", "PageUp", { shiftKey: true });
287 key(surface, "End", "End", { ctrlKey: true, shiftKey: true });
288 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual(["\x1b[5;2~", "\x1b[1;6F"]);
289 surface.selectAll();
290 expect(surface.getSelection()).toBe("app");
291 surface.write("\x1b[?1049l");
292 expect(surface.getSelection()).toBe("");
293 });
294
295 it("suppresses local shortcut releases in Kitty sessions, including read-only observers", async () => {
296 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
297 const harness = createHarness();
298 const surface = await harness.create({ beforeKey: () => true });
299 surface.input.readOnly = true;
300 surface.write("history\x1b[>31u");
301 for (const [name, code, modifiers] of [
302 ["PageUp", "PageUp", { shiftKey: true }],
303 ["Home", "Home", { ctrlKey: true, shiftKey: true }],
304 ["a", "KeyA", { ctrlKey: true, shiftKey: true }],
305 ] as const) {
306 key(surface, name, code, modifiers);
307 key(surface, name, code, modifiers, "keyup");
308 }
309 expect(surface.getSelection()).toBe("history");
310 expect(harness.onData).not.toHaveBeenCalled();
311
312 key(surface, "PageUp", "PageUp");
313 key(surface, "PageUp", "PageUp", {}, "keyup");
314 expect(harness.onData).toHaveBeenCalledTimes(2);
315 expect(harness.onData.mock.calls[1]?.[0]).toContain(":3");
316 });
317
318 it("reports Kitty releases only for presses encoded by this surface", async () => {
319 const harness = createHarness();
320 const surface = await harness.create({ beforeKey: () => true });
321 surface.write("\x1b[>11u");
322
323 key(surface, "a", "KeyA");
324 key(surface, "a", "KeyA", {}, "keyup");
325 key(surface, "Control", "ControlLeft", { ctrlKey: true });
326 // App capture stops Ctrl+D before it reaches the terminal input.
327 key(surface, "d", "KeyD", { ctrlKey: true }, "keydown", window);
328 key(surface, "d", "KeyD", { ctrlKey: true }, "keyup");
329 key(surface, "Control", "ControlLeft", {}, "keyup");
330
331 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
332 "\x1b[97u",
333 "\x1b[97;1:3u",
334 "\x1b[57442;5u",
335 "\x1b[57442;1:3u",
336 ]);
337 });
338
339 it("keeps a held Kitty press through focus changes and an app-consumed repeat", async () => {
340 const harness = createHarness();
341 let consumeRepeat = false;
342 const surface = await harness.create({ beforeKey: () => !consumeRepeat });
343 surface.write("\x1b[>11u");
344
345 key(surface, "a", "KeyA");
346 key(surface, "a", "KeyA", { repeat: true });
347 surface.input.dispatchEvent(new Event("blur"));
348 window.dispatchEvent(new Event("blur"));
349 window.dispatchEvent(new Event("focus"));
350 surface.input.dispatchEvent(new Event("focus"));
351 consumeRepeat = true;
352 key(surface, "a", "KeyA", { repeat: true });
353 key(surface, "a", "KeyA", {}, "keyup");
354
355 expect(harness.onData.mock.calls.map(([data]) => data)).toEqual([
356 "\x1b[97u",
357 "\x1b[97;1:2u",
358 "\x1b[97;1:3u",
359 ]);
360 });
361
362 it("honors host interception, IME candidates, and AltGr before local shortcuts", async () => {
363 vi.stubGlobal("navigator", { platform: "Linux x86_64" });
364 const harness = createHarness();
365 let allow = false;
366 const surface = await harness.create({ beforeKey: () => allow });
367 surface.write("hello\x1b[>31u");
368 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
369 key(surface, "a", "KeyA", {}, "keyup");
370 expect(surface.hasSelection()).toBe(false);
371 allow = true;
372 surface.input.value = "候補";
373 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, isComposing: true });
374 key(surface, "a", "KeyA", {}, "keyup");
375 key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true, keyCode: 229 });
376 key(surface, "a", "KeyA", {}, "keyup");
377 key(surface, "a", "KeyA", {
378 ctrlKey: true,
379 shiftKey: true,
380 altKey: true,
381 getModifierState: (modifier) => modifier === "AltGraph",
382 });
383 key(surface, "a", "KeyA", {}, "keyup");
384 expect(surface.input.value).toBe("候補");
385 expect(surface.hasSelection()).toBe(false);
386 expect(harness.onData).not.toHaveBeenCalled();
387 });
388
389 function paste(surface: GhosttyTerminalSurface, text: string) {
390 surface.input.dispatchEvent(
391 Object.assign(new Event("paste", { cancelable: true }), {
392 clipboardData: { getData: () => text },
393 }),
394 );
395 }
396
397 it.each(["native", "clipboard"])("pastes once when %s arrives first", async (first) => {
398 const harness = createHarness();
399 const read = Promise.resolve("echo hi");
400 vi.stubGlobal("navigator", {
401 platform: "MacIntel",
402 clipboard: { readText: () => read },
403 });
404 const surface = await harness.create({ beforeKey: () => true });
405
406 key(surface, "v", "KeyV", { metaKey: true });
407 if (first === "native") paste(surface, "echo hi");
408 await read;
409 if (first === "clipboard") paste(surface, "echo hi");
410
411 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
412 });
413
414 it.each(["V keyup", "blur", "Meta keyup without V keyup"])(
415 "accepts a later identical menu paste after %s",
416 async (end) => {
417 const harness = createHarness();
418 const read = Promise.resolve("echo hi");
419 vi.stubGlobal("navigator", {
420 platform: "MacIntel",
421 clipboard: { readText: () => read },
422 });
423 const surface = await harness.create({ beforeKey: () => true });
424
425 key(surface, "v", "KeyV", { metaKey: true });
426 await read;
427 expect(harness.onData.mock.calls).toEqual([["echo hi"]]);
428 if (end === "blur") surface.input.dispatchEvent(new Event("blur"));
429 else if (end === "V keyup") key(surface, "v", "KeyV", { metaKey: true }, "keyup");
430 // macOS can omit V keyup while Command is held.
431 else key(surface, "Meta", "MetaLeft", {}, "keyup");
432 paste(surface, "echo hi");
433
434 expect(harness.onData.mock.calls).toEqual([["echo hi"], ["echo hi"]]);
435 },
436 );
437
438 it("does not activate a link replaced before pointer release", async () => {
439 const harness = createHarness();
440 const onLinkActivate = vi.fn();
441 const surface = await harness.create({ onLinkActivate });
442 surface.write("https://first.example");
443 harness.flushFrame();
444
445 harness.pointer("pointerdown", 5, 1);
446 surface.write("\x1b[2J\x1b[Hhttps://second.example");
447 harness.flushFrame();
448 harness.pointer("pointerup", 5, 0);
449
450 expect(onLinkActivate).not.toHaveBeenCalled();
451 });
452
453 it.each([false, true])(
454 "uses visibility %s if it changes while WASM initializes",
455 async (visible) => {
456 const harness = createHarness();
457 let markCreated!: () => void;
458 const created = new Promise<void>((resolve) => {
459 markCreated = resolve;
460 });
461 let finishLoading!: () => void;
462 const release = new Promise<void>((resolve) => {
463 finishLoading = resolve;
464 });
465 const create = GhosttyTerminalCore.create;
466 vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
467 const core = await create(...args);
468 markCreated();
469 await release;
470 return core;
471 });
472 let currentVisible = !visible;
473 const pending = harness.create({
474 get visible() {
475 return currentVisible;
476 },
477 });
478 await created;
479 currentVisible = visible;
480 harness.paint.mockClear();
481 finishLoading();
482 const surface = await pending;
483
484 expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
485 if (!visible) expect(harness.paint).not.toHaveBeenCalled();
486 surface.write("ready\x1b[5n");
487 expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
488 if (!visible) {
489 expect(harness.frames.size).toBe(0);
490 surface.setVisible(true);
491 } else {
492 harness.flushFrame();
493 }
494 expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
495 },
496 );
497});
498
499const cell = (text: string): GhosttyCell => ({
500 text,
501 wide: 0,
502 foreground: { r: 255, g: 255, b: 255 },
503 background: { r: 0, g: 0, b: 0 },
504 bold: false,
505 italic: false,
506 invisible: false,
507 strikethrough: false,
508 overline: false,
509 underline: false,
510 selected: false,
511});
512
513describe("terminalLinkAtPositionWithRange", () => {
514 it("activates a wrapped quoted Windows path from its spaces and position suffix", () => {
515 const row = (text: string, isWrapContinuation: boolean): GhosttyRow => ({
516 cells: Array.from(text, (character) => cell(character)),
517 text,
518 isWrapContinuation,
519 wrapsToNext: false,
520 });
521 const first = String.raw`"C:\Users\Jane `;
522 const second = String.raw`Doe\index.ts":12:7`;
523 const rows = [row(first, false), row(second, true)];
524 const expected = {
525 text: String.raw`C:\Users\Jane Doe\index.ts:12:7`,
526 range: { start: { x: 1, y: 0 }, end: { x: second.length - 1, y: 1 } },
527 };
528 expect(terminalLinkAtPositionWithRange(rows, 0, first.length - 1)).toEqual(expected);
529 expect(terminalLinkAtPositionWithRange(rows, 1, second.length - 1)).toEqual(expected);
530 expect(terminalLinkAtPositionWithRange(rows, 0, 0)).toBeNull();
531 });
532
533 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
534 const cells = [
535 cell("🙂"),
536 cell(""),
537 ...Array.from("https://t3.codes", (character) => cell(character)),
538 ];
539 const row: GhosttyRow = {
540 cells,
541 text: cells
542 .map((value) => value.text || " ")
543 .join("")
544 .trimEnd(),
545 isWrapContinuation: false,
546 wrapsToNext: false,
547 };
548
549 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
550 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
551 "https://t3.codes",
552 );
553 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
554 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
555 start: { x: 2, y: 0 },
556 end: { x: cells.length - 1, y: 0 },
557 });
558 });
559
560 it("uses shared path matching and reconstructs soft-wrapped links", () => {
561 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
562 cells: Array.from(text.padEnd(16), (character) => cell(character)),
563 text: text.trimEnd(),
564 isWrapContinuation,
565 wrapsToNext,
566 });
567 const rows = [
568 row("https://example.", false),
569 row("com/reference", true),
570 row("~/project/file", false),
571 row("C:\\repo\\file.ts", false),
572 ];
573
574 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
575 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
576 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
577 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
578 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
579 text: "https://example.com/reference",
580 range: {
581 start: { x: 0, y: 0 },
582 end: { x: 12, y: 1 },
583 },
584 });
585 });
586
587 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
588 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
589 cells: Array.from(text.padEnd(16), (character) => cell(character)),
590 text: text.trimEnd(),
591 isWrapContinuation,
592 wrapsToNext,
593 });
594 const headCut = [row("ple.com/missing", true), row("head", true)];
595 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
596 const tailCut = [row("https://t3.codes", false, true)];
597 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
598 const complete = [row("https://t3.codes", false), row("", false)];
599 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
600 const wideFull: GhosttyRow = {
601 cells: [
602 { ...cell("🙂"), wide: 1 },
603 { ...cell(""), wide: 2 },
604 ...Array.from("https://t3.code", (character) => cell(character)),
605 ],
606 text: "🙂 https://t3.code",
607 isWrapContinuation: false,
608 wrapsToNext: true,
609 };
610 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
611 const unwrittenTail: GhosttyRow = {
612 cells: [
613 ...Array.from("https://t3.codes", (character) => cell(character)),
614 cell(""),
615 cell(""),
616 ],
617 text: "https://t3.codes",
618 isWrapContinuation: false,
619 wrapsToNext: false,
620 };
621 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
622 });
623});
624
625describe("isTerminalCopyShortcut", () => {
626 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
627 ctrlKey: false,
628 key: "c",
629 metaKey: false,
630 shiftKey: false,
631 ...overrides,
632 });
633
634 it("keeps Ctrl+C available for SIGINT on macOS", () => {
635 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
636 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
637 });
638
639 it("uses the produced character instead of the physical key position", () => {
640 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
641 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
642 });
643});
644
645describe("applyTerminalCopyEvent", () => {
646 // regression: #7678 copying a terminal selection produced a blank clipboard
647 it("leaves the writeText fallback alive when clipboardData is missing", () => {
648 // Electron menu Copy often omits clipboardData.
649 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
650 preventDefault: false,
651 claimWriteFallback: false,
652 });
653 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
654 preventDefault: false,
655 claimWriteFallback: false,
656 });
657 });
658
659 it("primes the current selection before a copy event with no clipboardData", () => {
660 const input = {
661 value: "stale",
662 selectionStart: 0,
663 selectionEnd: 0,
664 select() {
665 this.selectionStart = 0;
666 this.selectionEnd = this.value.length;
667 },
668 };
669 primeTerminalCopyInput(input, "git status");
670 expect(applyTerminalCopyEvent("git status", null)).toEqual({
671 preventDefault: false,
672 claimWriteFallback: false,
673 });
674 expect(input.value).toBe("git status");
675 expect(input.selectionStart).toBe(0);
676 expect(input.selectionEnd).toBe(10);
677 });
678});
679
680describe("primeTerminalCopyInput", () => {
681 it("does not wipe an IME candidate that replaced the primed copy", () => {
682 const input = { value: "", select() {} };
683 primeTerminalCopyInput(input, "git status");
684 input.value = "あ";
685 clearPrimedTerminalCopyInput(input, "git status");
686 expect(input.value).toBe("あ");
687 });
688});
689
690describe("isTerminalCompositionKey", () => {
691 const event = (
692 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
693 ) => ({
694 isComposing: false,
695 key: "a",
696 keyCode: 65,
697 ...overrides,
698 });
699
700 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
701 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
702 expect(isTerminalCompositionKey(event(), true)).toBe(true);
703 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
704 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
705 });
706});
707
708describe("application mouse reporting", () => {
709 it("drops repeated motion reports until another mouse action resets the cell", () => {
710 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
711 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
712
713 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
714 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
715
716 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
717 expect(press).toEqual({ send: true, nextMotionData: "" });
718
719 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
720 send: true,
721 nextMotionData: "\u001b[<35;8;4M",
722 });
723 });
724});
725
726describe("terminalContentOriginY", () => {
727 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
728 for (let height = 88; height < 104; height += 1) {
729 const rows = Math.max(1, Math.floor((height - 8) / 16));
730 const origin = terminalContentOriginY(height, 4, rows, 16, true);
731 expect(origin + rows * 16).toBe(height - 4);
732 }
733 });
734});
735
736describe("terminalWheelDeltaRows", () => {
737 it("accumulates fractional pixel deltas across events", () => {
738 let remainder = 0;
739 let scrolled = 0;
740 for (let index = 0; index < 4; index += 1) {
741 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
742 remainder = result.remainder;
743 scrolled += result.rows;
744 }
745 expect(scrolled).toBe(1);
746 expect(remainder).toBeCloseTo(4 / 16);
747 });
748});
749
750describe("advanceTerminalSelectionClickSequence", () => {
751 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
752 const first = advanceTerminalSelectionClickSequence(null, {
753 clientX: 20,
754 clientY: 30,
755 timeStamp: 1_000,
756 });
757 const second = advanceTerminalSelectionClickSequence(first, {
758 clientX: 22,
759 clientY: 29,
760 timeStamp: 1_200,
761 });
762 const third = advanceTerminalSelectionClickSequence(second, {
763 clientX: 21,
764 clientY: 31,
765 timeStamp: 1_400,
766 });
767
768 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
769 });
770});