refactor(frontend): split the fullscreen fallback out of the player controller

usePlayerFullscreen took an optional target so three library-driven
players could call it bare, purely to install the prototype patch, and
throw the controller away. That discarded controller was not free:
vueuse defaults the target to documentElement and still registers its
fullscreenchange listeners on both it and document.

Split the side effect into useFullscreenFallback and make the target
required. The three call sites now say what they mean without a comment
apologising for an unused return value.

Refcount the install. The patch is process-global while its callers are
scoped, so overlapping consumers would otherwise stack private patch
layers and restore them in teardown order. Probing HTMLElement.prototype
rather than Element.prototype lets an installed fallback see itself.

Drops v2's writes to playing.fullScreen, which no longer had a reader in
either tree. The field stays because v1 still destructures it.

Also: hoist swallow to module scope, annotate the return inline rather
than exporting an unused interface mirroring vueuse's shape, cover the
document.fullScreen alias at the layer that defines it, dispose test
fallbacks in afterEach so a failed assertion cannot leak a patched
document into the next test, and drop test cases that re-covered the
util through the composable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019Uo885XxwhN8wfC4oCtR48
This commit is contained in:
Sam Dornan
2026-09-15 15:40:29 +00:00
committed by Claude
parent c779765f45
commit a6e267e63a
9 changed files with 141 additions and 169 deletions

View File

@@ -3,6 +3,7 @@ import { defineStore } from "pinia";
export default defineStore("playing", {
state: () => ({
playing: false,
// Written by v1 players only; nothing reads it. Goes with that tree.
fullScreen: false,
// True while a running player stage owns the viewport (see useStageActive).
stageActive: false,

View File

@@ -259,8 +259,6 @@ watch(
);
// ── Fullscreen ─────────────────────────────────────────────────────
// `leaveFullscreen` is called before showing anything teleported to <body>:
// a fullscreened element paints over the whole page, dialogs included.
const {
isFullscreen,
enter: enterFullscreen,
@@ -268,12 +266,11 @@ const {
toggle: toggleFullscreen,
} = usePlayerFullscreen(stageRef);
useEventListener(document, "fullscreenchange", () => {
const resetStageTop = () => {
stageTop = null;
});
useEventListener(window, "resize", () => {
stageTop = null;
});
};
useEventListener(document, "fullscreenchange", resetStageTop);
useEventListener(window, "resize", resetStageTop);
useEventListener(window, "message", onFrameAnnounce);
onBeforeUnmount(() => {
@@ -283,7 +280,9 @@ onBeforeUnmount(() => {
});
// Fullscreen state and its toggle reach the bar as slot props, so only what a
// parent drives imperatively is exposed here.
// parent drives imperatively is exposed here. Callers use `leaveFullscreen`
// before showing anything teleported to <body>: a fullscreened element paints
// over the whole page, dialogs included.
defineExpose({
focusStream,
postToStream,

View File

@@ -1,79 +1,56 @@
import { afterEach, describe, expect, it } from "vitest";
import { effectScope, ref, type EffectScope } from "vue";
import { usePlayerFullscreen } from "./index";
import { useFullscreenFallback, usePlayerFullscreen } from "./index";
// happy-dom ships no Fullscreen API, so the fallback installs by default here
// and a test opts into the native path by defining the method itself.
const NATIVE_KEYS = ["requestFullscreen", "webkitRequestFullscreen"] as const;
// happy-dom ships no Fullscreen API, so the fallback installs by default here.
// The util's own spec covers its behaviour; this covers the composable's.
const scopes: EffectScope[] = [];
let scope: EffectScope | null = null;
// Stopped in afterEach rather than inline: a failed assertion inside
// scope.run() would otherwise leave the fallback patched for the next test.
function runInScope<T>(fn: () => T): T {
scope = effectScope();
return scope.run(fn) as T;
function runInScope<T>(fn: () => T): { value: T; scope: EffectScope } {
const scope = effectScope();
scopes.push(scope);
return { value: scope.run(fn) as T, scope };
}
// Stopped here rather than inline so a failed assertion cannot leave the
// document patched for the next test.
afterEach(() => {
scope?.stop();
scope = null;
NATIVE_KEYS.forEach((key) => Reflect.deleteProperty(Element.prototype, key));
while (scopes.length) scopes.pop()?.stop();
Reflect.deleteProperty(Element.prototype, "requestFullscreen");
document.body.innerHTML = "";
});
function mountStage() {
const el = document.createElement("div");
document.body.appendChild(el);
return ref<HTMLElement | null>(el);
}
describe("usePlayerFullscreen", () => {
it("installs the fallback so a stage can go fullscreen without the native API", async () => {
const stage = mountStage();
const { enter, isFullscreen } = runInScope(() =>
usePlayerFullscreen(stage),
);
await enter();
expect(stage.value?.hasAttribute("data-fullscreen-fallback")).toBe(true);
expect(isFullscreen.value).toBe(true);
});
it("exits back out of the fallback", async () => {
const stage = mountStage();
const { enter, exit, isFullscreen } = runInScope(() =>
usePlayerFullscreen(stage),
);
await enter();
await exit();
expect(stage.value?.hasAttribute("data-fullscreen-fallback")).toBe(false);
expect(isFullscreen.value).toBe(false);
});
describe("useFullscreenFallback", () => {
it("removes the fallback when the scope is disposed", () => {
runInScope(() => usePlayerFullscreen());
const { scope } = runInScope(() => useFullscreenFallback());
expect("requestFullscreen" in HTMLElement.prototype).toBe(true);
scope?.stop();
scope.stop();
expect("requestFullscreen" in HTMLElement.prototype).toBe(false);
});
it("stands aside where the native API exists", () => {
const native = () => Promise.resolve();
Object.defineProperty(Element.prototype, "requestFullscreen", {
value: native,
configurable: true,
writable: true,
});
it("keeps the fallback while another consumer still holds it", () => {
const first = runInScope(() => useFullscreenFallback());
runInScope(() => useFullscreenFallback());
runInScope(() => usePlayerFullscreen(mountStage()));
first.scope.stop();
expect(Element.prototype.requestFullscreen).toBe(native);
expect("requestFullscreen" in HTMLElement.prototype).toBe(true);
});
});
describe("usePlayerFullscreen", () => {
it("drives the stage through the installed fallback", async () => {
const el = document.createElement("div");
document.body.appendChild(el);
const stage = ref<HTMLElement | null>(el);
const { value } = runInScope(() => usePlayerFullscreen(stage));
await value.enter();
expect(value.isFullscreen.value).toBe(true);
expect(el.hasAttribute("data-fullscreen-fallback")).toBe(true);
});
it("swallows a denied request instead of rejecting", async () => {
@@ -82,8 +59,13 @@ describe("usePlayerFullscreen", () => {
configurable: true,
writable: true,
});
const { enter } = runInScope(() => usePlayerFullscreen(mountStage()));
const el = document.createElement("div");
document.body.appendChild(el);
await expect(enter()).resolves.toBeUndefined();
const { value } = runInScope(() =>
usePlayerFullscreen(ref<HTMLElement | null>(el)),
);
await expect(value.enter()).resolves.toBeUndefined();
});
});

View File

@@ -1,38 +1,48 @@
// usePlayerFullscreen — fullscreen for a player stage, native where the
// platform has it and emulated where it does not.
import { useFullscreen, type MaybeElementRef } from "@vueuse/core";
import { onScopeDispose, type ShallowRef } from "vue";
import { installFullscreenFallback } from "@/v2/utils/playerFullscreen";
export interface PlayerFullscreen {
// Refcounted because the patch is process-global while its callers are scoped:
// nesting or overlapping players would otherwise stack private patch layers
// and restore them in teardown order.
let consumers = 0;
let removeFallback: (() => void) | null = null;
/**
* Patches the Fullscreen API for this scope where the platform lacks it.
*
* Players whose emulator library drives fullscreen itself need only this: the
* fallback patches the same prototype the library reaches for.
*/
export function useFullscreenFallback(): void {
if (consumers++ === 0) removeFallback = installFullscreenFallback();
onScopeDispose(() => {
if (--consumers > 0) return;
removeFallback?.();
removeFallback = null;
});
}
// A rejected request is a denial (permissions policy, or no user gesture),
// not a fault to report: the stage simply stays windowed.
const swallow = (run: () => Promise<void>) => () => run().catch(() => {});
/** Fullscreen controls for `target`. */
export function usePlayerFullscreen(target: MaybeElementRef): {
isFullscreen: ShallowRef<boolean>;
enter: () => Promise<void>;
exit: () => Promise<void>;
toggle: () => Promise<void>;
}
/**
* Fullscreen for a player stage, native where the platform has it.
*
* Players whose emulator library drives fullscreen itself (EmulatorJS, Ruffle,
* js-dos) still call this without a target: the fallback patches the same
* prototype the library reaches for, so their own controls work too.
*
* Args:
* target: the element to fullscreen. Omit for fallback installation only.
*/
export function usePlayerFullscreen(
target?: MaybeElementRef,
): PlayerFullscreen {
// Installed before useFullscreen resolves its methods, since on a platform
// without the native API the fallback is what makes them exist.
const removeFallback = installFullscreenFallback();
onScopeDispose(removeFallback);
} {
// Before useFullscreen resolves its methods: where the native API is absent
// the fallback is what makes them exist.
useFullscreenFallback();
const { isFullscreen, enter, exit, toggle } = useFullscreen(target);
// A rejected request is a denial (permissions policy, or no user gesture),
// not a fault to report: the stage simply stays windowed.
const swallow = (run: () => Promise<void>) => () => run().catch(() => {});
return {
isFullscreen,
enter: swallow(enter),

View File

@@ -1,75 +1,74 @@
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { installFullscreenFallback } from "./playerFullscreen";
// The fallback gates on Element.prototype, so the tests move the native
// methods on and off it rather than faking a user agent.
// happy-dom ships no Fullscreen API, so the fallback installs by default here
// and a test opts into the native path by defining the method itself.
const NATIVE_KEYS = ["requestFullscreen", "webkitRequestFullscreen"] as const;
const nativeDescriptors = NATIVE_KEYS.map(
(key) =>
[key, Object.getOwnPropertyDescriptor(Element.prototype, key)] as const,
);
function withoutNativeFullscreen() {
NATIVE_KEYS.forEach((key) => Reflect.deleteProperty(Element.prototype, key));
}
let dispose: (() => void) | undefined;
function withNativeFullscreen() {
Object.defineProperty(Element.prototype, "requestFullscreen", {
value: () => Promise.resolve(),
function defineNative(key: (typeof NATIVE_KEYS)[number], value: unknown) {
Object.defineProperty(Element.prototype, key, {
value,
configurable: true,
writable: true,
});
}
afterEach(() => {
beforeEach(() => {
NATIVE_KEYS.forEach((key) => Reflect.deleteProperty(Element.prototype, key));
});
// Disposed here rather than inline so a failed assertion cannot leave the
// document patched for the next test.
afterEach(() => {
dispose?.();
dispose = undefined;
NATIVE_KEYS.forEach((key) => Reflect.deleteProperty(Element.prototype, key));
nativeDescriptors.forEach(([key, descriptor]) => {
if (descriptor) Object.defineProperty(Element.prototype, key, descriptor);
});
document.body.innerHTML = "";
});
// The deprecated alias the fallback also defines; lib.dom has no type for it.
function legacyFullScreen(): unknown {
return Reflect.get(document, "fullScreen");
}
function mountStage() {
const el = document.createElement("div");
document.body.appendChild(el);
return el;
}
describe("installFullscreenFallback", () => {
it("stands aside where the native API exists", () => {
withNativeFullscreen();
defineNative("requestFullscreen", () => Promise.resolve());
const before = HTMLElement.prototype.requestFullscreen;
const dispose = installFullscreenFallback();
dispose = installFullscreenFallback();
expect(HTMLElement.prototype.requestFullscreen).toBe(before);
dispose();
});
it("stands aside where only the webkit-prefixed API exists (iPad)", () => {
withoutNativeFullscreen();
Object.defineProperty(Element.prototype, "webkitRequestFullscreen", {
value: () => undefined,
configurable: true,
writable: true,
});
defineNative("webkitRequestFullscreen", () => undefined);
const before = HTMLElement.prototype.requestFullscreen;
const dispose = installFullscreenFallback();
dispose = installFullscreenFallback();
expect(HTMLElement.prototype.requestFullscreen).toBe(before);
dispose();
});
it("reports fullscreen as available once installed", () => {
withoutNativeFullscreen();
const dispose = installFullscreenFallback();
dispose = installFullscreenFallback();
expect(document.fullscreenEnabled).toBe(true);
expect(document.fullscreenElement).toBeNull();
dispose();
expect(legacyFullScreen()).toBe(false);
});
it("marks the element and fires fullscreenchange on enter", async () => {
withoutNativeFullscreen();
const dispose = installFullscreenFallback();
const el = document.createElement("div");
document.body.appendChild(el);
dispose = installFullscreenFallback();
const el = mountStage();
let changes = 0;
document.addEventListener("fullscreenchange", () => changes++);
@@ -78,35 +77,30 @@ describe("installFullscreenFallback", () => {
expect(el.hasAttribute("data-fullscreen-fallback")).toBe(true);
expect(document.fullscreenElement).toBe(el);
// The deprecated alias support probes read; see playerFullscreen.ts.
expect(legacyFullScreen()).toBe(true);
expect(changes).toBe(1);
dispose();
});
it("clears the element on exit", async () => {
withoutNativeFullscreen();
const dispose = installFullscreenFallback();
const el = document.createElement("div");
document.body.appendChild(el);
dispose = installFullscreenFallback();
const el = mountStage();
await el.requestFullscreen();
await document.exitFullscreen();
expect(el.hasAttribute("data-fullscreen-fallback")).toBe(false);
expect(document.fullscreenElement).toBeNull();
dispose();
expect(legacyFullScreen()).toBe(false);
});
it("restores the patched API and removes its stylesheet on dispose", async () => {
withoutNativeFullscreen();
const styleCount = document.head.querySelectorAll("style").length;
const dispose = installFullscreenFallback();
const el = document.createElement("div");
document.body.appendChild(el);
const install = installFullscreenFallback();
const el = mountStage();
await el.requestFullscreen();
dispose();
install();
expect("requestFullscreen" in HTMLElement.prototype).toBe(false);
expect(document.head.querySelectorAll("style")).toHaveLength(styleCount);

View File

@@ -1,9 +1,5 @@
// iPhone exposes no Fullscreen API on non-video elements, so a player's
// fullscreen control is inert there. We emulate just enough of the API to
// drive a fixed, viewport-filling stage.
//
// No nav-hiding counterpart is needed: players call useStageActive, which
// unmounts AppNav and BottomNav for the duration of the session.
// fullscreen control is inert there without this.
const FULLSCREEN_STYLE = `
[data-fullscreen-fallback] {
position: fixed !important;
@@ -17,12 +13,11 @@ const FULLSCREEN_STYLE = `
// Feature-detected rather than sniffed for iOS: iPad has the API behind the
// webkit prefix and iPhone has none at all, so sniffing would swap a working
// native implementation for this one on iPad. It also retires the fallback by
// itself if iPhone ever ships the real API.
function hasNativeElementFullscreen() {
// native implementation for this one on iPad.
function hasElementFullscreen() {
return (
"requestFullscreen" in Element.prototype ||
"webkitRequestFullscreen" in Element.prototype
"requestFullscreen" in HTMLElement.prototype ||
"webkitRequestFullscreen" in HTMLElement.prototype
);
}
@@ -33,7 +28,7 @@ function hasNativeElementFullscreen() {
* patched property. A no-op wherever the native API exists.
*/
export function installFullscreenFallback(): () => void {
if (hasNativeElementFullscreen()) {
if (hasElementFullscreen()) {
return () => {};
}
@@ -88,9 +83,8 @@ export function installFullscreenFallback(): () => void {
override(document, "fullscreenEnabled", { get: () => true });
override(document, "fullscreenElement", { get: () => fullscreenElement });
// The deprecated alias for "is the document fullscreen". Support probes
// (vueuse's useFullscreen among them) read it to decide the API is usable,
// so a polyfill that omits it reads as unsupported and silently no-ops.
// Support probes read this deprecated alias to decide the API is usable, so
// omitting it makes the polyfill read as unsupported.
override(document, "fullScreen", { get: () => fullscreenElement !== null });
override(document, "exitFullscreen", { value: exit, writable: true });
override(proto, "requestFullscreen", {

View File

@@ -53,7 +53,7 @@ import { useCoverArt } from "@/v2/composables/useCoverArt";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import { useInputModality } from "@/v2/composables/useInputModality";
import { usePlaySession } from "@/v2/composables/usePlaySession";
import { usePlayerFullscreen } from "@/v2/composables/usePlayerFullscreen";
import { useFullscreenFallback } from "@/v2/composables/usePlayerFullscreen";
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
import { usePlayerNav } from "@/v2/composables/usePlayerNav";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -89,11 +89,9 @@ const snackbar = useSnackbar();
const emitter = inject<Emitter<Events>>("emitter");
const playingStore = storePlaying();
const configStore = storeConfig();
const { playing, fullScreen } = storeToRefs(playingStore);
const { playing } = storeToRefs(playingStore);
const { fullscreenOnPlay } = useFullscreenPref();
// EmulatorJS drives fullscreen through its own control, so no target here:
// this is for the fallback the library's call goes through.
usePlayerFullscreen();
useFullscreenFallback();
const { modality } = useInputModality();
const playSession = usePlaySession();
@@ -226,7 +224,6 @@ async function onPlay() {
}
gameRunning.value = true;
window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value;
fullScreen.value = fullscreenOnPlay.value;
playing.value = true;
const { EJS_NETPLAY_ENABLED } = configStore.config;
@@ -256,7 +253,6 @@ async function onPlay() {
// leaving the unload guard and the input mute armed.
gameRunning.value = false;
playing.value = false;
fullScreen.value = false;
}
}

View File

@@ -13,7 +13,7 @@ import PlayerShell from "@/v2/components/Player/PlayerShell.vue";
import { useConfirm } from "@/v2/composables/useConfirm";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import { usePlaySession } from "@/v2/composables/usePlaySession";
import { usePlayerFullscreen } from "@/v2/composables/usePlayerFullscreen";
import { useFullscreenFallback } from "@/v2/composables/usePlayerFullscreen";
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
@@ -31,9 +31,7 @@ const { t } = useI18n();
const authStore = storeAuth();
const playingStore = storePlaying();
const { fullscreenOnPlay } = useFullscreenPref();
// js-dos drives fullscreen through its own control, so no target here:
// this is for the fallback the library's call goes through.
usePlayerFullscreen();
useFullscreenFallback();
const playSession = usePlaySession();
const snackbar = useSnackbar();
const confirm = useConfirm();

View File

@@ -14,7 +14,7 @@ import { getDownloadPath } from "@/utils";
import PlayerShell from "@/v2/components/Player/PlayerShell.vue";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import { usePlaySession } from "@/v2/composables/usePlaySession";
import { usePlayerFullscreen } from "@/v2/composables/usePlayerFullscreen";
import { useFullscreenFallback } from "@/v2/composables/usePlayerFullscreen";
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
import { colorCanvas } from "@/v2/tokens";
@@ -24,9 +24,7 @@ const DEFAULT_BACKGROUND_COLOR = colorCanvas.bgDeep;
const { t } = useI18n();
const { fullscreenOnPlay } = useFullscreenPref();
// Ruffle drives fullscreen through its own control, so no target here:
// this is for the fallback the library's call goes through.
usePlayerFullscreen();
useFullscreenFallback();
const playingStore = storePlaying();
const playSession = usePlaySession();