fix(frontend): show the YouTube video in the game media shelf (#5855)

This commit is contained in:
Sam Dornan authored and GitHub committed 2026-12-04 15:39:24 -06:00
1 parent e964bbec88
commit b20c0458d4
32 files changed
+551 -18

No files matched your search

@@ -9,7 +9,7 @@ import { REmptyState } from "@/lib";
import type { DetailedRom } from "@/stores/roms";
import { resolveRomArtwork } from "@/utils/romArtwork";
const props = defineProps<{ rom: DetailedRom }>();
const props = defineProps<{ rom: DetailedRom; suspended?: boolean }>();
const { t } = useI18n();
const { isPinned, togglePin } = usePinnedMedia(() => props.rom);
@@ -29,6 +29,7 @@ const artwork = computed(() => resolveRomArtwork(props.rom));
v-else
:items="artwork"
captions
:suspended="suspended"
:is-pinned="isPinned"
@toggle-pin="togglePin"
/>
@@ -34,6 +34,24 @@ function stubLoad() {
}
describe("MediaShelf", () => {
it("renders a YouTube item as an embed, kept out of the lightbox", () => {
const wrapper = mount(MediaShelf, {
props: {
items: [{ key: "yt", label: "YouTube", url: "", youtubeId: "abc123" }],
suspended: true,
},
global: { stubs: { RCarousel: true, RIcon: true, YoutubeEmbed: true } },
});
const embed = wrapper.getComponent({ name: "YoutubeEmbed" });
expect(embed.props()).toMatchObject({
videoId: "abc123",
title: "YouTube",
suspended: true,
});
expect(wrapper.find("button.r-media-shelf__btn").exists()).toBe(false);
});
it("does not start loading a clip until it is played", () => {
const wrapper = mountShelf([clip]);
@@ -4,6 +4,7 @@
import { computed, reactive, ref, type VNode } from "vue";
import { useI18n } from "vue-i18n";
import MediaPinButton from "@/components/GameDetails/MediaPinButton.vue";
import YoutubeEmbed from "@/components/GameDetails/YoutubeEmbed.vue";
import { RCarousel, RIcon } from "@/lib";
import { claimMedia, releaseMedia } from "@/utils/releaseMedia";
@@ -14,6 +15,8 @@ export type MediaShelfItem = {
isVideo?: boolean;
/** Still shown in a clip's box until it plays. */
poster?: string;
/** Renders a YouTube embed instead of an image or clip; `url` is unused. */
youtubeId?: string;
};
defineOptions({ inheritAttrs: false });
@@ -23,12 +26,16 @@ const props = defineProps<{
captions?: boolean;
compact?: boolean;
isPinned?: ((key: string) => boolean) | undefined;
/** The shelf sits in a hidden panel, so embeds pause. */
suspended?: boolean;
}>();
const emit = defineEmits<{ "toggle-pin": [key: string] }>();
const { t } = useI18n();
const images = computed(() => props.items.filter((item) => !item.isVideo));
const images = computed(() =>
props.items.filter((item) => !item.isVideo && !item.youtubeId),
);
// Lightbox indexes into the image-only list, so map a clicked card to its
// position there (videos are skipped).
@@ -83,10 +90,16 @@ function onClipPlay(event: Event, key: string) {
>
<div class="r-media-shelf__frame">
<div class="r-media-shelf__stage">
<YoutubeEmbed
v-if="item.youtubeId"
:video-id="item.youtubeId"
:title="item.label"
:suspended="suspended"
/>
<!-- Scraped preview clips ship no caption track. -->
<!-- eslint-disable-next-line vuejs-accessibility/media-has-caption -->
<video
v-if="item.isVideo"
v-else-if="item.isVideo"
:key="`${item.key}:${resets.get(item.key) ?? 0}`"
class="r-media-shelf__media r-media-shelf__media--video"
:src="item.url"
@@ -119,7 +132,11 @@ function onClipPlay(event: Event, key: string) {
</div>
</div>
<figcaption v-if="captions" class="r-media-shelf__caption">
<RIcon v-if="item.isVideo" icon="mdi-play-circle-outline" size="13" />
<RIcon
v-if="item.isVideo || item.youtubeId"
icon="mdi-play-circle-outline"
size="13"
/>
{{ item.label }}
</figcaption>
</figure>
@@ -265,7 +265,7 @@ async function deleteSoundtrack(fileId: number) {
class="r-media__panel"
v-bind="panelAttrs('artwork')"
>
<ArtworkSubtab :rom="rom" />
<ArtworkSubtab :rom="rom" :suspended="subTab !== 'artwork'" />
</section>
<!-- Soundtrack subtab -->
@@ -0,0 +1,154 @@
import { mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { nextTick } from "vue";
import YoutubeEmbed from "@/components/GameDetails/YoutubeEmbed.vue";
import storeHeartbeat from "@/stores/heartbeat";
import { claimMedia, releaseMedia } from "@/utils/releaseMedia";
vi.mock("vue-i18n");
type Player = { postMessage: ReturnType<typeof vi.fn> };
type EmbedWrapper = VueWrapper & { player: Player };
const mounted: VueWrapper[] = [];
// The test DOM loads no iframe pages, so each frame gets a stand-in window
// that records what the page posts to the player.
function mountEmbed(props: { suspended?: boolean } = {}): EmbedWrapper {
const wrapper = mount(YoutubeEmbed, {
props: { videoId: "abc123", title: "YouTube", ...props },
attachTo: document.body,
});
const player: Player = { postMessage: vi.fn() };
Object.defineProperty(wrapper.get("iframe").element, "contentWindow", {
value: player,
});
mounted.push(wrapper);
return Object.assign(wrapper, { player });
}
// Posts what the player sends after the "listening" handshake.
function playerSays(
wrapper: EmbedWrapper,
data: unknown,
origin = "https://www.youtube.com",
) {
window.dispatchEvent(
new MessageEvent("message", {
data: JSON.stringify(data),
origin,
source: wrapper.player as unknown as Window,
}),
);
}
function sentCommands(wrapper: EmbedWrapper) {
return wrapper.player.postMessage.mock.calls
.map(
([msg]) => JSON.parse(msg as string) as { event: string; func?: string },
)
.filter((msg) => msg.event === "command")
.map((msg) => msg.func);
}
beforeEach(() => setActivePinia(createPinia()));
afterEach(() => mounted.splice(0).forEach((w) => w.unmount()));
describe("YoutubeEmbed", () => {
it("loads the player lazily through the base URL with the JS API on", () => {
const heartbeat = storeHeartbeat();
heartbeat.value = {
...heartbeat.value,
FRONTEND: {
...heartbeat.value.FRONTEND,
YOUTUBE_BASE_URL: "https://yt.example",
},
};
const frame = mountEmbed().get("iframe");
const src = new URL(frame.attributes("src")!);
expect(`${src.origin}${src.pathname}`).toBe(
"https://yt.example/embed/abc123",
);
expect(src.searchParams.get("enablejsapi")).toBe("1");
expect(frame.attributes("loading")).toBe("lazy");
expect(frame.attributes("credentialless")).toBeDefined();
});
it("tells the player it is listening once the frame loads", async () => {
const wrapper = mountEmbed();
await wrapper.get("iframe").trigger("load");
expect(
JSON.parse(wrapper.player.postMessage.mock.calls[0]![0] as string),
).toMatchObject({
event: "listening",
});
expect(wrapper.player.postMessage.mock.calls[0]![1]).toBe(
"https://www.youtube.com",
);
});
it("toggles playback from the host button", async () => {
const wrapper = mountEmbed();
await wrapper.get("button").trigger("click");
playerSays(wrapper, { event: "onStateChange", info: 1 });
await nextTick();
await wrapper.get("button").trigger("click");
expect(sentCommands(wrapper)).toEqual(["playVideo", "pauseVideo"]);
});
it("ignores state messages from another origin", async () => {
const wrapper = mountEmbed();
playerSays(
wrapper,
{ event: "onStateChange", info: 1 },
"https://evil.example",
);
await nextTick();
await wrapper.get("button").trigger("click");
expect(sentCommands(wrapper)).toEqual(["playVideo"]);
});
it("pauses when a local clip starts playing", () => {
const wrapper = mountEmbed();
playerSays(wrapper, {
event: "infoDelivery",
info: { playerState: 1 },
});
const clip = document.createElement("video");
vi.spyOn(clip, "load").mockImplementation(() => undefined);
claimMedia(clip, vi.fn());
expect(sentCommands(wrapper)).toEqual(["pauseVideo"]);
releaseMedia(clip);
});
it("releases a local clip when it starts playing", () => {
const clip = document.createElement("video");
clip.setAttribute("src", "/clip.mp4");
vi.spyOn(clip, "load").mockImplementation(() => undefined);
const onRelease = vi.fn();
claimMedia(clip, onRelease);
playerSays(mountEmbed(), { event: "onStateChange", info: 1 });
expect(clip.hasAttribute("src")).toBe(false);
expect(onRelease).toHaveBeenCalledTimes(1);
});
it("pauses when its panel is hidden", async () => {
const wrapper = mountEmbed();
await wrapper.setProps({ suspended: true });
expect(sentCommands(wrapper)).toEqual(["pauseVideo"]);
});
});
@@ -0,0 +1,170 @@
<script setup lang="ts">
// A YouTube player driven over the embed's postMessage API, so it joins the
// one-clip-at-a-time rule and gets a play/pause control pads can reach.
import { useEventListener } from "@vueuse/core";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { RButton } from "@/lib";
import storeHeartbeat from "@/stores/heartbeat";
import { claimPlayer, releasePlayer } from "@/utils/releaseMedia";
const props = defineProps<{
videoId: string;
title: string;
suspended?: boolean;
}>();
// YT.PlayerState.PLAYING
const PLAYING = 1;
const { t } = useI18n();
const heartbeat = storeHeartbeat();
const frame = ref<HTMLIFrameElement | null>(null);
const playing = ref(false);
const owner = {};
const baseUrl = computed(() => heartbeat.value.FRONTEND.YOUTUBE_BASE_URL);
const playerOrigin = computed(() => new URL(baseUrl.value).origin);
const src = computed(() => {
const url = new URL(
`${baseUrl.value}/embed/${encodeURIComponent(props.videoId)}`,
);
url.searchParams.set("enablejsapi", "1");
url.searchParams.set("origin", window.location.origin);
return url.toString();
});
// Not in Vue's IframeHTMLAttributes typings yet.
const embedAttrs = { credentialless: "" } as Record<string, string>;
function post(message: Record<string, unknown>) {
frame.value?.contentWindow?.postMessage(
JSON.stringify(message),
playerOrigin.value,
);
}
function command(func: "playVideo" | "pauseVideo") {
post({ event: "command", func, args: [] });
}
function pause() {
command("pauseVideo");
}
// The player only reports its state after the page says it is listening.
function onLoad() {
playing.value = false;
post({ event: "listening", id: props.videoId, channel: "widget" });
}
function playerState(data: unknown): number | undefined {
if (typeof data !== "string") return undefined;
try {
const msg = JSON.parse(data);
if (msg.event === "onStateChange" && typeof msg.info === "number") {
return msg.info;
}
if (
msg.event === "infoDelivery" &&
typeof msg.info?.playerState === "number"
) {
return msg.info.playerState;
}
} catch {
// Other widgets on the page post non-JSON messages.
}
return undefined;
}
useEventListener(window, "message", (event: MessageEvent) => {
if (!frame.value || event.source !== frame.value.contentWindow) return;
if (event.origin !== playerOrigin.value) return;
const state = playerState(event.data);
if (state === undefined) return;
playing.value = state === PLAYING;
if (playing.value) claimPlayer(owner, pause);
});
function toggle() {
command(playing.value ? "pauseVideo" : "playVideo");
}
watch(
() => props.suspended,
(suspended) => {
if (suspended) pause();
},
);
onBeforeUnmount(() => releasePlayer(owner));
</script>
<template>
<div class="r-youtube-embed">
<iframe
ref="frame"
class="r-youtube-embed__frame"
:src="src"
:title="title"
v-bind="embedAttrs"
loading="lazy"
allow="
accelerometer;
autoplay;
clipboard-write;
encrypted-media;
gyroscope;
picture-in-picture;
web-share;
"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
@load="onLoad"
/>
<RButton
class="r-youtube-embed__toggle"
:icon="playing ? 'mdi-pause' : 'mdi-play'"
size="small"
variant="flat"
:aria-label="playing ? t('rom.media-pause') : t('rom.media-play')"
:tooltip="playing ? t('rom.media-pause') : t('rom.media-play')"
@click="toggle"
/>
</div>
</template>
<style scoped>
.r-youtube-embed {
position: relative;
}
.r-youtube-embed__frame {
display: block;
height: var(--art-h);
max-width: var(--art-w);
aspect-ratio: 16 / 9;
border: 0;
border-radius: var(--r-radius-art);
background: var(--r-color-cover-placeholder);
}
/* Sits on the video, so it needs the fixed overlay scrim to stay legible.
Hidden until hover or focus so it doesn't cover the player's own title. */
.r-button.r-youtube-embed__toggle {
position: absolute;
top: 6px;
left: 6px;
background: var(--r-color-overlay-scrim-strong);
color: var(--r-color-overlay-fg);
opacity: 0;
transition: opacity var(--r-motion-fast) var(--r-motion-ease-out);
}
.r-youtube-embed:hover .r-youtube-embed__toggle,
.r-youtube-embed__toggle:focus-visible,
html[data-input="pad"] .r-youtube-embed__toggle,
html[data-input="key"] .r-youtube-embed__toggle,
html[data-bp~="sm-and-down"] .r-youtube-embed__toggle {
opacity: 1;
}
</style>
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Маркиза",
"media-miximage": "Комбинирано изображение",
"media-miximage-v2": "Комбинирано изображение (v2)",
"media-pause": "Пауза",
"media-physical": "Физически носител",
"media-physical-disc": "Физически носител (диск {n})",
"media-play": "Пусни",
"media-title-screen": "Заглавен екран",
"media-video": "Видео",
"media-video-normalized": "Видео (стандартизирано)",
"media-youtube": "YouTube",
"metadata": "Метаданни",
"metadata-ids": "Метаданни ID-та",
"metadata-providers": "Доставчици на метаданни",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Kombinovaný obrázek",
"media-miximage-v2": "Kombinovaný obrázek (v2)",
"media-pause": "Pozastavit",
"media-physical": "Fyzické médium",
"media-physical-disc": "Fyzické médium (disk {n})",
"media-play": "Přehrát",
"media-title-screen": "Úvodní obrazovka",
"media-video": "Video",
"media-video-normalized": "Video (standardizované)",
"media-youtube": "YouTube",
"metadata": "Metadata",
"metadata-ids": "ID metadat",
"metadata-providers": "Poskytovatelé metadat",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Mischbild",
"media-miximage-v2": "Mischbild (v2)",
"media-pause": "Pause",
"media-physical": "Physischer Datenträger",
"media-physical-disc": "Physischer Datenträger (Disc {n})",
"media-play": "Abspielen",
"media-title-screen": "Titelbildschirm",
"media-video": "Video",
"media-video-normalized": "Video (standardisiert)",
"media-youtube": "YouTube",
"metadata": "Metadaten",
"metadata-ids": "Metadaten-IDs",
"metadata-providers": "Metadaten-Anbieter",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Mix image",
"media-miximage-v2": "Mix image (v2)",
"media-pause": "Pause",
"media-physical": "Physical media",
"media-physical-disc": "Physical media (disc {n})",
"media-play": "Play",
"media-title-screen": "Title screen",
"media-video": "Video",
"media-video-normalized": "Video (standardized)",
"media-youtube": "YouTube",
"metadata": "Metadata",
"metadata-ids": "Metadata IDs",
"metadata-providers": "Metadata providers",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Mix image",
"media-miximage-v2": "Mix image (v2)",
"media-pause": "Pause",
"media-physical": "Physical media",
"media-physical-disc": "Physical media (disc {n})",
"media-play": "Play",
"media-title-screen": "Title screen",
"media-video": "Video",
"media-video-normalized": "Video (standardized)",
"media-youtube": "YouTube",
"metadata": "Metadata",
"metadata-ids": "Metadata IDs",
"metadata-providers": "Metadata providers",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquesina",
"media-miximage": "Imagen combinada",
"media-miximage-v2": "Imagen combinada (v2)",
"media-pause": "Pausar",
"media-physical": "Soporte físico",
"media-physical-disc": "Soporte físico (disco {n})",
"media-play": "Reproducir",
"media-title-screen": "Pantalla de título",
"media-video": "Vídeo",
"media-video-normalized": "Vídeo (estandarizado)",
"media-youtube": "YouTube",
"metadata": "Metadatos",
"metadata-ids": "IDs de metadatos",
"metadata-providers": "Proveedores de metadatos",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Image composite",
"media-miximage-v2": "Image composite (v2)",
"media-pause": "Pause",
"media-physical": "Support physique",
"media-physical-disc": "Support physique (disque {n})",
"media-play": "Lire",
"media-title-screen": "Écran-titre",
"media-video": "Vidéo",
"media-video-normalized": "Vidéo (standardisée)",
"media-youtube": "YouTube",
"metadata": "Métadonnées",
"metadata-ids": "IDs de métadonnées",
"metadata-providers": "Fournisseurs de métadonnées",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Kombinált kép",
"media-miximage-v2": "Kombinált kép (v2)",
"media-pause": "Szünet",
"media-physical": "Fizikai adathordozó",
"media-physical-disc": "Fizikai adathordozó ({n}. lemez)",
"media-play": "Lejátszás",
"media-title-screen": "Címképernyő",
"media-video": "Videó",
"media-video-normalized": "Videó (szabványosított)",
"media-youtube": "YouTube",
"metadata": "Metaadat",
"metadata-ids": "Metaadat ID-k",
"metadata-providers": "Metaadat-szolgáltatók",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Immagine combinata",
"media-miximage-v2": "Immagine combinata (v2)",
"media-pause": "Pausa",
"media-physical": "Supporto fisico",
"media-physical-disc": "Supporto fisico (disco {n})",
"media-play": "Riproduci",
"media-title-screen": "Schermata del titolo",
"media-video": "Video",
"media-video-normalized": "Video (standardizzato)",
"media-youtube": "YouTube",
"metadata": "Metadati",
"metadata-ids": "ID metadati",
"metadata-providers": "Provider dei metadati",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "マーキー",
"media-miximage": "ミックス画像",
"media-miximage-v2": "ミックス画像(v2)",
"media-pause": "一時停止",
"media-physical": "物理メディア",
"media-physical-disc": "物理メディア(ディスク{n})",
"media-play": "再生",
"media-title-screen": "タイトル画面",
"media-video": "ビデオ",
"media-video-normalized": "ビデオ(標準化)",
"media-youtube": "YouTube",
"metadata": "メタデータ",
"metadata-ids": "メタデータID",
"metadata-providers": "メタデータプロバイダ",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "마퀴",
"media-miximage": "혼합 이미지",
"media-miximage-v2": "혼합 이미지 (v2)",
"media-pause": "일시 정지",
"media-physical": "실물 미디어",
"media-physical-disc": "실물 미디어 (디스크 {n})",
"media-play": "재생",
"media-title-screen": "타이틀 화면",
"media-video": "비디오",
"media-video-normalized": "비디오 (표준화)",
"media-youtube": "YouTube",
"metadata": "메타데이터",
"metadata-ids": "메타데이터 ID",
"metadata-providers": "메타데이터 제공자",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Obraz złożony",
"media-miximage-v2": "Obraz złożony (v2)",
"media-pause": "Wstrzymaj",
"media-physical": "Nośnik fizyczny",
"media-physical-disc": "Nośnik fizyczny (płyta {n})",
"media-play": "Odtwórz",
"media-title-screen": "Ekran tytułowy",
"media-video": "Wideo",
"media-video-normalized": "Wideo (znormalizowane)",
"media-youtube": "YouTube",
"metadata": "Metadane",
"metadata-ids": "ID-y metadanych",
"metadata-providers": "Dostawcy metadanych",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Imagem combinada",
"media-miximage-v2": "Imagem combinada (v2)",
"media-pause": "Pausar",
"media-physical": "Mídia física",
"media-physical-disc": "Mídia física (disco {n})",
"media-play": "Reproduzir",
"media-title-screen": "Tela de título",
"media-video": "Vídeo",
"media-video-normalized": "Vídeo (padronizado)",
"media-youtube": "YouTube",
"metadata": "Metadados",
"metadata-ids": "IDs Metadados",
"metadata-providers": "Provedores de metadados",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Imagine combinată",
"media-miximage-v2": "Imagine combinată (v2)",
"media-pause": "Pauză",
"media-physical": "Suport fizic",
"media-physical-disc": "Suport fizic (disc {n})",
"media-play": "Redare",
"media-title-screen": "Ecran de titlu",
"media-video": "Video",
"media-video-normalized": "Video (standardizat)",
"media-youtube": "YouTube",
"metadata": "Metadate",
"metadata-ids": "ID-uri Metadate",
"metadata-providers": "Furnizori de metadate",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Маркиза",
"media-miximage": "Комбинированное изображение",
"media-miximage-v2": "Комбинированное изображение (v2)",
"media-pause": "Пауза",
"media-physical": "Физический носитель",
"media-physical-disc": "Физический носитель (диск {n})",
"media-play": "Воспроизвести",
"media-title-screen": "Титульный экран",
"media-video": "Видео",
"media-video-normalized": "Видео (стандартизированное)",
"media-youtube": "YouTube",
"metadata": "Метаданные",
"metadata-ids": "ID-ы метаданных",
"metadata-providers": "Поставщики метаданных",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Mixbild",
"media-miximage-v2": "Mixbild (v2)",
"media-pause": "Pausa",
"media-physical": "Fysiska medier",
"media-physical-disc": "Fysiskt medium (skiva {n})",
"media-play": "Spela upp",
"media-title-screen": "Titelskärm",
"media-video": "Video",
"media-video-normalized": "Video (standardiserad)",
"media-youtube": "YouTube",
"metadata": "Metadata",
"metadata-ids": "Metadata-ID:n",
"metadata-providers": "Metadatakällor",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Marquee",
"media-miximage": "Karışık görüntü",
"media-miximage-v2": "Karışık görüntü (v2)",
"media-pause": "Duraklat",
"media-physical": "Fiziksel medya",
"media-physical-disc": "Fiziksel medya ({n}. disk)",
"media-play": "Oynat",
"media-title-screen": "Başlık ekranı",
"media-video": "Video",
"media-video-normalized": "Video (standartlaştırılmış)",
"media-youtube": "YouTube",
"metadata": "Meta veri",
"metadata-ids": "Meta veri ID'leri",
"metadata-providers": "Meta veri sağlayıcıları",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "Вивіска аркадного автомата",
"media-miximage": "Комбіноване зображення",
"media-miximage-v2": "Комбіноване зображення (v2)",
"media-pause": "Пауза",
"media-physical": "Фізичні носії",
"media-physical-disc": "Фізичний носій (диск {n})",
"media-play": "Відтворити",
"media-title-screen": "Титульний екран",
"media-video": "Відео",
"media-video-normalized": "Відео (стандартизоване)",
"media-youtube": "YouTube",
"metadata": "Метадані",
"metadata-ids": "Ідентифікатори метаданих",
"metadata-providers": "Постачальники метаданих",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "顶部标牌",
"media-miximage": "混合图像",
"media-miximage-v2": "混合图像(v2)",
"media-pause": "暂停",
"media-physical": "实体媒介",
"media-physical-disc": "实体媒介(光盘 {n})",
"media-play": "播放",
"media-title-screen": "标题画面",
"media-video": "视频",
"media-video-normalized": "视频(标准化)",
"media-youtube": "YouTube",
"metadata": "元数据",
"metadata-ids": "元数据ID",
"metadata-providers": "元数据提供商",
+3
View File
@@ -241,11 +241,14 @@
"media-marquee": "頂部標牌",
"media-miximage": "混合圖像",
"media-miximage-v2": "混合圖像(v2)",
"media-pause": "暫停",
"media-physical": "實體媒介",
"media-physical-disc": "實體媒介(光碟 {n})",
"media-play": "播放",
"media-title-screen": "標題畫面",
"media-video": "影片",
"media-video-normalized": "影片(標準化)",
"media-youtube": "YouTube",
"metadata": "元數據",
"metadata-ids": "元數據ID",
"metadata-providers": "中繼資料提供商",
+6
View File
@@ -78,6 +78,12 @@ describe("defaultPinnedMediaKeys", () => {
]);
});
it("includes the YouTube embed", () => {
const rom = romWithPins(null, { youtube_video_id: "abc123" });
expect(defaultPinnedMediaKeys(rom)).toContain("artwork:youtube");
});
it("caps the selection at the pin limit", () => {
const rom = romWithPins(null, {
merged_screenshots: Array.from(
+4 -1
View File
@@ -77,7 +77,10 @@ function defaultKeys({
screenshots,
artwork,
}: ReturnType<typeof mediaSources>): string[] {
return [...screenshots, ...artwork.filter((entry) => entry.isVideo)]
return [
...screenshots,
...artwork.filter((entry) => entry.isVideo || entry.youtubeId),
]
.map((item) => item.key)
.slice(0, PINNED_MEDIA_MAX_ITEMS);
}
+45 -1
View File
@@ -1,5 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { claimMedia, claimPreview, releaseMedia } from "@/utils/releaseMedia";
import {
claimMedia,
claimPlayer,
claimPreview,
releaseMedia,
releasePlayer,
} from "@/utils/releaseMedia";
const claimed: HTMLVideoElement[] = [];
@@ -84,3 +90,41 @@ describe("claimMedia", () => {
expect(onRelease).not.toHaveBeenCalled();
});
});
describe("claimPlayer", () => {
afterEach(() => {
claimed.splice(0).forEach(releaseMedia);
});
it("pauses an embedded player when a clip plays", () => {
const owner = {};
const pause = vi.fn();
claimPlayer(owner, pause);
claimMedia(clip(), vi.fn());
expect(pause).toHaveBeenCalledTimes(1);
});
it("releases the clip played before it", () => {
const playing = clip();
const onRelease = vi.fn();
claimMedia(playing, onRelease);
claimPlayer({}, vi.fn());
expect(playing.hasAttribute("src")).toBe(false);
expect(onRelease).toHaveBeenCalledTimes(1);
});
it("forgets a released player", () => {
const owner = {};
const pause = vi.fn();
claimPlayer(owner, pause);
releasePlayer(owner);
claimMedia(clip(), vi.fn());
expect(pause).not.toHaveBeenCalled();
});
});
+33 -11
View File
@@ -1,39 +1,61 @@
// A paused clip keeps its request open too, so only the clip played last may
// hold one. Hover previews have a slot of their own and never stop a clip.
type Holder = { el: HTMLMediaElement; onRelease: () => void };
type Holder = {
owner: object;
release: () => void;
onRelease: () => void;
};
const holders: { clip: Holder | null; preview: Holder | null } = {
clip: null,
preview: null,
};
function forget(owner: object) {
if (holders.clip?.owner === owner) holders.clip = null;
if (holders.preview?.owner === owner) holders.preview = null;
}
// Dropping the src aborts the in-flight request; pause() alone keeps it open
// and ties up a browser connection.
export function releaseMedia(el: HTMLMediaElement) {
if (holders.clip?.el === el) holders.clip = null;
if (holders.preview?.el === el) holders.preview = null;
forget(el);
el.pause();
el.removeAttribute("src");
el.load();
}
function displace(holder: Holder | null, el: HTMLMediaElement) {
if (!holder || holder.el === el) return;
releaseMedia(holder.el);
function displace(holder: Holder | null, owner: object) {
if (!holder || holder.owner === owner) return;
holder.release();
holder.onRelease();
}
function claim(holder: Holder) {
const { clip, preview } = holders;
holders.clip = holder;
displace(clip, holder.owner);
displace(preview, holder.owner);
}
// Call when a clip starts playing. The clip and preview played before it are
// released, and their owners make them playable again (onRelease).
export function claimMedia(el: HTMLMediaElement, onRelease: () => void) {
const { clip, preview } = holders;
holders.clip = { el, onRelease };
displace(clip, el);
displace(preview, el);
claim({ owner: el, release: () => releaseMedia(el), onRelease });
}
// claimMedia for a player this page can't release directly, such as an
// embedded iframe: `pause` stops it when another clip plays.
export function claimPlayer(owner: object, pause: () => void) {
claim({ owner, release: pause, onRelease: () => undefined });
}
export function releasePlayer(owner: object) {
forget(owner);
}
// claimMedia for a hover preview: it only displaces the preview before it.
export function claimPreview(el: HTMLMediaElement, onRelease: () => void) {
const { preview } = holders;
holders.preview = { el, onRelease };
holders.preview = { owner: el, release: () => releaseMedia(el), onRelease };
displace(preview, el);
}
+27
View File
@@ -283,3 +283,30 @@ describe("resolveRomArtwork (clip posters)", () => {
).toBeUndefined();
});
});
describe("resolveRomArtwork (YouTube)", () => {
it("adds an embed entry from the scraped id", () => {
const rom = romWithFiles([], { youtube_video_id: "abc123" });
const entry = resolveRomArtwork(rom).find((e) => e.youtubeId);
expect(entry?.key).toBe("artwork:youtube");
expect(entry?.youtubeId).toBe("abc123");
});
it("prefers the manual override over the scraped id", () => {
const rom = romWithFiles([], {
youtube_video_id: "scraped",
manual_metadata: { youtube_video_id: "manual" },
});
expect(resolveRomArtwork(rom).find((e) => e.youtubeId)?.youtubeId).toBe(
"manual",
);
});
it("adds nothing without an id", () => {
expect(resolveRomArtwork(romWithFiles([])).some((e) => e.youtubeId)).toBe(
false,
);
});
});
+11
View File
@@ -199,5 +199,16 @@ export function resolveRomArtwork(rom: DetailedRom): MediaShelfItem[] {
});
}
const youtubeId =
rom.manual_metadata?.youtube_video_id || rom.youtube_video_id;
if (youtubeId) {
out.push({
key: mediaKey.artwork("youtube"),
label: i18n.global.t("rom.media-youtube"),
url: "",
youtubeId,
});
}
return [...out, ...libraryMedia];
}