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

ServerBrowserSurface.browser.test.tsx

281 lines10.0 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import type {
3 PreviewStreamControl,
4 PreviewStreamEvents,
5 PreviewStreamInput,
6} from "@t3tools/client-runtime/preview/server-browser-stream";
7import { describe, expect, it, vi } from "vite-plus/test";
8import { userEvent } from "vite-plus/test/browser";
9​
10import { act, fakeTimers, render } from "../../test/render";
11​
12const mocks = vi.hoisted(() => ({
13 createClient: vi.fn<(target: unknown, handlers: PreviewStreamEvents) => unknown>(),
14 sent: [] as PreviewStreamInput[],
15 access: { url: "ws://preview.test", token: "test" },
16 painted: null as (() => void) | null,
17}));
18​
19vi.mock(import("@t3tools/client-runtime/preview/server-browser-stream"), async (original) => ({
20 ...(await original()),
21 createPreviewStreamClient: mocks.createClient as never,
22 createPreviewFramePainter: (_canvas, onPainted) => {
23 mocks.painted = onPainted ?? null;
24 return { paint: () => undefined, stop: () => undefined };
25 },
26}));
27​
28vi.mock(import("~/state/previewStream"), async (original) => ({
29 ...(await original()),
30 usePreviewStreamAccess: () => mocks.access as never,
31}));
32​
33import { ServerBrowserSurface } from "./ServerBrowserSurface";
34​
35function setup() {
36 mocks.sent.length = 0;
37 mocks.painted = null;
38 mocks.createClient.mockReset().mockImplementation(() => ({
39 send: (input: PreviewStreamInput) => mocks.sent.push(input),
40 stop: () => undefined,
41 }));
43​
44async function renderSurface(controller: PreviewStreamControl["controller"]) {
45 const container = document.createElement("div");
46 container.style.cssText = "width: 400px; height: 300px; display: flex;";
47 await using stack = new AsyncDisposableStack();
48 const screen = stack.use(
49 await render(
50 <ServerBrowserSurface
51 environmentId={EnvironmentId.make("environment-copy")}
52 threadId="thread-copy"
53 tabId="tab-copy"
54 visible
55 followSize={false}
56 className="flex-1"
57 />,
58 { container },
59 ),
60 );
61 await vi.waitFor(() => expect(mocks.createClient).toHaveBeenCalled());
62 const handlers = mocks.createClient.mock.calls.at(-1)![1];
63 await act(() =>
64 handlers.onControl?.({ canOperate: true, controller, generation: 1, dialog: null }),
65 );
66 mocks.sent.length = 0;
67 const input = container.querySelector("textarea")!;
68 const canvas = container.querySelector("canvas")!;
69 stack.move();
70 return { screen, input, canvas };
72​
73const keys = () => mocks.sent.filter((input) => input.type === "key");
74​
75it("moves browser keyboard focus to the HTTP sign-in prompt", async () => {
76 setup();
77 const { screen, input } = await renderSurface("you");
78 await using _screen = screen;
79 input.focus();
80 const handlers = mocks.createClient.mock.calls.at(-1)![1];
81 await act(() =>
82 handlers.onControl?.({
83 canOperate: true,
84 controller: "you",
85 generation: 1,
86 dialog: {
87 type: "auth",
88 message: "Sign in to the preview",
89 defaultValue: "",
90 authChallengeId: "test-challenge",
91 },
92 }),
93 );
94 await expect.element(screen.getByRole("textbox", { name: "Username" })).toHaveFocus();
95 await userEvent.keyboard("tester");
96 expect(mocks.sent).toEqual([]);
97});
98​
99describe("ServerBrowserSurface clipboard commands", () => {
100 it("sends a native Copy or Cut menu command to the page once", async () => {
101 setup();
102 const { screen, input, canvas } = await renderSurface("you");
103 await using _screen = screen;
104 // Chromium runs a script Copy or Cut only during a user gesture, as a menu click is.
105 await userEvent.click(canvas);
106 input.focus();
107 mocks.sent.length = 0;
108​
109 // Like Electron's webContents.copy(): the browser's Copy command, with no key.
110 expect(document.execCommand("copy")).toBe(true);
111 expect(keys()).toEqual([
112 { type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
113 { type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
114 ]);
115​
116 mocks.sent.length = 0;
117 expect(document.execCommand("cut")).toBe(true);
118 expect(input.value).toBe("\u200b");
119 expect(keys()).toEqual([
120 { type: "key", action: "down", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
121 { type: "key", action: "up", key: "x", code: "KeyX", keyCode: 88, modifiers: 2 },
122 ]);
123 });
124​
125 it("sends a keyboard Copy or Cut once and leaves menu Copy working after any shortcut", async () => {
126 setup();
127 const { screen, input, canvas } = await renderSurface("you");
128 await using _screen = screen;
129 await userEvent.click(canvas);
130 input.focus();
131 const prevented: boolean[] = [];
132 const onKeyDown = (event: KeyboardEvent) => {
133 if (/^[cx]$/i.test(event.key)) prevented.push(event.defaultPrevented);
134 };
135 window.addEventListener("keydown", onKeyDown);
136 using _listener = { [Symbol.dispose]: () => window.removeEventListener("keydown", onKeyDown) };
137​
138 // An unprevented copy or cut key also makes the browser fire copy or cut: here Chromium's
139 // Ctrl key binding, on macOS Electron's menu after the Meta keyup.
140 for (const [shortcut, cancels] of [
141 ["{Control>}x{/Control}", true],
142 ["{Control>}c{/Control}", true],
143 ["{Meta>}{x>}{/Meta}{/x}", true],
144 ["{Control>}{Shift>}c{/Shift}{/Control}", false],
145 ["{Control>}{Alt>}x{/Alt}{/Control}", false],
146 ] as const) {
147 mocks.sent.length = 0;
148 prevented.length = 0;
149 await userEvent.keyboard(shortcut);
150 expect(prevented, shortcut).toEqual([cancels]);
151 expect(keys().filter((key) => /^[cx]$/i.test(key.key)).length, shortcut).toBe(2);
152 expect(input.value).toBe("\u200b");
153​
154 mocks.sent.length = 0;
155 expect(document.execCommand("copy")).toBe(true);
156 expect(keys(), shortcut).toEqual([
157 { type: "key", action: "down", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
158 { type: "key", action: "up", key: "c", code: "KeyC", keyCode: 67, modifiers: 2 },
159 ]);
160 }
161 });
162​
163 it("sends nothing when another viewer controls the page", async () => {
164 setup();
165 const { screen, input } = await renderSurface("another-viewer");
166 await using _screen = screen;
167​
168 expect(
169 input.dispatchEvent(new ClipboardEvent("copy", { bubbles: true, cancelable: true })),
170 ).toBe(false);
171 expect(
172 input.dispatchEvent(new ClipboardEvent("cut", { bubbles: true, cancelable: true })),
173 ).toBe(false);
174 expect(mocks.sent).toEqual([]);
175 });
176});
177​
178const mouseUp = (canvas: HTMLCanvasElement, button: number) => {
179 const event = new MouseEvent("mouseup", { button, bubbles: true, cancelable: true });
180 canvas.dispatchEvent(event);
181 return event;
182};
183​
184describe("ServerBrowserSurface history", () => {
185 it("routes mouse thumb buttons to the preview's history instead of the app", async () => {
186 setup();
187 const { screen, input } = await renderSurface("you");
188 await using _screen = screen;
189 const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
190​
191 expect(mouseUp(canvas, 3).defaultPrevented).toBe(true);
192 expect(mouseUp(canvas, 4).defaultPrevented).toBe(true);
193 expect(mocks.sent).toEqual([
194 { type: "history", delta: -1 },
195 { type: "history", delta: 1 },
196 ]);
197 });
198​
199 it("leaves other mouse buttons alone", async () => {
200 setup();
201 const { screen, input } = await renderSurface("you");
202 await using _screen = screen;
203 const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
204​
205 expect(mouseUp(canvas, 0).defaultPrevented).toBe(false);
206 expect(mocks.sent).toEqual([]);
207 });
208​
209 it("does not forward thumb-button presses to the page", async () => {
210 setup();
211 const { screen, input } = await renderSurface("you");
212 await using _screen = screen;
213 const canvas = input.closest("[data-server-browser-surface]")!.querySelector("canvas")!;
214 canvas.width = 400;
215 canvas.height = 300;
216 // Synthetic pointers have no active pointer id to capture.
217 canvas.setPointerCapture = () => undefined;
218 const handlers = mocks.createClient.mock.calls.at(-1)![1];
219 await act(() => {
220 mocks.painted?.();
221 handlers.onViewport({ width: 400, height: 300 });
222 });
223 const { left, top } = canvas.getBoundingClientRect();
224 const press = (type: "pointerdown" | "pointerup", button: number) =>
225 canvas.dispatchEvent(
226 new PointerEvent(type, {
227 button,
228 buttons: type === "pointerdown" ? 1 << button : 0,
229 clientX: left + 10,
230 clientY: top + 10,
231 pointerType: "mouse",
232 bubbles: true,
233 }),
234 );
235 const mouseInputs = () => mocks.sent.filter((input) => input.type === "mouse");
236​
237 for (const button of [3, 4]) {
238 press("pointerdown", button);
239 press("pointerup", button);
240 }
241 expect(mouseInputs()).toEqual([]);
242​
243 press("pointerdown", 0);
244 expect(mouseInputs()).not.toEqual([]);
245 });
246});
247​
248describe("ServerBrowserSurface frames", () => {
249 it("reports a connected stream that never delivers a frame until one arrives", async () => {
250 setup();
251 const onNoFrames = vi.fn();
252 const container = document.createElement("div");
253 container.style.cssText = "width: 400px; height: 300px; display: flex;";
254 await using _screen = await render(
255 <ServerBrowserSurface
256 environmentId={EnvironmentId.make("environment-frames")}
257 threadId="thread-frames"
258 tabId="tab-frames"
259 visible
260 followSize={false}
261 onNoFrames={onNoFrames}
262 className="flex-1"
263 />,
264 { container },
265 );
266 await vi.waitFor(() => expect(mocks.createClient).toHaveBeenCalled());
267 using _timers = fakeTimers();
268 const handlers = mocks.createClient.mock.calls.at(-1)![1];
269 await act(() => handlers.onConnectedChange(true));
270 await act(() => vi.advanceTimersByTime(9_999));
271 expect(onNoFrames).not.toHaveBeenCalled();
272 expect(container.querySelector('[role="alert"]')).toBeNull();
273​
274 await act(() => vi.advanceTimersByTime(1));
275 expect(onNoFrames).toHaveBeenCalledOnce();
276 expect(container.querySelector('[role="alert"]')?.textContent).toContain("not drawing it");
277​
278 await act(() => mocks.painted?.());
279 expect(container.querySelector('[role="alert"]')).toBeNull();
280 });
281});