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

DeviceStreamView.browser.test.tsx

324 lines10.6 KB

1import { act, useEffect, useSyncExternalStore } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { EnvironmentId } from "@t3tools/contracts";
4import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vite-plus/test";
5​
6const accessStore = {
7 value: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true },
8 listeners: new Set<() => void>(),
9 refresh() {
10 accessStore.value = { ...accessStore.value };
11 for (const listener of accessStore.listeners) listener();
12 },
13 subscribe(listener: () => void) {
14 accessStore.listeners.add(listener);
15 return () => accessStore.listeners.delete(listener);
16 },
17};
18vi.mock(import("~/state/device"), async (original) => ({
19 ...(await original()),
20 useDeviceHubAccess: () => useSyncExternalStore(accessStore.subscribe, () => accessStore.value),
21 refreshDeviceHubAccess: () => accessStore.refresh(),
22}));
23let viewerMounts = 0;
24let viewerUnmounts = 0;
25// The 3D phone frame needs WebGL; the test only cares whether it stays mounted.
26vi.mock(import("./DevicePhoneViewport"), async (original) => ({
27 ...(await original()),
28 DevicePhoneViewport: function Viewer(): React.ReactElement {
29 useEffect(() => {
30 viewerMounts++;
31 return () => {
32 viewerUnmounts++;
33 };
34 }, []);
35 return <></>;
36 },
37}));
38import { DeviceStreamView } from "./DeviceStreamView";
39​
40// MJPEG frames come from the device hub, so images keep their src without loading it and a
41// test publishes a frame by setting the natural size and firing "load".
42const imageSources = new WeakMap<HTMLImageElement, string>();
43const framedImages = new WeakSet<HTMLImageElement>();
44let images: HTMLImageElement[] = [];
45const srcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src")!;
46const naturalWidthDescriptor = Object.getOwnPropertyDescriptor(
47 HTMLImageElement.prototype,
48 "naturalWidth",
49)!;
50const naturalHeightDescriptor = Object.getOwnPropertyDescriptor(
51 HTMLImageElement.prototype,
52 "naturalHeight",
53)!;
54const removeAttribute = Element.prototype.removeAttribute;
55function stubImages() {
56 Object.defineProperty(HTMLImageElement.prototype, "src", {
57 configurable: true,
58 get(this: HTMLImageElement) {
59 return imageSources.get(this) ?? "";
60 },
61 set(this: HTMLImageElement, value: string) {
62 if (!images.includes(this)) images.push(this);
63 imageSources.set(this, value);
64 },
65 });
66 for (const name of ["naturalWidth", "naturalHeight"]) {
67 Object.defineProperty(HTMLImageElement.prototype, name, {
68 configurable: true,
69 get(this: HTMLImageElement) {
70 if (!framedImages.has(this)) return 0;
71 return name === "naturalWidth" ? 400 : 800;
72 },
73 });
74 }
75 Element.prototype.removeAttribute = function (this: Element, name: string) {
76 if (this instanceof HTMLImageElement && name === "src") imageSources.delete(this);
77 return removeAttribute.call(this, name);
78 };
80function restoreImages() {
81 Object.defineProperty(HTMLImageElement.prototype, "src", srcDescriptor);
82 Object.defineProperty(HTMLImageElement.prototype, "naturalWidth", naturalWidthDescriptor);
83 Object.defineProperty(HTMLImageElement.prototype, "naturalHeight", naturalHeightDescriptor);
84 Element.prototype.removeAttribute = removeAttribute;
86async function publishFrame(image: HTMLImageElement) {
87 framedImages.add(image);
88 await act(async () => image.dispatchEvent(new Event("load")));
90let root: Root;
91let container: HTMLDivElement;
92let primes = 0;
93beforeEach(() => {
94 primes = 0;
95 viewerMounts = 0;
96 viewerUnmounts = 0;
97 images = [];
98 stubImages();
99 container = document.createElement("div");
100 container.style.cssText = "width: 400px; height: 800px; display: flex";
101 document.body.append(container);
102 root = createRoot(container);
103});
104afterEach(async () => {
105 await act(async () => root.unmount());
106 container.remove();
107 restoreImages();
108 vi.useRealTimers();
109 vi.unstubAllGlobals();
110});
111​
112async function setup(h264 = false) {
113 const touches: unknown[] = [];
114 vi.useFakeTimers();
115 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
116 let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
117 let output: VideoFrameOutputCallback | undefined;
118 if (h264) {
119 vi.stubGlobal(
120 "VideoDecoder",
121 class {
122 static isConfigSupported = async () => ({ supported: true });
123 state = "unconfigured";
124 constructor(callbacks: VideoDecoderInit) {
125 output = callbacks.output;
126 }
127 configure() {
128 this.state = "configured";
129 }
130 close() {
131 this.state = "closed";
132 }
133 },
134 );
135 vi.stubGlobal("EncodedVideoChunk", vi.fn());
136 } else {
137 // Without WebCodecs the iOS client streams MJPEG.
138 const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
139 if (videoDecoder) {
140 Reflect.deleteProperty(globalThis, "VideoDecoder");
141 onTestFinished(() => {
142 Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
143 });
144 }
145 }
146 vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
147 if (url.endsWith("stream.avcc")) {
148 return Promise.resolve(
149 new Response(
150 new ReadableStream<Uint8Array>({
151 start(controller) {
152 videoBody = controller;
153 init.signal?.addEventListener("abort", () => controller.error(new Error("aborted")));
154 },
155 }),
156 ),
157 );
158 }
159 primes++;
160 return Promise.resolve(new Response("prime"));
161 });
162 const sockets: Array<{ onmessage?: (event: { data: ArrayBuffer }) => void }> = [];
163 vi.stubGlobal(
164 "WebSocket",
165 class {
166 static OPEN = 1;
167 readyState = 1;
168 constructor() {
169 sockets.push(this);
170 }
171 onmessage?: (event: { data: ArrayBuffer }) => void;
172 send(packet: Uint8Array) {
173 if (packet[0] === 0x03) {
174 touches.push(JSON.parse(new TextDecoder().decode(packet.subarray(1))));
175 }
176 }
177 close() {}
178 },
179 );
180 const view = (visible: boolean) => (
181 <DeviceStreamView
182 hostId="local"
183 environmentId={EnvironmentId.make("test")}
184 deviceId="test"
185 platform="ios"
186 visible={visible}
187 allowPhoneView={h264}
188 />
189 );
190 await act(async () => root.render(view(true)));
191 return {
192 images,
193 view,
194 touches,
195 configure() {
196 const json = new TextEncoder().encode(
197 JSON.stringify({ width: 400, height: 800, orientation: "portrait" }),
198 );
199 const packet = new Uint8Array(1 + json.length);
200 packet[0] = 0x82;
201 packet.set(json, 1);
202 sockets[0]?.onmessage?.({ data: Uint8Array.of(0x83).buffer });
203 sockets[0]?.onmessage?.({ data: packet.buffer });
204 videoBody?.enqueue(new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]));
205 },
206 frame() {
207 const source = new OffscreenCanvas(400, 800);
208 source.getContext("2d")!.fillRect(0, 0, 400, 800);
209 output?.(new VideoFrame(source, { timestamp: 0 }));
210 },
211 };
213​
214const alert = () => container.querySelector('[role="alert"]');
215const reconnect = () =>
216 act(async () =>
217 [...container.querySelectorAll("button")]
218 .find((button) => button.textContent?.includes("Reconnect"))!
219 .click(),
220 );
221​
222it.each([
223 { name: "middle", button: 1, buttons: 4 },
224 { name: "right", button: 2, buttons: 2 },
225])("ignores $name-button drags and forwards the next primary drag", async ({ button, buttons }) => {
226 const { touches, configure } = await setup();
227 await act(async () => configure());
228 const viewport = container.querySelector("canvas")!.parentElement!;
229 viewport.style.width = "400px";
230 viewport.style.height = "800px";
231 // Synthetic pointer events do not register an active browser pointer to capture.
232 viewport.setPointerCapture = () => {};
233 const rect = viewport.getBoundingClientRect();
234 const pointer = (type: string, button: number, buttons: number, y: number) =>
235 viewport.dispatchEvent(
236 new PointerEvent(type, {
237 bubbles: true,
238 pointerId: 1,
239 pointerType: "mouse",
240 button,
241 buttons,
242 clientX: rect.left + 100,
243 clientY: rect.top + y,
244 }),
245 );
246​
247 await act(async () => {
248 pointer("pointerdown", button, buttons, 600);
249 pointer("pointermove", -1, buttons, 200);
250 pointer("pointerup", button, 0, 200);
251 });
252 expect(touches).toEqual([]);
253​
254 await act(async () => {
255 pointer("pointerdown", 0, 1, 600);
256 pointer("pointermove", -1, 1, 200);
257 pointer("pointerup", 0, 0, 200);
258 pointer("pointermove", -1, 0, 400);
259 });
260 expect(touches).toEqual([
261 { type: "begin", x: 0.25, y: 0.75 },
262 { type: "move", x: 0.25, y: 0.25 },
263 { type: "end", x: 0.25, y: 0.25 },
264 ]);
265});
266​
267it("removes MJPEG requests while hidden and reconnects when shown", async () => {
268 const { images, view } = await setup();
269 expect(images[0]!.src).toContain("stream.mjpeg");
270 await act(async () => root.render(view(false)));
271 expect(container.querySelectorAll("img")).toHaveLength(0);
272 expect(images[0]!.src).toBe("");
273 expect(vi.getTimerCount()).toBe(0);
274 await act(async () => root.render(view(true)));
275 expect(images.at(-1)!.src).toContain("stream.mjpeg");
276});
277​
278it("offers Reconnect after the shared timeout and receives a frame after retry with unchanged access", async () => {
279 const { images } = await setup();
280 await act(async () => {
281 await vi.advanceTimersByTimeAsync(15_000);
282 });
283 expect(alert()?.textContent).toContain("No video");
284 expect(images[0]!.src).toBe("");
285 await reconnect();
286 expect(alert()).toBeNull();
287 expect(images[1]!.src).toContain("stream.mjpeg");
288 await publishFrame(images[1]!);
289 expect(container.querySelector('[role="status"]')).toBeNull();
290 expect(container.querySelectorAll("button")).toHaveLength(0);
291 expect(vi.getTimerCount()).toBe(0);
292});
293​
294it("starts exactly one new stream per Reconnect press", async () => {
295 await setup();
296 await act(async () => {
297 await vi.advanceTimersByTimeAsync(15_000);
298 });
299 expect(primes).toBe(1);
300 await reconnect();
301 expect(primes).toBe(2);
302});
303​
304it("keeps the 3D viewer mounted across iOS video recovery and releases it when hidden", async () => {
305 const { configure, frame, view } = await setup(true);
306 await act(async () => configure());
307 expect(viewerMounts).toBe(0);
308 await act(async () => frame());
309 expect(viewerMounts).toBe(1);
310 await act(async () => {
311 await vi.advanceTimersByTimeAsync(15_000);
312 });
313 expect(viewerUnmounts).toBe(0);
314 expect(viewerMounts).toBe(1);
315 await act(async () => {
316 await vi.advanceTimersByTimeAsync(1_000);
317 configure();
318 });
319 await act(async () => frame());
320 expect(viewerMounts).toBe(1);
321 await act(async () => root.render(view(false)));
322 expect(viewerUnmounts).toBe(1);
323 expect(vi.getTimerCount()).toBe(0);
324});