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

surface.test.ts

822 lines27.9 KB

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.each([
516 { text: "https://example.com/日本", cols: 80, end: { x: 23, y: 0 } },
517 { text: "src/日本/main.ts:3:1", cols: 80, end: { x: 19, y: 0 } },
518 { text: "https://example.com/🙂", cols: 80, end: { x: 21, y: 0 } },
519 { text: "https://example.com/日本", cols: 23, end: { x: 1, y: 1 } },
520 ])("keeps every cell of $text clickable at $cols columns", async ({ text, cols, end }) => {
521 const core = await GhosttyTerminalCore.create(
522 cols,
523 3,
524 8,
525 16,
526 {
527 foreground: { r: 255, g: 255, b: 255 },
528 background: { r: 0, g: 0, b: 0 },
529 cursor: { r: 255, g: 255, b: 255 },
530 },
531 () => {},
532 );
533 try {
534 core.write(text + " next");
535 const rows = core.snapshot().rowData;
536 for (let y = 0; y <= end.y; y += 1) {
537 const lastColumn = y === end.y ? end.x : cols - 2;
538 for (let x = 0; x <= lastColumn; x += 1) {
539 expect(terminalLinkAtPositionWithRange(rows, y, x)).toEqual({
540 text,
541 range: { start: { x: 0, y: 0 }, end },
542 });
543 }
544 }
545 expect(terminalLinkAtPositionWithRange(rows, end.y, end.x + 1)).toBeNull();
546 } finally {
547 core.dispose();
548 }
549 });
550​
551 it("activates a wrapped quoted Windows path from its spaces and position suffix", () => {
552 const row = (text: string, isWrapContinuation: boolean): GhosttyRow => ({
553 cells: Array.from(text, (character) => cell(character)),
554 text,
555 isWrapContinuation,
556 wrapsToNext: false,
557 });
558 const first = String.raw`"C:\Users\Jane `;
559 const second = String.raw`Doe\index.ts":12:7`;
560 const rows = [row(first, false), row(second, true)];
561 const expected = {
562 text: String.raw`C:\Users\Jane Doe\index.ts:12:7`,
563 range: { start: { x: 1, y: 0 }, end: { x: second.length - 1, y: 1 } },
564 };
565 expect(terminalLinkAtPositionWithRange(rows, 0, first.length - 1)).toEqual(expected);
566 expect(terminalLinkAtPositionWithRange(rows, 1, second.length - 1)).toEqual(expected);
567 expect(terminalLinkAtPositionWithRange(rows, 0, 0)).toBeNull();
568 });
569​
570 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
571 const cells = [
572 cell("🙂"),
573 cell(""),
574 ...Array.from("https://t3.codes", (character) => cell(character)),
575 ];
576 const row: GhosttyRow = {
577 cells,
578 text: cells
579 .map((value) => value.text || " ")
580 .join("")
581 .trimEnd(),
582 isWrapContinuation: false,
583 wrapsToNext: false,
584 };
585​
586 expect(terminalLinkAtPositionWithRange([row], 0, 2)?.text).toBe("https://t3.codes");
587 expect(terminalLinkAtPositionWithRange([row], 0, cells.length - 1)?.text).toBe(
588 "https://t3.codes",
589 );
590 expect(terminalLinkAtPositionWithRange([row], 0, 0)).toBeNull();
591 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
592 start: { x: 2, y: 0 },
593 end: { x: cells.length - 1, y: 0 },
594 });
595 });
596​
597 it("uses shared path matching and reconstructs soft-wrapped links", () => {
598 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
599 cells: Array.from(text.padEnd(16), (character) => cell(character)),
600 text: text.trimEnd(),
601 isWrapContinuation,
602 wrapsToNext,
603 });
604 const rows = [
605 row("https://example.", false),
606 row("com/reference", true),
607 row("~/project/file", false),
608 row("C:\\repo\\file.ts", false),
609 ];
610​
611 expect(terminalLinkAtPositionWithRange(rows, 0, 8)?.text).toBe("https://example.com/reference");
612 expect(terminalLinkAtPositionWithRange(rows, 1, 4)?.text).toBe("https://example.com/reference");
613 expect(terminalLinkAtPositionWithRange(rows, 2, 2)?.text).toBe("~/project/file");
614 expect(terminalLinkAtPositionWithRange(rows, 3, 4)?.text).toBe("C:\\repo\\file.ts");
615 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
616 text: "https://example.com/reference",
617 range: {
618 start: { x: 0, y: 0 },
619 end: { x: 12, y: 1 },
620 },
621 });
622 });
623​
624 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
625 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
626 cells: Array.from(text.padEnd(16), (character) => cell(character)),
627 text: text.trimEnd(),
628 isWrapContinuation,
629 wrapsToNext,
630 });
631 const headCut = [row("ple.com/missing", true), row("head", true)];
632 expect(terminalLinkAtPositionWithRange(headCut, 0, 4)).toBeNull();
633 const tailCut = [row("https://t3.codes", false, true)];
634 expect(terminalLinkAtPositionWithRange(tailCut, 0, 8)).toBeNull();
635 const complete = [row("https://t3.codes", false), row("", false)];
636 expect(terminalLinkAtPositionWithRange(complete, 0, 8)?.text).toBe("https://t3.codes");
637 const wideFull: GhosttyRow = {
638 cells: [
639 { ...cell("🙂"), wide: 1 },
640 { ...cell(""), wide: 2 },
641 ...Array.from("https://t3.code", (character) => cell(character)),
642 ],
643 text: "🙂 https://t3.code",
644 isWrapContinuation: false,
645 wrapsToNext: true,
646 };
647 expect(terminalLinkAtPositionWithRange([wideFull], 0, 8)).toBeNull();
648 const unwrittenTail: GhosttyRow = {
649 cells: [
650 ...Array.from("https://t3.codes", (character) => cell(character)),
651 cell(""),
652 cell(""),
653 ],
654 text: "https://t3.codes",
655 isWrapContinuation: false,
656 wrapsToNext: false,
657 };
658 expect(terminalLinkAtPositionWithRange([unwrittenTail], 0, 8)?.text).toBe("https://t3.codes");
659 });
660});
661​
662describe("isTerminalCopyShortcut", () => {
663 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
664 ctrlKey: false,
665 key: "c",
666 metaKey: false,
667 shiftKey: false,
668 ...overrides,
669 });
670​
671 it("keeps Ctrl+C available for SIGINT on macOS", () => {
672 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
673 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
674 });
675​
676 it("uses the produced character instead of the physical key position", () => {
677 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
678 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
679 });
680});
681​
682describe("applyTerminalCopyEvent", () => {
683 // regression: #7678 copying a terminal selection produced a blank clipboard
684 it("leaves the writeText fallback alive when clipboardData is missing", () => {
685 // Electron menu Copy often omits clipboardData.
686 expect(applyTerminalCopyEvent("ls -la", null)).toEqual({
687 preventDefault: false,
688 claimWriteFallback: false,
689 });
690 expect(applyTerminalCopyEvent("", { setData: vi.fn() })).toEqual({
691 preventDefault: false,
692 claimWriteFallback: false,
693 });
694 });
695​
696 it("primes the current selection before a copy event with no clipboardData", () => {
697 const input = {
698 value: "stale",
699 selectionStart: 0,
700 selectionEnd: 0,
701 select() {
702 this.selectionStart = 0;
703 this.selectionEnd = this.value.length;
704 },
705 };
706 primeTerminalCopyInput(input, "git status");
707 expect(applyTerminalCopyEvent("git status", null)).toEqual({
708 preventDefault: false,
709 claimWriteFallback: false,
710 });
711 expect(input.value).toBe("git status");
712 expect(input.selectionStart).toBe(0);
713 expect(input.selectionEnd).toBe(10);
714 });
715});
716​
717describe("primeTerminalCopyInput", () => {
718 it("does not wipe an IME candidate that replaced the primed copy", () => {
719 const input = { value: "", select() {} };
720 primeTerminalCopyInput(input, "git status");
721 input.value = "あ";
722 clearPrimedTerminalCopyInput(input, "git status");
723 expect(input.value).toBe("あ");
724 });
725});
726​
727describe("isTerminalCompositionKey", () => {
728 const event = (
729 overrides: Partial<Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">> = {},
730 ) => ({
731 isComposing: false,
732 key: "a",
733 keyCode: 65,
734 ...overrides,
735 });
736​
737 it("treats in-progress IME keydowns as composition so the copy primer cannot wipe them", () => {
738 expect(isTerminalCompositionKey(event({ isComposing: true }), false)).toBe(true);
739 expect(isTerminalCompositionKey(event(), true)).toBe(true);
740 expect(isTerminalCompositionKey(event({ key: "Process" }), false)).toBe(true);
741 expect(isTerminalCompositionKey(event({ keyCode: 229 }), false)).toBe(true);
742 });
743});
744​
745describe("application mouse reporting", () => {
746 it("drops repeated motion reports until another mouse action resets the cell", () => {
747 const first = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", "");
748 expect(first).toEqual({ send: true, nextMotionData: "\u001b[<35;8;4M" });
749​
750 const duplicate = resolveTerminalMouseData("motion", "\u001b[<35;8;4M", first.nextMotionData);
751 expect(duplicate).toEqual({ send: false, nextMotionData: "\u001b[<35;8;4M" });
752​
753 const press = resolveTerminalMouseData("press", "\u001b[<0;8;4M", duplicate.nextMotionData);
754 expect(press).toEqual({ send: true, nextMotionData: "" });
755​
756 expect(resolveTerminalMouseData("motion", "\u001b[<35;8;4M", press.nextMotionData)).toEqual({
757 send: true,
758 nextMotionData: "\u001b[<35;8;4M",
759 });
760 });
761});
762​
763describe("terminalContentOriginY", () => {
764 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
765 for (let height = 88; height < 104; height += 1) {
766 const rows = Math.max(1, Math.floor((height - 8) / 16));
767 const origin = terminalContentOriginY(height, 4, rows, 16, true);
768 expect(origin + rows * 16).toBe(height - 4);
769 }
770 });
771});
772​
773describe("terminalWheelDeltaRows", () => {
774 it("accumulates fractional pixel deltas across events", () => {
775 let remainder = 0;
776 let scrolled = 0;
777 for (let index = 0; index < 4; index += 1) {
778 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
779 remainder = result.remainder;
780 scrolled += result.rows;
781 }
782 expect(scrolled).toBe(1);
783 expect(remainder).toBeCloseTo(4 / 16);
784 });
785});
786​
787// regression: #19492 drag selection scrolled one row per tick however far past the edge
788describe("terminalSelectionAutoscrollRows", () => {
789 it("scrolls more rows per tick the farther the pointer is past an edge", () => {
790 const top = 100;
791 const bottom = 500;
792 expect(terminalSelectionAutoscrollRows(300, top, bottom)).toBe(0);
793 expect(terminalSelectionAutoscrollRows(99, top, bottom)).toBe(-1);
794 expect(terminalSelectionAutoscrollRows(75, top, bottom)).toBe(-8);
795 expect(terminalSelectionAutoscrollRows(501, top, bottom)).toBe(1);
796 expect(terminalSelectionAutoscrollRows(525, top, bottom)).toBe(8);
797 expect(terminalSelectionAutoscrollRows(550, top, bottom)).toBe(15);
798 expect(terminalSelectionAutoscrollRows(2_000, top, bottom)).toBe(15);
799 });
800});
801​
802describe("advanceTerminalSelectionClickSequence", () => {
803 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
804 const first = advanceTerminalSelectionClickSequence(null, {
805 clientX: 20,
806 clientY: 30,
807 timeStamp: 1_000,
808 });
809 const second = advanceTerminalSelectionClickSequence(first, {
810 clientX: 22,
811 clientY: 29,
812 timeStamp: 1_200,
813 });
814 const third = advanceTerminalSelectionClickSequence(second, {
815 clientX: 21,
816 clientY: 31,
817 timeStamp: 1_400,
818 });
819​
820 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
821 });
822});