Render v2 QR codes with useQRCode from @vueuse/integrations (#5060)

This commit is contained in:
Sam Dornan
2026-10-02 20:33:19 -04:00
committed by GitHub
parent 5d9705e01b
commit b26a8ab6f2
7 changed files with 306 additions and 80 deletions

View File

@@ -12,6 +12,7 @@
"@floating-ui/vue": "^2.0.0",
"@mdi/font": "7.4.47",
"@vueuse/core": "^15.0.0",
"@vueuse/integrations": "^15.0.0",
"@zxing/browser": "^0.2.0",
"@zxing/library": "^0.23.0",
"axios": "^1.18.1",
@@ -6507,6 +6508,75 @@
"vue": "^3.5.0"
}
},
"node_modules/@vueuse/integrations": {
"version": "15.0.0",
"resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-15.0.0.tgz",
"integrity": "sha512-uWC1608pEocJPeRk1IqrEA3uYHhAGTJNibcMAdxgdK2Sy2Hypc6b+VdNO9KekCxyPc4VXK8SKDp8vsXefR/ZFg==",
"license": "MIT",
"dependencies": {
"@vueuse/core": "15.0.0",
"@vueuse/shared": "15.0.0"
},
"engines": {
"node": ">=22"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"async-validator": "^4",
"axios": "^1",
"change-case": "^5",
"drauu": "^1 || ^0.4",
"focus-trap": "^7 || ^8",
"fuse.js": "^7",
"idb-keyval": "^6",
"jwt-decode": "^4",
"nprogress": "^0.2",
"qrcode": "^1.5",
"sortablejs": "^1",
"universal-cookie": "^7 || ^8",
"vue": "^3.5.0"
},
"peerDependenciesMeta": {
"async-validator": {
"optional": true
},
"axios": {
"optional": true
},
"change-case": {
"optional": true
},
"drauu": {
"optional": true
},
"focus-trap": {
"optional": true
},
"fuse.js": {
"optional": true
},
"idb-keyval": {
"optional": true
},
"jwt-decode": {
"optional": true
},
"nprogress": {
"optional": true
},
"qrcode": {
"optional": true
},
"sortablejs": {
"optional": true
},
"universal-cookie": {
"optional": true
}
}
},
"node_modules/@vueuse/metadata": {
"version": "15.0.0",
"resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-15.0.0.tgz",

View File

@@ -42,6 +42,7 @@
"@floating-ui/vue": "^2.0.0",
"@mdi/font": "7.4.47",
"@vueuse/core": "^15.0.0",
"@vueuse/integrations": "^15.0.0",
"@zxing/browser": "^0.2.0",
"@zxing/library": "^0.23.0",
"axios": "^1.18.1",

View File

@@ -0,0 +1,80 @@
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import mitt, { type Emitter } from "mitt";
import { describe, expect, it, vi } from "vitest";
import type { SimpleRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { rom } from "@/v2/components/Gallery/listRowFixture";
import ShowQRCodeDialog from "./ShowQRCodeDialog.vue";
// Each encode waits for releaseQR() so a test can look between the link
// changing and the new image arriving.
const { toDataURL, releaseQR } = vi.hoisted(() => {
let pending: Array<() => void> = [];
return {
toDataURL: vi.fn(
(text: string) =>
new Promise<string>((resolve) =>
pending.push(() => resolve(`qr:${text}`)),
),
),
releaseQR: () => {
pending.forEach((resolve) => resolve());
pending = [];
},
};
});
vi.mock("vue-i18n");
vi.mock("qrcode", () => ({ default: { toDataURL } }));
vi.mock("@/utils", () => ({
isNintendoDSFile: () => true,
getNintendoDSFiles: () => [],
getDownloadLink: ({ rom }: { rom: SimpleRom }) => `link-${rom.id}`,
}));
function mountDialog(): { wrapper: VueWrapper; emitter: Emitter<Events> } {
const emitter = mitt<Events>();
const wrapper = mount(ShowQRCodeDialog, {
global: {
provide: { emitter },
stubs: {
RDialog: {
props: { modelValue: { type: Boolean, default: false } },
template: '<div v-if="modelValue"><slot name="content" /></div>',
},
},
},
});
return { wrapper, emitter };
}
describe("ShowQRCodeDialog", () => {
it("encodes the ROM's download link", async () => {
const { wrapper, emitter } = mountDialog();
emitter.emit("showQRCodeDialog", rom({ id: 1 }));
await flushPromises();
releaseQR();
await flushPromises();
expect(wrapper.get(".r-v2-qr__code").attributes("src")).toBe("qr:link-1");
});
it("never shows the previous ROM's code while the next one encodes", async () => {
const { wrapper, emitter } = mountDialog();
emitter.emit("showQRCodeDialog", rom({ id: 1 }));
await flushPromises();
releaseQR();
await flushPromises();
emitter.emit("showQRCodeDialog", rom({ id: 2 }));
await flushPromises();
expect(wrapper.find(".r-v2-qr__code").exists()).toBe(false);
releaseQR();
await flushPromises();
expect(wrapper.get(".r-v2-qr__code").attributes("src")).toBe("qr:link-2");
});
});

View File

@@ -1,51 +1,49 @@
<script setup lang="ts">
// ShowQRCodeDialog: emitter-driven QR for downloading a single ROM from a
// handheld/phone. The qrcode library renders into the canvas directly
// after the dialog opens (nextTick so the canvas is in the DOM).
// handheld/phone.
import { RDialog } from "@v2/lib";
import { useQRCode } from "@vueuse/integrations/useQRCode";
import type { Emitter } from "mitt";
import qrcode from "qrcode";
import { inject, nextTick, onBeforeUnmount, ref } from "vue";
import { computed, inject, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { SimpleRom } from "@/stores/roms";
import type { Events } from "@/types/emitter";
import { getNintendoDSFiles, getDownloadLink, isNintendoDSFile } from "@/utils";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { colorCanvas, colorOverlay } from "@/v2/tokens";
defineOptions({ inheritAttrs: false });
const { t } = useI18n();
const { lgAndUp } = useBreakpoint();
const show = ref(false);
const rom = ref<SimpleRom | null>(null);
const emitter = inject<Emitter<Events>>("emitter");
const canvasRef = ref<HTMLCanvasElement | null>(null);
const openHandler = async (romToView: SimpleRom) => {
show.value = true;
rom.value = romToView;
await nextTick();
const isNDSFile = isNintendoDSFile(romToView);
const matchingFiles = getNintendoDSFiles(romToView);
const downloadLink = getDownloadLink({
rom: romToView,
const downloadLink = computed(() => {
if (!rom.value) return "";
const isNDSFile = isNintendoDSFile(rom.value);
const matchingFiles = getNintendoDSFiles(rom.value);
return getDownloadLink({
rom: rom.value,
fileIDs: isNDSFile ? [] : [matchingFiles[0].id],
});
});
if (canvasRef.value) {
qrcode.toCanvas(canvasRef.value, downloadLink, {
margin: 1,
width: lgAndUp.value ? 300 : 220,
color: {
dark: colorCanvas.bgDeep,
light: colorOverlay.emphasisBg,
},
});
}
// Rendered at 2x the largest display size so it stays sharp on HiDPI screens.
const qrCode = useQRCode(downloadLink, {
margin: 1,
width: 600,
color: {
dark: colorCanvas.bgDeep,
light: colorOverlay.emphasisBg,
},
});
// useQRCode keeps the previous image until the new one resolves; drop it so
// the next ROM never briefly shows the last ROM's code.
watch(downloadLink, () => (qrCode.value = ""));
const openHandler = (romToView: SimpleRom) => {
show.value = true;
rom.value = romToView;
};
emitter?.on("showQRCodeDialog", openHandler);
onBeforeUnmount(() => emitter?.off("showQRCodeDialog", openHandler));
@@ -69,8 +67,13 @@ function closeDialog() {
<p v-if="rom" class="r-v2-qr__filename" :title="rom.fs_name">
{{ rom.fs_name }}
</p>
<div class="r-v2-qr__canvas-wrap">
<canvas ref="canvasRef" />
<div class="r-v2-qr__code-wrap">
<img
v-if="qrCode"
:src="qrCode"
:alt="t('rom.qr-scan-to-download')"
class="r-v2-qr__code"
/>
</div>
</div>
</template>
@@ -110,7 +113,10 @@ function closeDialog() {
text-align: center;
}
.r-v2-qr__canvas-wrap {
.r-v2-qr__code-wrap {
box-sizing: content-box;
width: 220px;
height: 220px;
margin: 20px 0px 0px;
padding: 6px;
background: var(--r-color-overlay-emphasis-bg);
@@ -119,4 +125,15 @@ function closeDialog() {
display: grid;
place-items: center;
}
html[data-bp~="lg-and-up"] .r-v2-qr__code-wrap {
width: 300px;
height: 300px;
}
.r-v2-qr__code {
display: block;
width: 100%;
height: 100%;
}
</style>

View File

@@ -14,8 +14,28 @@ const { regenerateToken, pairToken, pollPairStatus, success } = vi.hoisted(
}),
);
// Each encode waits for releaseQR() so a test can look between the code
// changing and the new image arriving.
const { toDataURL, releaseQR } = vi.hoisted(() => {
let pending: Array<() => void> = [];
return {
toDataURL: vi.fn(
(text: string) =>
new Promise<string>((resolve) =>
pending.push(() => resolve(`qr:${text}`)),
),
),
releaseQR: () => {
pending.forEach((resolve) => resolve());
pending = [];
},
};
});
vi.mock("vue-i18n");
vi.mock("qrcode", () => ({ default: { toDataURL } }));
vi.mock("@/services/api/client-token", () => ({
default: { regenerateToken, pairToken, pollPairStatus },
}));
@@ -74,6 +94,11 @@ async function openPairing(expiresIn: number) {
return { wrapper, emitter };
}
function qrSrc(wrapper: Awaited<ReturnType<typeof openPairing>>["wrapper"]) {
const img = wrapper.find(".r-v2-tok-dialog__qr-code");
return img.exists() ? img.attributes("src") : undefined;
}
function counter(wrapper: Awaited<ReturnType<typeof openPairing>>["wrapper"]) {
return wrapper.find(".r-v2-tok-dialog__pair-counter");
}
@@ -129,4 +154,28 @@ describe("CreateClientTokenDialog pairing", () => {
expect(pollPairStatus).not.toHaveBeenCalled();
});
it("encodes the pair URL and never shows an expired code's QR", async () => {
const { wrapper } = await openPairing(3);
releaseQR();
await flushPromises();
expect(qrSrc(wrapper)).toBe(
`qr:${window.location.origin}/pair?code=ABC1-23`,
);
await vi.advanceTimersByTimeAsync(3000);
pairToken.mockResolvedValue({ data: { code: "XYZ789", expires_in: 9 } });
const regenerate = wrapper
.findAll("button")
.find((b) => b.text() === "settings.regenerate-code");
await regenerate!.trigger("click");
await flushPromises();
expect(qrSrc(wrapper)).toBeUndefined();
releaseQR();
await flushPromises();
expect(qrSrc(wrapper)).toBe(
`qr:${window.location.origin}/pair?code=XYZ7-89`,
);
});
});

View File

@@ -19,9 +19,9 @@ import {
RTextField,
} from "@v2/lib";
import { useCountdown } from "@vueuse/core";
import { useQRCode } from "@vueuse/integrations/useQRCode";
import type { Emitter } from "mitt";
import qrcode from "qrcode";
import { computed, inject, nextTick, ref, watch } from "vue";
import { computed, inject, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import clientTokenApi, {
type ClientTokenSchema,
@@ -31,6 +31,7 @@ import type { Events } from "@/types/emitter";
import { useClipboard } from "@/v2/composables/useClipboard";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import RDialog from "@/v2/lib/overlays/RDialog/RDialog.vue";
import { colorOverlay } from "@/v2/tokens";
defineOptions({ inheritAttrs: false });
@@ -155,6 +156,23 @@ const formattedPairCode = computed(() => {
return c ? `${c.slice(0, 4)}-${c.slice(4)}` : "";
});
const pairUrl = computed(() =>
formattedPairCode.value
? `${window.location.origin}/pair?code=${formattedPairCode.value}`
: "",
);
// High error correction leaves room for the logo covering the center.
// Rendered at 2x the largest display size so it stays sharp on HiDPI screens.
const pairQRCode = useQRCode(pairUrl, {
margin: 2,
width: 500,
errorCorrectionLevel: "H",
color: { light: colorOverlay.emphasisBg },
});
// useQRCode keeps the previous image until the new one resolves; drop it so
// a regenerated code never briefly shows the expired one.
watch(pairUrl, () => (pairQRCode.value = ""));
const dialogTitle = computed(() => {
if (step.value === "config") return t("settings.create-new-api-token");
if (step.value === "delivery")
@@ -264,8 +282,6 @@ async function startPairing() {
pairCode.value = data.code;
pairLoading.value = false;
startPairCountdown(data.expires_in);
await nextTick();
renderQR(data.code);
} catch (err) {
pairLoading.value = false;
const e = err as { response?: { data?: { detail?: string } } };
@@ -306,8 +322,6 @@ async function regeneratePairCode() {
pairCode.value = data.code;
pairLoading.value = false;
startPairCountdown(data.expires_in);
await nextTick();
renderQR(data.code);
} catch (err) {
pairLoading.value = false;
const e = err as { response?: { data?: { detail?: string } } };
@@ -318,46 +332,6 @@ async function regeneratePairCode() {
}
}
function renderQR(code: string) {
const displayCode = `${code.slice(0, 4)}-${code.slice(4)}`;
const pairUrl = `${window.location.origin}/pair?code=${displayCode}`;
const canvas = document.getElementById(
"r-v2-pair-qr-code",
) as HTMLCanvasElement | null;
if (!canvas) return;
const isWide = window.innerWidth >= 1280;
const size = isWide ? 250 : 200;
qrcode.toCanvas(
canvas,
pairUrl,
{ margin: 2, width: size, errorCorrectionLevel: "H" },
() => {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const logo = new Image();
logo.src = "/assets/logos/romm_logo_xbox_one_circle.svg";
logo.onload = () => {
const logoSize = canvas.width * 0.24;
const cx = canvas.width / 2;
const cy = canvas.height / 2;
const radius = logoSize / 2 + 4;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.drawImage(
logo,
cx - logoSize / 2,
cy - logoSize / 2,
logoSize,
logoSize,
);
};
},
);
}
function closeDialog() {
stopPairPolling();
show.value = false;
@@ -521,7 +495,20 @@ watch(show, (val) => {
<RProgressCircular indeterminate :size="36" />
</div>
<template v-else-if="pairStatus === 'pending'">
<canvas id="r-v2-pair-qr-code" class="r-v2-tok-dialog__qr" />
<div class="r-v2-tok-dialog__qr">
<template v-if="pairQRCode">
<img
:src="pairQRCode"
:alt="t('settings.pair-device')"
class="r-v2-tok-dialog__qr-code"
/>
<img
src="/assets/logos/romm_logo_xbox_one_circle.svg"
alt=""
class="r-v2-tok-dialog__qr-logo"
/>
</template>
</div>
<div class="r-v2-tok-dialog__pair-code">{{ formattedPairCode }}</div>
<div class="r-v2-tok-dialog__pair-counter">{{ pairCountdown }}s</div>
</template>
@@ -677,9 +664,31 @@ html[data-bp~="xs"] .r-v2-tok-dialog__scopes-grid {
}
.r-v2-tok-dialog__qr {
display: block;
position: relative;
width: 200px;
height: 200px;
margin: 0 auto;
}
html[data-bp~="lg-and-up"] .r-v2-tok-dialog__qr {
width: 250px;
height: 250px;
}
.r-v2-tok-dialog__qr-code {
display: block;
width: 100%;
height: 100%;
}
.r-v2-tok-dialog__qr-logo {
position: absolute;
top: 50%;
left: 50%;
box-sizing: content-box;
width: 24%;
padding: 4px;
border-radius: 50%;
background: var(--r-color-overlay-emphasis-bg);
transform: translate(-50%, -50%);
}
.r-v2-tok-dialog__pair-code {
margin-top: 8px;
font-family: var(--r-font-family-mono, monospace);

View File

@@ -15,7 +15,7 @@ export default defineConfig({
test: {
server: {
deps: {
inline: ["vuetify"],
inline: ["vuetify", "@vueuse/integrations"],
},
},
projects: [