Merge pull request #4853 from rommapp/fix/pdf-viewer-tabs

fix(v2): mount one PDF viewer at a time in the Media tab
This commit is contained in:
Georges-Antoine Assi
2026-09-28 08:10:03 -04:00
committed by GitHub
6 changed files with 237 additions and 27 deletions

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
// ManualSubtab — the Media tab's Manual panel. Surfaces the scraped primary
// ManualSubtab: the Media tab's Manual panel. Surfaces the scraped primary
// manual plus any manual-category files sitting in the ROM folder, picking the
// viewer (PDF or Markdown) by extension. An entry selector appears when more
// than one manual exists. The panel doubles as a drag-and-drop upload target.
@@ -36,6 +36,9 @@ const props = defineProps<{
/** Drop the header Upload button when the parent renders it elsewhere
* (through the exposed `openUpload`). */
hideUpload?: boolean;
/** Whether this panel may mount the PDF viewer (one per page, see
* MediaTab). */
pdfActive?: boolean;
}>();
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();
@@ -269,7 +272,7 @@ function requestDeleteManual() {
@delete="requestDeleteManual"
/>
<PdfViewer
v-else
v-else-if="pdfActive"
:key="selectedManual.url"
:pdf-url="selectedManual.url"
:rom-id="rom.id"
@@ -297,7 +300,7 @@ function requestDeleteManual() {
scrollbar-color: var(--r-color-border-strong) transparent;
}
/* Header — hosts the manual entry selector (when more than one manual) and
/* Header: hosts the manual entry selector (when more than one manual) and
the Upload button, pushed to the right. */
.r-v2-manual__head {
display: flex;
@@ -306,7 +309,7 @@ function requestDeleteManual() {
flex-shrink: 0;
}
/* Manual entry selector — capped width so it doesn't stretch to fill the
/* Manual entry selector: capped width so it doesn't stretch to fill the
row. */
.r-v2-manual__select {
max-width: 360px;
@@ -338,7 +341,7 @@ html[data-bp~="sm-and-down"] .r-v2-manual__fill {
min-height: 20rem;
}
/* Viewer — fills the available panel height so the inner PDF / Markdown uses
/* Viewer: fills the available panel height so the inner PDF / Markdown uses
100% and only its own scroll triggers. */
.r-v2-manual__viewer {
flex: 1;

View File

@@ -0,0 +1,111 @@
import { flushPromises, mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, ref } from "vue";
import { createMemoryHistory, createRouter, type Router } from "vue-router";
import { makeDetailedRom } from "@/utils/rom.fixtures";
import MediaTab from "./MediaTab.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("@/v2/composables/useRomSync", () => ({
useRomSync: () => ({ refetchRom: vi.fn() }),
}));
vi.mock("@/v2/composables/useRomSoundtrack", () => ({
useRomSoundtrack: () => ({
tracks: ref([]),
loading: ref(false),
fallbackArtUrl: ref(null),
}),
}));
function panelStub(name: string) {
return {
__esModule: true,
default: defineComponent({
name,
props: { pdfActive: Boolean },
setup: () => ({ canUpload: false, openUpload: () => {} }),
template: `<div />`,
}),
};
}
vi.mock("@/v2/components/GameDetails/ManualSubtab.vue", () =>
panelStub("ManualSubtab"),
);
vi.mock("@/v2/components/GameDetails/WalkthroughSubtab.vue", () =>
panelStub("WalkthroughSubtab"),
);
vi.mock("@/v2/components/GameDetails/ScreenshotsSubtab.vue", () =>
panelStub("ScreenshotsSubtab"),
);
vi.mock("@/v2/components/GameDetails/ArtworkSubtab.vue", () =>
panelStub("ArtworkSubtab"),
);
vi.mock("@/v2/components/Soundtrack/Panel.vue", () =>
panelStub("SoundtrackPanel"),
);
let router: Router;
async function mountTab(subtab?: string) {
router = createRouter({
history: createMemoryHistory(),
routes: [{ path: "/rom/:id", component: { template: "<div />" } }],
});
await router.push({
path: "/rom/1",
query: subtab ? { tab: "media", subtab } : { tab: "media" },
});
const wrapper = mount(MediaTab, {
props: {
rom: makeDetailedRom({ has_soundtrack: false }),
},
global: {
plugins: [router],
stubs: { SubtabNav: true, RDropzone: true, REmptyState: true },
},
});
await flushPromises();
return wrapper;
}
function pdfActive(wrapper: Awaited<ReturnType<typeof mountTab>>) {
return {
manual: wrapper.findComponent({ name: "ManualSubtab" }).props("pdfActive"),
walkthrough: wrapper
.findComponent({ name: "WalkthroughSubtab" })
.props("pdfActive"),
};
}
async function selectSubtab(subtab: string) {
await router.push({ path: "/rom/1", query: { tab: "media", subtab } });
await flushPromises();
}
describe("MediaTab PDF viewer ownership", () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it("lets only the visited PDF subtab mount a viewer", async () => {
const wrapper = await mountTab();
expect(pdfActive(wrapper)).toEqual({ manual: true, walkthrough: false });
await selectSubtab("walkthrough");
expect(pdfActive(wrapper)).toEqual({ manual: false, walkthrough: true });
});
it("keeps the last PDF subtab's viewer across non-PDF subtabs", async () => {
const wrapper = await mountTab("walkthrough");
await selectSubtab("screenshots");
expect(pdfActive(wrapper)).toEqual({ manual: false, walkthrough: true });
});
it("mounts no viewer until a PDF subtab is shown", async () => {
const wrapper = await mountTab("artwork");
expect(pdfActive(wrapper)).toEqual({ manual: false, walkthrough: false });
});
});

View File

@@ -12,7 +12,7 @@
//
// The soundtrack player is reused from v1 for now.
import { RBtn, RDropzone, REmptyState } from "@v2/lib";
import { computed, defineAsyncComponent, ref } from "vue";
import { computed, defineAsyncComponent, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { DetailedRom } from "@/stores/roms";
import SubtabNav, {
@@ -79,6 +79,17 @@ const subTab = useSubtabQuery<Subtab>(
"manual",
);
// vue3-pdf-app drives one global pdf.js app, so only the last shown PDF subtab
// mounts a PdfViewer.
const pdfSubtab = ref<"manual" | "walkthrough" | null>(null);
watch(
subTab,
(value) => {
if (value === "manual" || value === "walkthrough") pdfSubtab.value = value;
},
{ immediate: true },
);
// ---------- Subtab nav ----------
const subtabDefs = computed<SubtabNavItem<Subtab>[]>(() => [
{
@@ -188,14 +199,19 @@ async function deleteSoundtrack(fileId: number) {
<div class="r-v2-media__content">
<!-- All subtab sections stay mounted (v-show, not v-if). The manual,
soundtrack and screenshots panels are heavy defineAsyncComponent
loads — un/remounting them on every subtab switch causes a visible
loads; un/remounting them on every subtab switch causes a visible
main-thread freeze (the PDF parser is the worst offender). With
v-show the cost is paid once on Media tab entry and switching is a
CSS toggle. -->
<!-- Manual subtab — its own component (PDF / Markdown viewer with an
CSS toggle (bar the PDF viewer, see `pdfSubtab`). -->
<!-- Manual subtab: its own component (PDF / Markdown viewer with an
entry selector; scrolls independently). -->
<section v-show="subTab === 'manual'" class="r-v2-media__panel">
<ManualSubtab ref="manualPanel" :rom="rom" :hide-upload="smAndDown" />
<ManualSubtab
ref="manualPanel"
:rom="rom"
:hide-upload="smAndDown"
:pdf-active="pdfSubtab === 'manual'"
/>
</section>
<!-- Walkthrough subtab: uploaded or GameFAQs-fetched documents, with
@@ -205,16 +221,17 @@ async function deleteSoundtrack(fileId: number) {
ref="walkthroughPanel"
:rom="rom"
:hide-upload="smAndDown"
:pdf-active="pdfSubtab === 'walkthrough'"
/>
</section>
<!-- Screenshots subtab — its own component (ROM / Mine / Community
<!-- Screenshots subtab: its own component (ROM / Mine / Community
sections, per-user public/private). -->
<section v-show="subTab === 'screenshots'" class="r-v2-media__panel">
<ScreenshotsSubtab :rom="rom" />
</section>
<!-- Artwork subtab — read-only gallery of scraped art assets
<!-- Artwork subtab: read-only gallery of scraped art assets
(bezel / logo / marquee / box art / fan art / videos). -->
<section v-show="subTab === 'artwork'" class="r-v2-media__panel">
<ArtworkSubtab :rom="rom" />
@@ -288,7 +305,7 @@ async function deleteSoundtrack(fileId: number) {
gap: 24px;
/* Fills the parent tab panel exactly so the PDF viewer (inside the
manual section) can size to 100% without forcing the outer panel
to scroll — the PDF has its own internal scroll. */
to scroll; the PDF has its own internal scroll. */
height: 100%;
min-height: 0;
}
@@ -308,7 +325,7 @@ async function deleteSoundtrack(fileId: number) {
min-height: 0;
}
/* Panels — each subtab section fills the content height so its
/* Panels: each subtab section fills the content height so its
children (manual / soundtrack / screenshots) can stretch to 100%
without forcing an outer scrollbar. */
.r-v2-media__panel {
@@ -357,7 +374,7 @@ html[data-bp~="sm-and-down"] .r-v2-media {
gap: 14px;
}
/* Soundtrack — the v1 player has its own internal styling; wrap in an
/* Soundtrack: the v1 player has its own internal styling; wrap in an
elevated container so it blends with v2 tokens. */
.r-v2-media__soundtrack {
border: 1px solid var(--r-color-border);

View File

@@ -0,0 +1,66 @@
import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { nextTick, ref } from "vue";
import PdfViewer from "./PdfViewer.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
vi.mock("vue3-pdf-app", () => ({
default: { name: "VuePdfApp", template: `<div class="pdf-app-stub" />` },
}));
vi.mock("@/v2/composables/useReadingProgress", () => ({
useReadingProgress: () => ({
progress: ref(0),
restore: vi.fn(async () => ({ lastPage: null })),
setPage: vi.fn(),
suppressWhileRestoring: vi.fn(),
}),
}));
type ResizeCallback = (entries: { contentRect: { width: number } }[]) => void;
let resize: ResizeCallback | undefined;
beforeEach(() => {
setActivePinia(createPinia());
resize = undefined;
vi.stubGlobal(
"ResizeObserver",
class {
constructor(callback: ResizeCallback) {
resize = callback;
}
observe() {}
unobserve() {}
disconnect() {}
},
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("PdfViewer", () => {
it("waits for a laid-out container before loading pdf.js", async () => {
const wrapper = mount(PdfViewer, {
props: { pdfUrl: "/manual.pdf" },
global: { stubs: { RTooltip: true, RIcon: true, RProgressLinear: true } },
});
await nextTick();
expect(wrapper.find(".pdf-app-stub").exists()).toBe(false);
resize?.([{ contentRect: { width: 0 } }]);
await nextTick();
expect(wrapper.find(".pdf-app-stub").exists()).toBe(false);
resize?.([{ contentRect: { width: 640 } }]);
await nextTick();
expect(wrapper.find(".pdf-app-stub").exists()).toBe(true);
resize?.([{ contentRect: { width: 0 } }]);
await nextTick();
expect(wrapper.find(".pdf-app-stub").exists()).toBe(true);
});
});

View File

@@ -1,14 +1,15 @@
<script setup lang="ts">
// PdfViewer (v2) — wraps `vue3-pdf-app` with v2 chrome:
// PdfViewer (v2): wraps `vue3-pdf-app` with v2 chrome:
//
// * Single bg-elevated panel hosts toolbar + canvas. The toolbar
// shares the same surface as the PDF area (no internal divider /
// bottom border) so the pane reads as one continuous panel.
// * Plain <button> + RIcon + RTooltip per toolbar action — vue3-pdf-app
// * Plain <button> + RIcon + RTooltip per toolbar action, since vue3-pdf-app
// wires controls by `id`, so raw buttons keep that contract while
// the v2 visual is owned by our scoped CSS.
import { RIcon, RProgressLinear, RTooltip } from "@v2/lib";
import { computed } from "vue";
import { useResizeObserver } from "@vueuse/core";
import { computed, ref, useTemplateRef } from "vue";
import VuePdfApp from "vue3-pdf-app";
import { useI18n } from "vue-i18n";
import { useReadingProgress } from "@/v2/composables/useReadingProgress";
@@ -40,7 +41,15 @@ const pdfTheme = computed<"light" | "dark">(() =>
isLight.value ? "light" : "dark",
);
// IDs the library reaches for to wire up the custom toolbar — must
// pdf.js sizes pages to its container when it loads, so a viewer inside a
// hidden subtab waits until it is laid out.
const viewerEl = useTemplateRef<HTMLElement>("viewer");
const laidOut = ref(false);
useResizeObserver(viewerEl, ([entry]) => {
if (entry && entry.contentRect.width > 0) laidOut.value = true;
});
// IDs the library reaches for to wire up the custom toolbar; they must
// match the field names of the `id-config` prop below.
const ids = {
sidebarToggle: "sidebarToggleId",
@@ -65,7 +74,7 @@ const fileIdRef = computed(() =>
const { progress, restore, setPage, suppressWhileRestoring } =
useReadingProgress(romIdRef, fileIdRef);
// Only the members we touch — vue3-pdf-app hands over pdf.js's application
// Only the members we touch; vue3-pdf-app hands over pdf.js's application
// object untyped.
type PdfApp = {
page: number;
@@ -259,8 +268,9 @@ async function onPagesRendered(pdfApp: PdfApp) {
class="r-v2-pdfv__progress"
/>
<div class="r-v2-pdfv__viewer">
<div ref="viewer" class="r-v2-pdfv__viewer">
<VuePdfApp
v-if="laidOut"
:id-config="ids"
:config="{ toolbar: false }"
:theme="pdfTheme"
@@ -276,14 +286,14 @@ async function onPagesRendered(pdfApp: PdfApp) {
.r-v2-pdfv {
display: flex;
flex-direction: column;
/* Fills the parent container exactly — height comes from the chain
/* Fills the parent container exactly: height comes from the chain
`.r-v2-det__panel → .r-v2-media → .r-v2-media__panel →
.r-v2-manual__viewer`, all flex-sized. The viewer never overflows
so the only visible scroll is the PDF's own internal one. */
height: 100%;
}
/* Toolbar inherits the parent's bg-elevated — no separate background
/* Toolbar inherits the parent's bg-elevated, so no separate background
or divider so the surface reads as one continuous panel. */
.r-v2-pdfv__toolbar {
display: flex;
@@ -328,7 +338,7 @@ async function onPagesRendered(pdfApp: PdfApp) {
html[data-bp~="xs"] .r-v2-pdfv__btn--step {
display: none;
}
/* Danger variant — Delete sits at the end of the toolbar, so it takes
/* Danger variant: Delete sits at the end of the toolbar, so it takes
a danger-tinted foreground + hover so the destructive action reads
different from the navigation/zoom siblings. */
.r-v2-pdfv__btn--danger {
@@ -395,7 +405,7 @@ html[data-bp~="xs"] .r-v2-pdfv__btn--step {
/* vue3-pdf-app paints its own canvas chrome via this CSS variable.
Override with v2 tokens so the canvas blends with the surrounding
bg-elevated container — no visible seam between toolbar and canvas. */
bg-elevated container, with no visible seam between toolbar and canvas. */
.r-v2-pdfv__viewer :deep(.pdf-app.dark),
.r-v2-pdfv__viewer :deep(.pdf-app.light) {
--pdf-app-background-color: var(--r-color-bg-elevated) !important;

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
// WalkthroughSubtab — the Media tab's Walkthrough panel. Surfaces
// WalkthroughSubtab: the Media tab's Walkthrough panel. Surfaces
// walkthrough-category files (uploaded, or fetched from a GameFAQs guide URL),
// picking the viewer (PDF / Markdown / Text) by extension. Mirrors
// ManualSubtab's chrome, plus an "add from GameFAQs URL" affordance.
@@ -52,6 +52,9 @@ const props = defineProps<{
/** Drop the Upload button when the parent renders it elsewhere (through
* the exposed `openUpload`). */
hideUpload?: boolean;
/** Whether this panel may mount the PDF viewer (one per page, see
* MediaTab). */
pdfActive?: boolean;
}>();
const snackbar = useSnackbar();
const confirm = useConfirm();
@@ -273,7 +276,7 @@ async function requestDelete() {
@delete="requestDelete"
/>
<PdfViewer
v-else
v-else-if="pdfActive"
:key="selected.url"
:pdf-url="selected.url"
:rom-id="rom.id"