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