1
-import { describe, expect, it, vi } from "vite-plus/test";
1
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3
-import type { GhosttyCell, GhosttyRow } from "./core";
3
+import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
4
import {
5
DEFAULT_TERMINAL_FONT_FAMILY,
6
DEFAULT_TERMINAL_FONT_SIZE,
31
terminalFontSize,
32
terminalWheelArrowData,
33
terminalWheelDeltaRows,
34
+ GhosttyTerminalSurface,
35
+ type GhosttyTerminalSurfaceOptions,
36
} from "./surface";
37
38
+vi.mock("./vendor/ghostty-vt.wasm?url", async () => ({
39
+ default: (await import("./vendor/ghostty-vt.wasm?inline")).default,
40
+}));
41
+vi.mock("./vendor/ghostty-write-pty.wasm?url&no-inline", async () => ({
42
+ default: (await import("./vendor/ghostty-write-pty.wasm?inline")).default,
43
+}));
44
+
45
+describe("GhosttyTerminalSurface visibility", () => {
46
+ const surfaces = new Set<GhosttyTerminalSurface>();
47
+
48
+ // Keep the real surface, renderer, and WASM core. Only browser layout and
49
+ // scheduling are replaced so tests can count work while the terminal is hidden.
50
+ function createHarness() {
51
+ vi.useFakeTimers();
52
+ const frames = new Map<number, FrameRequestCallback>();
53
+ const resizeCallbacks = new Set<() => void>();
54
+ const paint = vi.fn((_operation: string, _args: ReadonlyArray<unknown>) => {});
55
+ let frameId = 0;
56
+ const requestFrame = vi.fn((callback: FrameRequestCallback) => {
57
+ frames.set(++frameId, callback);
58
+ return frameId;
59
+ });
60
+
61
+ class TerminalTestElement extends EventTarget {
62
+ style: Record<string, string> = {};
63
+ parentElement: TerminalTestElement | null = null;
64
+ clientWidth = 168;
65
+ clientHeight = 104;
66
+ width = 300;
67
+ height = 150;
68
+ value = "";
69
+ private readonly captures = new Set<number>();
70
+
71
+ setAttribute() {}
72
+ append(...children: TerminalTestElement[]) {
73
+ for (const child of children) child.parentElement = this;
74
+ }
75
+ replaceChildren(...children: TerminalTestElement[]) {
76
+ this.append(...children);
77
+ }
78
+ remove() {
79
+ this.parentElement = null;
80
+ }
81
+ getContext() {
82
+ return context;
83
+ }
84
+ focus() {
85
+ this.dispatchEvent(new Event("focus"));
86
+ }
87
+ setPointerCapture(pointerId: number) {
88
+ this.captures.add(pointerId);
89
+ }
90
+ hasPointerCapture(pointerId: number) {
91
+ return this.captures.has(pointerId);
92
+ }
93
+ releasePointerCapture(pointerId: number) {
94
+ this.captures.delete(pointerId);
95
+ }
96
+ getBoundingClientRect() {
97
+ return { left: 0, top: 0, right: 168, bottom: 104, width: 168, height: 104 };
98
+ }
99
+ }
100
+
101
+ const canvas = new TerminalTestElement();
102
+ const mount = new TerminalTestElement();
103
+ const context = {
104
+ canvas,
105
+ beginPath() {},
106
+ clip() {},
107
+ rect() {},
108
+ resetTransform() {},
109
+ restore() {},
110
+ save() {},
111
+ setTransform() {},
112
+ fillRect: (...args: number[]) => paint("fillRect", args),
113
+ strokeRect: (...args: number[]) => paint("strokeRect", args),
114
+ fillText: (...args: [string, number, number, number?]) => paint("fillText", args),
115
+ measureText: (text: string) => ({
116
+ width: text.length * 8,
117
+ actualBoundingBoxAscent: 9,
118
+ actualBoundingBoxDescent: 3,
119
+ }),
120
+ };
121
+ vi.stubGlobal("document", {
122
+ createElement: (tag: string) => (tag === "canvas" ? canvas : new TerminalTestElement()),
123
+ fonts: Object.assign(new EventTarget(), { load: async () => [], add() {} }),
124
+ });
125
+ vi.stubGlobal(
126
+ "window",
127
+ Object.assign(new EventTarget(), {
128
+ devicePixelRatio: 1,
129
+ requestAnimationFrame: requestFrame,
130
+ cancelAnimationFrame: (id: number) => frames.delete(id),
131
+ setTimeout,
132
+ clearTimeout,
133
+ setInterval,
134
+ clearInterval,
135
+ matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
136
+ }),
137
+ );
138
+ vi.stubGlobal(
139
+ "ResizeObserver",
140
+ class {
141
+ constructor(private readonly callback: () => void) {
142
+ resizeCallbacks.add(callback);
143
+ }
144
+ observe() {}
145
+ disconnect() {
146
+ resizeCallbacks.delete(this.callback);
147
+ }
148
+ },
149
+ );
150
+ const snapshot = vi.spyOn(GhosttyTerminalCore.prototype, "snapshot");
151
+ const onData = vi.fn<(data: string) => void>();
152
+
153
+ return {
154
+ mount,
155
+ frames,
156
+ paint,
157
+ requestFrame,
158
+ snapshot,
159
+ onData,
160
+ get renderedSnapshot() {
161
+ const result = snapshot.mock.results.at(-1);
162
+ if (result?.type !== "return") throw new Error("No terminal snapshot was rendered");
163
+ return result.value;
164
+ },
165
+ flushFrame() {
166
+ const queued = [...frames.values()];
167
+ frames.clear();
168
+ for (const callback of queued) callback(0);
169
+ },
170
+ resize() {
171
+ for (const callback of resizeCallbacks) callback();
172
+ },
173
+ pointer(type: string, clientX: number, buttons: number) {
174
+ canvas.dispatchEvent(
175
+ Object.assign(new Event(type, { cancelable: true }), {
176
+ clientX,
177
+ clientY: 5,
178
+ pointerId: 1,
179
+ button: 0,
180
+ buttons,
181
+ }),
182
+ );
183
+ },
184
+ async create(options: Partial<GhosttyTerminalSurfaceOptions> = {}) {
185
+ const surface = await GhosttyTerminalSurface.create(mount as unknown as HTMLElement, {
186
+ theme: {
187
+ foreground: { r: 255, g: 255, b: 255 },
188
+ background: { r: 0, g: 0, b: 0 },
189
+ cursor: { r: 255, g: 255, b: 255 },
190
+ },
191
+ onData,
192
+ onResize() {},
193
+ onSelectionChange() {},
194
+ beforeKey: () => false,
195
+ onLinkActivate() {},
196
+ ...options,
197
+ get visible() {
198
+ return options.visible ?? true;
199
+ },
200
+ });
201
+ surfaces.add(surface);
202
+ return surface;
203
+ },
204
+ };
205
+ }
206
+
207
+ afterEach(() => {
208
+ for (const surface of surfaces) surface.dispose();
209
+ surfaces.clear();
210
+ vi.useRealTimers();
211
+ vi.unstubAllGlobals();
212
+ vi.restoreAllMocks();
213
+ });
214
+
215
+ it("stops hidden snapshots and paint while preserving live VT replies and the next cursor", async () => {
216
+ const harness = createHarness();
217
+ const surface = await harness.create();
218
+ surface.focus();
219
+ surface.write("ready\x1b[1 q");
220
+ harness.flushFrame();
221
+ vi.advanceTimersByTime(500);
222
+ harness.flushFrame();
223
+ surface.write("queued");
224
+ expect(harness.frames.size).toBe(1);
225
+ surface.setVisible(false);
226
+ expect(harness.frames.size).toBe(0);
227
+ expect(vi.getTimerCount()).toBe(0);
228
+ harness.snapshot.mockClear();
229
+ harness.paint.mockClear();
230
+ harness.requestFrame.mockClear();
231
+
232
+ surface.write("\x1b[2J\x1b[H\x1b[3");
233
+ surface.write("1mhidden");
234
+ surface.write("界🙂\x1b[0m\x1b[5n\x1b[6n");
235
+ surface.fit();
236
+ vi.advanceTimersByTime(2_000);
237
+ harness.flushFrame();
238
+
239
+ expect(harness.onData.mock.calls).toEqual([["\x1b[0n"], ["\x1b[1;11R"]]);
240
+ expect(harness.snapshot).not.toHaveBeenCalled();
241
+ expect(harness.paint).not.toHaveBeenCalled();
242
+ expect(harness.requestFrame).not.toHaveBeenCalled();
243
+
244
+ surface.setVisible(true);
245
+ expect(harness.snapshot).toHaveBeenCalledTimes(1);
246
+ expect(harness.renderedSnapshot).toMatchObject({ cursorX: 10, cursorY: 0 });
247
+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("hidden");
248
+ expect(harness.paint.mock.calls).toContainEqual(["fillRect", [84, 4, 8, 16]]);
249
+ expect(harness.frames.size).toBe(0);
250
+ });
251
+
252
+ it("keeps the selection on reveal and applies a hidden selection clear", async () => {
253
+ const harness = createHarness();
254
+ const surface = await harness.create();
255
+ surface.write("hello world");
256
+ harness.flushFrame();
257
+ harness.pointer("pointerdown", 5, 1);
258
+ harness.pointer("pointermove", 37, 1);
259
+ harness.pointer("pointerup", 37, 0);
260
+ harness.flushFrame();
261
+ expect(surface.getSelection()).toBe("hello");
262
+ const position = surface.getSelectionPosition();
263
+
264
+ surface.setVisible(false);
265
+ harness.snapshot.mockClear();
266
+ surface.setVisible(true);
267
+ expect(harness.snapshot).toHaveBeenCalledTimes(1);
268
+ expect(surface.getSelectionPosition()).toEqual(position);
269
+ expect(
270
+ harness.renderedSnapshot.rowData[0]?.cells.slice(0, 5).every((cell) => cell.selected),
271
+ ).toBe(true);
272
+
273
+ surface.setVisible(false);
274
+ harness.snapshot.mockClear();
275
+ surface.clearSelection();
276
+ surface.write("!");
277
+ expect(harness.snapshot).not.toHaveBeenCalled();
278
+ surface.setVisible(true);
279
+ expect(harness.snapshot).toHaveBeenCalledTimes(1);
280
+ expect(surface.getSelection()).toBe("");
281
+ expect(surface.getSelectionPosition()).toBeNull();
282
+ expect(harness.renderedSnapshot.rowData[0]?.cells.some((cell) => cell.selected)).toBe(false);
283
+ });
284
+
285
+ it("stops zero-size mounts and repaints when the same size returns", async () => {
286
+ const harness = createHarness();
287
+ const surface = await harness.create();
288
+ surface.focus();
289
+ surface.write("visible");
290
+ harness.flushFrame();
291
+ harness.snapshot.mockClear();
292
+ harness.paint.mockClear();
293
+ harness.mount.clientWidth = 0;
294
+ surface.write("!");
295
+ harness.flushFrame();
296
+ harness.requestFrame.mockClear();
297
+ for (let index = 0; index < 8; index += 1) surface.write("x");
298
+ vi.advanceTimersByTime(2_000);
299
+
300
+ expect(harness.snapshot).not.toHaveBeenCalled();
301
+ expect(harness.paint).not.toHaveBeenCalled();
302
+ expect(harness.requestFrame).not.toHaveBeenCalled();
303
+ harness.mount.clientWidth = 168;
304
+ harness.resize();
305
+ expect(harness.snapshot).toHaveBeenCalledTimes(1);
306
+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("visible!xxxxxxxx");
307
+ expect(harness.paint).toHaveBeenCalled();
308
+ });
309
+
310
+ it.each([false, true])(
311
+ "uses visibility %s if it changes while WASM initializes",
312
+ async (visible) => {
313
+ const harness = createHarness();
314
+ let markCreated!: () => void;
315
+ const created = new Promise<void>((resolve) => {
316
+ markCreated = resolve;
317
+ });
318
+ let finishLoading!: () => void;
319
+ const release = new Promise<void>((resolve) => {
320
+ finishLoading = resolve;
321
+ });
322
+ const create = GhosttyTerminalCore.create;
323
+ vi.spyOn(GhosttyTerminalCore, "create").mockImplementation(async (...args) => {
324
+ const core = await create(...args);
325
+ markCreated();
326
+ await release;
327
+ return core;
328
+ });
329
+ let currentVisible = !visible;
330
+ const pending = harness.create({
331
+ get visible() {
332
+ return currentVisible;
333
+ },
334
+ });
335
+ await created;
336
+ currentVisible = visible;
337
+ harness.paint.mockClear();
338
+ finishLoading();
339
+ const surface = await pending;
340
+
341
+ expect(harness.snapshot).toHaveBeenCalledTimes(visible ? 1 : 0);
342
+ if (!visible) expect(harness.paint).not.toHaveBeenCalled();
343
+ surface.write("ready\x1b[5n");
344
+ expect(harness.onData).toHaveBeenCalledWith("\x1b[0n");
345
+ if (!visible) {
346
+ expect(harness.frames.size).toBe(0);
347
+ surface.setVisible(true);
348
+ } else {
349
+ harness.flushFrame();
350
+ }
351
+ expect(harness.renderedSnapshot.rowData[0]?.text).toContain("ready");
352
+ },
353
+ );
354
+});
355
+
356
const cell = (text: string): GhosttyCell => ({
357
text,
358
wide: 0,