Open History to see the last commit
1import type { PerspectiveCamera, Scene, Object3D } from "three";
2import { afterEach, expect, it, vi } from "vite-plus/test";
3
4const gpu = vi.hoisted(() => ({
5 instances: [] as {
6 blank: boolean;
7 allocations: number;
8 disposed: boolean;
9 size: { width: number; height: number; pixelRatio: number };
10 frames: {
11 scene: Scene;
12 phone: Object3D | undefined;
13 rotation: Quaternion | undefined;
14 yaw: number | undefined;
15 cameraZ: number;
16 }[];
17 }[],
18}));
19
20vi.mock("three", async () => {
21 const actual = await vi.importActual<typeof import("three")>("three");
22 return {
23 ...actual,
24 WebGLRenderer: class {
25 outputColorSpace = "";
26 state: (typeof gpu.instances)[number] = {
27 blank: true,
28 allocations: 0,
29 disposed: false,
30 size: { width: 0, height: 0, pixelRatio: 1 },
31 frames: [],
32 };
33 constructor() {
34 gpu.instances.push(this.state);
35 }
36 setDrawingBufferSize(width: number, height: number, pixelRatio: number) {
37 this.state.size = { width, height, pixelRatio };
38 this.state.allocations++;
39 this.state.blank = true;
40 }
41 setSize(width: number, height: number) {
42 this.setDrawingBufferSize(width, height, this.state.size.pixelRatio);
43 }
44 setPixelRatio(pixelRatio: number) {
45 this.setDrawingBufferSize(this.state.size.width, this.state.size.height, pixelRatio);
46 }
47 render(scene: Scene, camera: PerspectiveCamera) {
48 const phone = scene.children.find((child) => child.type === "Group");
49 this.state.frames.push({
50 scene,
51 phone,
52 rotation: phone?.quaternion.clone(),
53 yaw: phone?.rotation.y,
54 cameraZ: camera.position.z,
55 });
56 this.state.blank = false;
57 }
58 dispose() {
59 this.state.disposed = true;
60 }
61 forceContextLoss() {}
62 },
63 };
64});
65
66const models = vi.hoisted(() => ({
67 pending: [] as {
68 signal: AbortSignal;
69 resolve: (model: { asset: import("three").Group; dispose: () => void }) => void;
70 }[],
71}));
72vi.mock("./modelScene.ts", async () => {
73 const actual = await vi.importActual<typeof import("./modelScene.ts")>("./modelScene.ts");
74 return {
75 ...actual,
76 loadDeviceModel: (_source: unknown, signal: AbortSignal) =>
77 new Promise((resolve) => models.pending.push({ signal, resolve })),
78 };
79});
80
81import { BoxGeometry, Group, Mesh, MeshBasicMaterial, PlaneGeometry, Quaternion } from "three";
82import { disposeDeviceModel } from "./modelScene.ts";
83import { createPhoneViewer } from "./phoneViewer.ts";
84import { IOS_TABLET_SHAPE } from "./shapeProfile.ts";
85
86afterEach(() => {
87 vi.restoreAllMocks();
88 vi.unstubAllGlobals();
89 gpu.instances.length = 0;
90 models.pending.length = 0;
91});
92
93function fixture() {
94 const pending = new Map<number, FrameRequestCallback>();
95 let id = 0;
96 let now = 0;
97 vi.spyOn(performance, "now").mockImplementation(() => now);
98 vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
99 pending.set(++id, callback);
100 return id;
101 });
102 vi.stubGlobal("cancelAnimationFrame", (id: number) => pending.delete(id));
103 const canvas = Object.assign(new EventTarget(), { width: 0, height: 0 }) as HTMLCanvasElement;
104 const source = { width: 1206, height: 2622 } as HTMLCanvasElement;
105 const onUnavailable = vi.fn();
106 const onFramingAspect = vi.fn();
107 const viewer = createPhoneViewer({ canvas, source, onUnavailable, onFramingAspect });
108 const draw = (time = now) => {
109 now = time;
110 const callbacks = [...pending.values()];
111 pending.clear();
112 callbacks.forEach((callback) => callback(0));
113 };
114 viewer.resize(400, 700, 2);
115 draw();
116 return {
117 viewer,
118 draw,
119 pending,
120 source,
121 onUnavailable,
122 onFramingAspect,
123 state: gpu.instances[0]!,
124 };
125}
126
127it("retains the drawn phone until resize and redraw commit together, without replacing scene or pose", () => {
128 const { viewer, draw, pending, source, state, onUnavailable } = fixture();
129 viewer.orbit(0.08, 0.04);
130 draw();
131 const previous = state.frames.at(-1)!;
132 const allocations = state.allocations;
133 viewer.resize(500, 700, 2);
134 viewer.resize(450, 700, 2);
135 viewer.frameUpdated();
136 // ResizeObserver runs after rAF. A cleared buffer here would reach the browser's next paint.
137 expect(state.blank).toBe(false);
138 expect(state.allocations).toBe(allocations);
139 expect(pending.size).toBe(1);
140 draw();
141 expect(state.size).toEqual({ width: 450, height: 700, pixelRatio: 2 });
142 expect(state.blank).toBe(false);
143 expect(state.allocations).toBe(allocations + 1);
144 expect(state.frames.at(-1)?.scene).toBe(previous.scene);
145 expect(state.frames.at(-1)?.phone).toBe(previous.phone);
146 expect(state.frames.at(-1)?.yaw).toBe(previous.yaw);
147 viewer.resize(400, 700, 2);
148 draw();
149 expect(state.frames.at(-1)?.cameraZ).toBeCloseTo(previous.cameraZ);
150 expect(source).toMatchObject({ width: 1206, height: 2622 });
151 expect(gpu.instances).toHaveLength(1);
152 expect(onUnavailable).not.toHaveBeenCalled();
153 viewer.dispose();
154});
155
156it("ignores redundant and invalid sizes and combines a DPR change into one allocation and draw", () => {
157 const { viewer, draw, pending, state } = fixture();
158 const allocations = state.allocations;
159 viewer.resize(400, 700, 2);
160 viewer.resize(400, 700, 5);
161 viewer.resize(0, 700, 2);
162 viewer.resize(NaN, 700, 2);
163 expect(pending.size).toBe(0);
164 viewer.resize(400, 700, 1);
165 expect(state.blank).toBe(false);
166 draw();
167 expect(state.size.pixelRatio).toBe(1);
168 expect(state.allocations).toBe(allocations + 1);
169 viewer.resize(450, 700, 1);
170 viewer.dispose();
171 draw();
172 expect(state.allocations).toBe(allocations + 1);
173 expect(state.disposed).toBe(true);
174});
175
176it("changes device shape without replacing the renderer, decoded source or pose", () => {
177 const { viewer, draw, source, state } = fixture();
178 viewer.orbit(0.1, 0.05);
179 draw();
180 const previous = state.frames.at(-1)!;
181 const allocations = state.allocations;
182 viewer.setScreen(null, IOS_TABLET_SHAPE);
183 draw();
184 expect(state.frames.at(-1)?.phone).not.toBe(previous.phone);
185 expect(state.frames.at(-1)?.yaw).toBe(previous.yaw);
186 expect(state.frames.at(-1)?.scene).toBe(previous.scene);
187 expect(state.allocations).toBe(allocations);
188 expect(source.width).toBe(1206);
189 expect(gpu.instances).toHaveLength(1);
190 const tablet = state.frames.at(-1)?.phone;
191 viewer.frameUpdated();
192 draw();
193 expect(state.frames.at(-1)?.phone).toBe(tablet);
194 viewer.dispose();
195});
196
197it("retains the loaded model and pose through rotation and framebuffer resolution changes, then releases it once", async () => {
198 const { viewer, draw, source, state } = fixture();
199 viewer.orbit(0.08, 0.04);
200 draw();
201 const yaw = state.frames.at(-1)!.yaw;
202 viewer.setModel({ id: "iphone-18-pro", url: "/pro.glb" });
203 const asset = new Group();
204 const body = new Mesh(new BoxGeometry(1.15, 2.3, 0.1), new MeshBasicMaterial());
205 body.position.z = -0.02;
206 const display = new Mesh(new PlaneGeometry(1, 2.2), new MeshBasicMaterial());
207 display.geometry.translate(0, 0, 0.043);
208 display.name = "device-screen";
209 asset.add(body, display);
210 const release = vi.spyOn(body.geometry, "dispose");
211 const dispose = vi.fn(() => disposeDeviceModel(asset));
212 models.pending[0]!.resolve({ asset, dispose });
213 await Promise.resolve();
214 draw();
215 const loaded = state.frames.at(-1)!.phone;
216 expect(loaded?.getObjectByName("device-screen")).toBe(display);
217 expect(state.frames.at(-1)!.yaw).toBe(yaw);
218 source.width = 2622;
219 source.height = 1206;
220 viewer.setScreen({ width: 2622, height: 1206, orientation: "landscape_left" });
221 viewer.frameUpdated();
222 viewer.resize(700, 400, 1);
223 draw();
224 expect(state.frames.at(-1)!.phone).toBe(loaded);
225 expect(state.frames.at(-1)!.yaw).toBe(yaw);
226 expect(display.material.map?.image).toBe(source);
227 expect(release).not.toHaveBeenCalled();
228 expect(gpu.instances).toHaveLength(1);
229 viewer.dispose();
230 viewer.dispose();
231 expect(dispose).toHaveBeenCalledOnce();
232 expect(release).toHaveBeenCalledOnce();
233});
234
235it("attaches and detaches an accessory without replacing the device, stream texture, renderer or pose", async () => {
236 const { viewer, draw, source, state, onFramingAspect } = fixture();
237 viewer.setModel({ id: "ipad-pro-13-m5", url: "/ipad.glb" });
238 const asset = new Group();
239 const body = new Mesh(new BoxGeometry(1.8, 2.3, 0.1), new MeshBasicMaterial());
240 const display = new Mesh(new PlaneGeometry(1.7, 2.2), new MeshBasicMaterial());
241 display.geometry.translate(0, 0, 0.043);
242 display.name = "device-screen";
243 asset.add(body, display);
244 const releaseBody = vi.fn(() => disposeDeviceModel(asset));
245 models.pending[0]!.resolve({ asset, dispose: releaseBody });
246 await Promise.resolve();
247 viewer.orbit(0.1, 0.05);
248 draw();
249 const before = state.frames.at(-1)!;
250 const bareAspect = onFramingAspect.mock.lastCall![0];
251 const keyboard = new Group();
252 const deck = new Mesh(new BoxGeometry(2, 1, 1), new MeshBasicMaterial());
253 deck.position.set(1, 0, 0.5);
254 keyboard.add(deck);
255 const releaseKeyboard = vi.fn(() => disposeDeviceModel(keyboard));
256 viewer.setAccessory({
257 id: "ipad-pro-13-m5-magic-keyboard",
258 modelId: "ipad-pro-13-m5",
259 url: "/keyboard.glb",
260 });
261 models.pending[1]!.resolve({ asset: keyboard, dispose: releaseKeyboard });
262 await Promise.resolve();
263 draw();
264 expect(state.frames.at(-1)!.phone).toBe(before.phone);
265 expect(keyboard.parent).toBe(asset.parent);
266 expect(state.frames.at(-1)!.yaw).toBe(before.yaw);
267 expect(display.material.map?.image).toBe(source);
268 expect(state.frames.at(-1)!.cameraZ).toBeGreaterThan(before.cameraZ);
269 expect(onFramingAspect.mock.lastCall![0]).toBeGreaterThan(bareAspect);
270 const calls = onFramingAspect.mock.calls.length;
271 viewer.orbit(0.1, 0.05);
272 viewer.frameUpdated();
273 draw();
274 expect(onFramingAspect).toHaveBeenCalledTimes(calls);
275 viewer.setAccessory(null);
276 draw();
277 expect(keyboard.parent).toBeNull();
278 expect(onFramingAspect.mock.lastCall![0]).toBeCloseTo(bareAspect);
279 expect(releaseKeyboard).toHaveBeenCalledOnce();
280 expect(releaseBody).not.toHaveBeenCalled();
281 expect(state.frames.at(-1)!.phone).toBe(before.phone);
282 expect(state.frames.at(-1)!.cameraZ).toBeCloseTo(before.cameraZ);
283 expect(gpu.instances).toHaveLength(1);
284 viewer.dispose();
285 expect(releaseBody).toHaveBeenCalledOnce();
286 expect(releaseKeyboard).toHaveBeenCalledOnce();
287});
288
289it("rejects incompatible accessories and releases an accessory that finishes after detaching", async () => {
290 const { viewer } = fixture();
291 const keyboard = {
292 id: "ipad-pro-13-m5-magic-keyboard",
293 modelId: "ipad-pro-13-m5",
294 url: "/keyboard.glb",
295 } as const;
296 viewer.setAccessory(keyboard);
297 expect(models.pending).toHaveLength(0);
298 viewer.setModel({ id: "ipad-pro-13-m5", url: "/ipad.glb" });
299 viewer.setAccessory(keyboard);
300 viewer.setAccessory(null);
301 expect(models.pending[1]!.signal.aborted).toBe(true);
302 const dispose = vi.fn();
303 const asset = new Group();
304 models.pending[1]!.resolve({ asset, dispose });
305 await Promise.resolve();
306 expect(asset.parent).toBeNull();
307 expect(dispose).toHaveBeenCalledOnce();
308 viewer.dispose();
309});
310
311it("springs an ordinary device back toward its screen, freezes captured input, and stops rendering at rest", () => {
312 const { viewer, draw, pending, state } = fixture();
313 const initialYaw = state.frames.at(-1)!.yaw!;
314 viewer.setInteractionActive(true, "orbit");
315 viewer.orbit(0.8, 0.4);
316 draw(80);
317 const dragged = state.frames.at(-1)!;
318 expect(Math.abs(dragged.yaw! - initialYaw)).toBeGreaterThan(0.05);
319 viewer.setInteractionActive(false, "orbit");
320 draw(160);
321 viewer.setInteractionActive(true, "touch");
322 draw(180);
323 const captured = state.frames.at(-1)!;
324 viewer.orbit(1, 1);
325 viewer.frameUpdated();
326 draw(1000);
327 expect(state.frames.at(-1)!.yaw).toBe(captured.yaw);
328 expect(state.frames.at(-1)!.cameraZ).toBe(captured.cameraZ);
329 expect(pending.size).toBe(0);
330 viewer.setInteractionActive(false, "touch");
331 for (let time = 1016; time <= 4000 && pending.size; time += 16) draw(time);
332 expect(pending.size).toBe(0);
333 expect(Math.abs(state.frames.at(-1)!.yaw!)).toBeLessThanOrEqual(Math.PI / 3 + 1e-6);
334 expect(state.frames.at(-1)!.phone).toBe(dragged.phone);
335 viewer.dispose();
336});
337
338it("resets the device to a square front view after orbiting", () => {
339 const { viewer, draw, pending, state } = fixture();
340 const front = state.frames.at(-1)!.rotation!;
341 expect(front.angleTo(new Quaternion())).toBeLessThan(1e-6);
342 viewer.orbit(0.8, 0.4);
343 draw(80);
344 expect(state.frames.at(-1)!.rotation!.angleTo(front)).toBeGreaterThan(0.05);
345 viewer.resetPose();
346 for (let time = 96; time <= 3000 && pending.size; time += 16) draw(time);
347 expect(pending.size).toBe(0);
348 expect(state.frames.at(-1)!.rotation!.angleTo(new Quaternion())).toBeLessThan(1e-6);
349 viewer.dispose();
350});