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

surface.test.ts

494 lines17.7 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2​
3import type { GhosttyCell, GhosttyRow } from "./core";
4import {
5 DEFAULT_TERMINAL_FONT_FAMILY,
6 DEFAULT_TERMINAL_FONT_SIZE,
7 advanceTerminalSelectionClickSequence,
8 ghosttyMouseButton,
9 isTerminalAltGraphText,
10 isTerminalCompositionCommitInput,
11 isTerminalCopyShortcut,
12 isTerminalLinkPointerGesture,
13 isTerminalPasteShortcut,
14 loadTerminalFontFamily,
15 shouldBlinkTerminalCursor,
16 shouldReportTerminalMouse,
17 shouldShowTerminalLinkHover,
18 terminalGridCellAt,
19 terminalScrollbarGeometry,
20 terminalScrollbarOffsetAtPointer,
21 terminalLinkAtColumn,
22 terminalLinkAtPosition,
23 terminalLinkAtPositionWithRange,
24 terminalContentOriginY,
25 terminalFontFamily,
26 terminalFontSize,
27 terminalWheelArrowData,
28 terminalWheelDeltaRows,
29} from "./surface";
30​
31const cell = (text: string): GhosttyCell => ({
32 text,
33 wide: 0,
34 foreground: { r: 255, g: 255, b: 255 },
35 background: { r: 0, g: 0, b: 0 },
36 bold: false,
37 italic: false,
38 invisible: false,
39 strikethrough: false,
40 overline: false,
41 underline: false,
42 selected: false,
43});
44​
45describe("isTerminalAltGraphText", () => {
46 it("defers printable AltGr output to the textarea input event", () => {
47 expect(
48 isTerminalAltGraphText({
49 key: "@",
50 getModifierState: (modifier) => modifier === "AltGraph",
51 }),
52 ).toBe(true);
53 expect(
54 isTerminalAltGraphText({
55 key: "ArrowRight",
56 getModifierState: (modifier) => modifier === "AltGraph",
57 }),
58 ).toBe(false);
59 });
60});
61​
62describe("terminalGridCellAt", () => {
63 const options = {
64 bounds: { left: 100, top: 200 },
65 cols: 3,
66 rows: 2,
67 metrics: { width: 10, height: 20 },
68 padding: 4,
69 originY: 24,
70 };
71​
72 it("maps points inside the rendered grid without clamping its padding", () => {
73 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 224 })).toEqual({
74 x: 0,
75 y: 0,
76 });
77 expect(terminalGridCellAt({ ...options, clientX: 133, clientY: 263 })).toEqual({
78 x: 2,
79 y: 1,
80 });
81 expect(terminalGridCellAt({ ...options, clientX: 103, clientY: 224 })).toBeNull();
82 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 223 })).toBeNull();
83 expect(terminalGridCellAt({ ...options, clientX: 134, clientY: 224 })).toBeNull();
84 expect(terminalGridCellAt({ ...options, clientX: 104, clientY: 264 })).toBeNull();
85 });
86});
87​
88describe("shouldBlinkTerminalCursor", () => {
89 const blinking = {
90 focused: true,
91 cursorBlinking: true,
92 cursorVisible: true,
93 reducedMotion: false,
94 };
95​
96 it("blinks a focused visible cursor the terminal asked to blink", () => {
97 expect(shouldBlinkTerminalCursor(blinking)).toBe(true);
98 });
99​
100 it("holds the cursor steady when blinking would be unwanted", () => {
101 // Unfocused surfaces draw a steady hollow cursor, DECSCUSR steady styles and
102 // DEC mode 12 turn blinking off, a hidden cursor has nothing to toggle, and
103 // reduced-motion readers get no permanently animating element.
104 expect(shouldBlinkTerminalCursor({ ...blinking, focused: false })).toBe(false);
105 expect(shouldBlinkTerminalCursor({ ...blinking, cursorBlinking: false })).toBe(false);
106 expect(shouldBlinkTerminalCursor({ ...blinking, cursorVisible: false })).toBe(false);
107 expect(shouldBlinkTerminalCursor({ ...blinking, reducedMotion: true })).toBe(false);
108 });
109});
110​
111describe("terminalLinkAtColumn", () => {
112 it("maps terminal cells to UTF-16 offsets after a wide emoji", () => {
113 const cells = [
114 cell("πŸ™‚"),
115 cell(""),
116 ...Array.from("https://t3.codes", (character) => cell(character)),
117 ];
118 const row: GhosttyRow = {
119 cells,
120 text: cells
121 .map((value) => value.text || " ")
122 .join("")
123 .trimEnd(),
124 isWrapContinuation: false,
125 wrapsToNext: false,
126 };
127​
128 expect(terminalLinkAtColumn(row, 2)).toBe("https://t3.codes");
129 expect(terminalLinkAtColumn(row, cells.length - 1)).toBe("https://t3.codes");
130 expect(terminalLinkAtColumn(row, 0)).toBeNull();
131 expect(terminalLinkAtPositionWithRange([row], 0, 8)?.range).toEqual({
132 start: { x: 2, y: 0 },
133 end: { x: cells.length - 1, y: 0 },
134 });
135 });
136​
137 it("uses shared path matching and reconstructs soft-wrapped links", () => {
138 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
139 cells: Array.from(text.padEnd(16), (character) => cell(character)),
140 text: text.trimEnd(),
141 isWrapContinuation,
142 wrapsToNext,
143 });
144 const rows = [
145 row("https://example.", false),
146 row("com/reference", true),
147 row("~/project/file", false),
148 row("C:\\repo\\file.ts", false),
149 ];
150​
151 expect(terminalLinkAtPosition(rows, 0, 8)).toBe("https://example.com/reference");
152 expect(terminalLinkAtPosition(rows, 1, 4)).toBe("https://example.com/reference");
153 expect(terminalLinkAtPosition(rows, 2, 2)).toBe("~/project/file");
154 expect(terminalLinkAtPosition(rows, 3, 4)).toBe("C:\\repo\\file.ts");
155 expect(terminalLinkAtPositionWithRange(rows, 1, 4)).toEqual({
156 text: "https://example.com/reference",
157 range: {
158 start: { x: 0, y: 0 },
159 end: { x: 12, y: 1 },
160 },
161 });
162 });
163​
164 it("refuses links truncated at the viewport edges instead of mis-resolving", () => {
165 const row = (text: string, isWrapContinuation: boolean, wrapsToNext = false): GhosttyRow => ({
166 cells: Array.from(text.padEnd(16), (character) => cell(character)),
167 text: text.trimEnd(),
168 isWrapContinuation,
169 wrapsToNext,
170 });
171 // The head of the wrapped line scrolled above the viewport.
172 const headCut = [row("ple.com/missing", true), row("head", true)];
173 expect(terminalLinkAtPosition(headCut, 0, 4)).toBeNull();
174 // The bottom row soft-wraps on below the viewport.
175 const tailCut = [row("https://t3.codes", false, true)];
176 expect(terminalLinkAtPosition(tailCut, 0, 8)).toBeNull();
177 // A partial bottom row is provably complete and still resolves.
178 const complete = [row("https://t3.codes", false), row("", false)];
179 expect(terminalLinkAtPosition(complete, 0, 8)).toBe("https://t3.codes");
180 // A wide grapheme earlier in the row must not break truncation detection:
181 // the soft-wrap flag decides, not string-length-versus-cell-count.
182 const wideFull: GhosttyRow = {
183 cells: [
184 { ...cell("πŸ™‚"), wide: 1 },
185 { ...cell(""), wide: 2 },
186 ...Array.from("https://t3.code", (character) => cell(character)),
187 ],
188 text: "πŸ™‚ https://t3.code",
189 isWrapContinuation: false,
190 wrapsToNext: true,
191 };
192 expect(terminalLinkAtPosition([wideFull], 0, 8)).toBeNull();
193 // Unwritten trailing cells prove the bottom row is complete.
194 const unwrittenTail: GhosttyRow = {
195 cells: [
196 ...Array.from("https://t3.codes", (character) => cell(character)),
197 cell(""),
198 cell(""),
199 ],
200 text: "https://t3.codes",
201 isWrapContinuation: false,
202 wrapsToNext: false,
203 };
204 expect(terminalLinkAtPosition([unwrittenTail], 0, 8)).toBe("https://t3.codes");
205 });
206});
207​
208describe("isTerminalCopyShortcut", () => {
209 const event = (overrides: Partial<Parameters<typeof isTerminalCopyShortcut>[0]> = {}) => ({
210 ctrlKey: false,
211 key: "c",
212 metaKey: false,
213 shiftKey: false,
214 ...overrides,
215 });
216​
217 it("keeps Ctrl+C available for SIGINT on macOS", () => {
218 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
219 expect(isTerminalCopyShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
220 });
221​
222 it("copies with Ctrl+C and Ctrl+Shift+C elsewhere", () => {
223 expect(isTerminalCopyShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(true);
224 expect(isTerminalCopyShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
225 true,
226 );
227 expect(isTerminalCopyShortcut(event({}), "Linux x86_64")).toBe(false);
228 });
229​
230 it("uses the produced character instead of the physical key position", () => {
231 expect(isTerminalCopyShortcut(event({ key: "C", metaKey: true }), "MacIntel")).toBe(true);
232 expect(isTerminalCopyShortcut(event({ key: "j", metaKey: true }), "MacIntel")).toBe(false);
233 });
234});
235​
236describe("isTerminalPasteShortcut", () => {
237 const event = (overrides: Partial<Parameters<typeof isTerminalPasteShortcut>[0]> = {}) => ({
238 ctrlKey: false,
239 key: "v",
240 metaKey: false,
241 shiftKey: false,
242 ...overrides,
243 });
244​
245 it("uses Cmd+V on macOS", () => {
246 expect(isTerminalPasteShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
247 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "MacIntel")).toBe(false);
248 });
249​
250 it("preserves Ctrl+V and uses Ctrl+Shift+V elsewhere", () => {
251 expect(isTerminalPasteShortcut(event({ ctrlKey: true }), "Linux x86_64")).toBe(false);
252 expect(isTerminalPasteShortcut(event({ ctrlKey: true, shiftKey: true }), "Linux x86_64")).toBe(
253 true,
254 );
255 });
256});
257​
258describe("isTerminalCompositionCommitInput", () => {
259 it("identifies browser composition follow-up input", () => {
260 expect(isTerminalCompositionCommitInput({ inputType: "" })).toBe(true);
261 expect(isTerminalCompositionCommitInput({ inputType: "insertCompositionText" })).toBe(true);
262 expect(isTerminalCompositionCommitInput({ inputType: "insertFromComposition" })).toBe(true);
263 });
264​
265 it("keeps a fast repeated input as legitimate text", () => {
266 expect(isTerminalCompositionCommitInput({ inputType: "insertText" })).toBe(false);
267 });
268});
269​
270describe("application mouse reporting", () => {
271 const event = (overrides: Partial<Parameters<typeof shouldReportTerminalMouse>[1]> = {}) => ({
272 ctrlKey: false,
273 metaKey: false,
274 shiftKey: false,
275 ...overrides,
276 });
277​
278 it("keeps Shift and link activation modifiers available to the browser", () => {
279 expect(shouldReportTerminalMouse(true, event())).toBe(true);
280 expect(shouldReportTerminalMouse(true, event({ shiftKey: true }))).toBe(false);
281 expect(shouldReportTerminalMouse(true, event({ ctrlKey: true }))).toBe(false);
282 expect(shouldReportTerminalMouse(true, event({ metaKey: true }))).toBe(false);
283 expect(shouldReportTerminalMouse(false, event())).toBe(false);
284 });
285​
286 it("maps browser buttons to Ghostty's button enum", () => {
287 expect([0, 1, 2, 3, 4, 5].map(ghosttyMouseButton)).toEqual([1, 3, 2, 4, 5, null]);
288 });
289​
290 it("only shows link hover during mouse tracking when the link modifier is held", () => {
291 expect(shouldShowTerminalLinkHover(false, false)).toBe(true);
292 expect(shouldShowTerminalLinkHover(false, true)).toBe(true);
293 expect(shouldShowTerminalLinkHover(true, false)).toBe(false);
294 expect(shouldShowTerminalLinkHover(true, true)).toBe(true);
295 });
296});
297​
298describe("terminal font resolution", () => {
299 it("validates the requested face after its styles load", async () => {
300 let loaded = false;
301 const load = vi.fn(async () => {
302 loaded = true;
303 return [];
304 });
305 const resolve = vi.fn(() => {
306 expect(loaded).toBe(true);
307 return DEFAULT_TERMINAL_FONT_FAMILY;
308 });
309​
310 await expect(
311 loadTerminalFontFamily("Proportional Test", 12, {
312 load,
313 resolve,
314 }),
315 ).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
316 expect(load).toHaveBeenCalledTimes(4);
317 expect(resolve).toHaveBeenCalledWith("Proportional Test");
318 });
319​
320 it("keeps the glyph fallbacks behind a custom text face", () => {
321 expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
322 expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
323 const custom = terminalFontFamily('"Fira Code"');
324 expect(custom.startsWith('"Fira Code", ')).toBe(true);
325 expect(custom).toContain('"Symbols Nerd Font Mono"');
326 expect(custom.endsWith("monospace")).toBe(true);
327 });
328​
329 it("ignores proportional families the cell grid cannot lay out", () => {
330 // jsdom has no canvas metrics, so the probe answers "monospace" and the
331 // family is kept; the guard is exercised in the browser instead. Assert the
332 // shape stays intact so a rejected face still yields a usable stack.
333 const stack = terminalFontFamily("Helvetica Neue");
334 expect(stack.endsWith("monospace")).toBe(true);
335 });
336​
337 it("quotes families the canvas font shorthand would otherwise reject", () => {
338 expect(terminalFontFamily("3270 Nerd Font").startsWith('"3270 Nerd Font", ')).toBe(true);
339 expect(terminalFontFamily("M+ 1m").startsWith('"M+ 1m", ')).toBe(true);
340 expect(terminalFontFamily("Cascadia Code, Menlo").startsWith('"Cascadia Code", Menlo, ')).toBe(
341 true,
342 );
343 expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
344 });
345​
346 it("clamps requested font sizes to the supported range", () => {
347 expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
348 expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
349 expect(terminalFontSize(13.4)).toBe(13);
350 expect(terminalFontSize(2)).toBe(6);
351 expect(terminalFontSize(90)).toBe(32);
352 });
353});
354​
355describe("terminalContentOriginY", () => {
356 it("stays top-anchored like a fresh terminal until scrollback exists", () => {
357 expect(terminalContentOriginY(100, 4, 5, 16, false)).toBe(4);
358 });
359​
360 it("pins the grid to the bottom by moving the sub-row slack above row 0", () => {
361 // 100px mount, 4px padding, 5 rows of 16px: 92 - 80 = 12px slack on top.
362 expect(terminalContentOriginY(100, 4, 5, 16, true)).toBe(16);
363 // Exact fit keeps the origin at the padding.
364 expect(terminalContentOriginY(88, 4, 5, 16, true)).toBe(4);
365 // A mount smaller than the grid never pushes the origin above the padding.
366 expect(terminalContentOriginY(80, 4, 5, 16, true)).toBe(4);
367 });
368​
369 it("keeps the prompt stationary while a drag crosses row boundaries", () => {
370 // Growing the mount pixel by pixel: the bottom edge (origin + rows*cell)
371 // tracks the mount bottom exactly until a new row fits.
372 for (let height = 88; height < 104; height += 1) {
373 const rows = Math.max(1, Math.floor((height - 8) / 16));
374 const origin = terminalContentOriginY(height, 4, rows, 16, true);
375 expect(origin + rows * 16).toBe(height - 4);
376 }
377 });
378});
379​
380describe("terminalWheelDeltaRows", () => {
381 it("converts line-mode deltas into whole rows", () => {
382 const result = terminalWheelDeltaRows({ deltaY: 3, deltaMode: 1 }, 16, 24, 0);
383 expect(result.rows).toBe(3);
384 expect(result.remainder).toBe(0);
385 });
386​
387 it("accumulates fractional pixel deltas across events", () => {
388 let remainder = 0;
389 let scrolled = 0;
390 for (let index = 0; index < 4; index += 1) {
391 const result = terminalWheelDeltaRows({ deltaY: 5, deltaMode: 0 }, 16, 24, remainder);
392 remainder = result.remainder;
393 scrolled += result.rows;
394 }
395 expect(scrolled).toBe(1);
396 expect(remainder).toBeCloseTo(4 / 16);
397 });
398​
399 it("keeps direction for negative page-mode deltas", () => {
400 const result = terminalWheelDeltaRows({ deltaY: -1, deltaMode: 2 }, 16, 24, 0);
401 expect(result.rows).toBe(-24);
402 expect(result.remainder).toBe(0);
403 });
404});
405​
406describe("terminalWheelArrowData", () => {
407 it("emits one arrow per row honoring application cursor keys", () => {
408 expect(terminalWheelArrowData(-2, false)).toBe("\u001b[A\u001b[A");
409 expect(terminalWheelArrowData(3, false)).toBe("\u001b[B\u001b[B\u001b[B");
410 expect(terminalWheelArrowData(-1, true)).toBe("\u001bOA");
411 expect(terminalWheelArrowData(0, true)).toBe("");
412 });
413});
414​
415describe("isTerminalLinkPointerGesture", () => {
416 it("uses Command on macOS and Control elsewhere", () => {
417 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "MacIntel")).toBe(true);
418 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "MacIntel")).toBe(false);
419 expect(isTerminalLinkPointerGesture({ ctrlKey: true, metaKey: false }, "Linux x86_64")).toBe(
420 true,
421 );
422 expect(isTerminalLinkPointerGesture({ ctrlKey: false, metaKey: true }, "Linux x86_64")).toBe(
423 false,
424 );
425 });
426});
427​
428describe("advanceTerminalSelectionClickSequence", () => {
429 it("recognizes stationary double and triple pointer presses without PointerEvent.detail", () => {
430 const first = advanceTerminalSelectionClickSequence(null, {
431 clientX: 20,
432 clientY: 30,
433 timeStamp: 1_000,
434 });
435 const second = advanceTerminalSelectionClickSequence(first, {
436 clientX: 22,
437 clientY: 29,
438 timeStamp: 1_200,
439 });
440 const third = advanceTerminalSelectionClickSequence(second, {
441 clientX: 21,
442 clientY: 31,
443 timeStamp: 1_400,
444 });
445​
446 expect([first.count, second.count, third.count]).toEqual([1, 2, 3]);
447 });
448​
449 it("starts over after movement, delay, or a completed triple click", () => {
450 const previous = { count: 3, time: 1_000, x: 20, y: 30 };
451 expect(
452 advanceTerminalSelectionClickSequence(previous, {
453 clientX: 20,
454 clientY: 30,
455 timeStamp: 1_100,
456 }).count,
457 ).toBe(1);
458 expect(
459 advanceTerminalSelectionClickSequence(previous, {
460 clientX: 30,
461 clientY: 30,
462 timeStamp: 1_100,
463 }).count,
464 ).toBe(1);
465 expect(
466 advanceTerminalSelectionClickSequence(previous, {
467 clientX: 20,
468 clientY: 30,
469 timeStamp: 1_501,
470 }).count,
471 ).toBe(1);
472 });
473});
474​
475describe("terminal scrollbar", () => {
476 it("maps Ghostty's viewport state to a proportional thumb", () => {
477 expect(terminalScrollbarGeometry({ total: 100, offset: 40, len: 20 }, 200)).toEqual({
478 thumbHeight: 40,
479 thumbTop: 80,
480 maxOffset: 80,
481 });
482 expect(terminalScrollbarGeometry({ total: 100, offset: 0, len: 100 }, 200)).toBeNull();
483 });
484​
485 it("keeps the thumb usable for large scrollback and maps dragging back to rows", () => {
486 const state = { total: 10_000, offset: 0, len: 20 };
487 expect(terminalScrollbarGeometry(state, 200)).toEqual({
488 thumbHeight: 18,
489 thumbTop: 0,
490 maxOffset: 9_980,
491 });
492 expect(terminalScrollbarOffsetAtPointer(state, 200, 191, 9)).toBe(9_980);
493 });
494});