mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
Use VueUse for v2 debounces, intervals, the page title and avatar preview (#5035)
This commit is contained in:
@@ -18,6 +18,7 @@ import storeAuth from "@/stores/auth";
|
||||
import storeHeartbeat from "@/stores/heartbeat";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import type { User } from "@/stores/users";
|
||||
import { DEFAULT_TITLE } from "@/v2/composables/usePageTitle";
|
||||
import {
|
||||
notFoundComponent,
|
||||
v2Layouts,
|
||||
@@ -635,7 +636,7 @@ export function applyRouteTitle(
|
||||
// A query/hash-only navigation leaves the view mounted, so `usePageTitle`
|
||||
// won't refire and the fallback would drop the title it already set.
|
||||
if (from && route.path === from.path) return;
|
||||
document.title = "RomM";
|
||||
document.title = DEFAULT_TITLE;
|
||||
}
|
||||
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
@@ -702,7 +703,7 @@ router.beforeEach(async (to, from, next) => {
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error("Navigation guard error:", error);
|
||||
document.title = "RomM";
|
||||
document.title = DEFAULT_TITLE;
|
||||
next({ name: ROUTES.LOGIN });
|
||||
}
|
||||
});
|
||||
|
||||
61
frontend/src/v2/components/Auth/SetupStepAdmin.test.ts
Normal file
61
frontend/src/v2/components/Auth/SetupStepAdmin.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { defaultAvatarPath } from "@/utils";
|
||||
import SetupStepAdmin, { type AdminUserDraft } from "./SetupStepAdmin.vue";
|
||||
|
||||
vi.mock("vue-i18n");
|
||||
|
||||
function draft(avatar?: File): AdminUserDraft {
|
||||
return { username: "", email: "", password: "", repeatPassword: "", avatar };
|
||||
}
|
||||
|
||||
function mountStep(avatar?: File) {
|
||||
return mount(SetupStepAdmin, {
|
||||
props: { modelValue: draft(avatar) },
|
||||
global: {
|
||||
stubs: {
|
||||
RBtn: true,
|
||||
RForm: { template: "<form><slot /></form>" },
|
||||
RIcon: true,
|
||||
RTextField: true,
|
||||
RTooltip: true,
|
||||
PasswordField: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
describe("SetupStepAdmin avatar preview", () => {
|
||||
let urls = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
urls = 0;
|
||||
vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:${++urls}`);
|
||||
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
it("shows the default avatar until a file is picked", () => {
|
||||
const wrapper = mountStep();
|
||||
|
||||
expect(wrapper.get("img").attributes("src")).toBe(defaultAvatarPath);
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("previews the picked file and revokes each URL it replaces", async () => {
|
||||
const wrapper = mountStep(new File(["a"], "a.png"));
|
||||
expect(wrapper.get("img").attributes("src")).toBe("blob:1");
|
||||
|
||||
await wrapper.setProps({ modelValue: draft(new File(["b"], "b.png")) });
|
||||
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:1");
|
||||
expect(wrapper.get("img").attributes("src")).toBe("blob:2");
|
||||
});
|
||||
|
||||
it("revokes the preview on unmount", () => {
|
||||
const wrapper = mountStep(new File(["a"], "a.png"));
|
||||
|
||||
wrapper.unmount();
|
||||
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:1");
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,8 @@
|
||||
// to Step 1 and back preserves what the user typed). This component is
|
||||
// pure UI: bind props in, emit input/validity out.
|
||||
import { RBtn, RForm, RIcon, RTextField, RTooltip } from "@v2/lib";
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useObjectUrl } from "@vueuse/core";
|
||||
import { computed, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { defaultAvatarPath } from "@/utils";
|
||||
import PasswordField from "@/v2/components/shared/PasswordField.vue";
|
||||
@@ -56,31 +57,8 @@ const repeatPasswordRules = computed(() => [
|
||||
]);
|
||||
|
||||
// ── Avatar picker ──────────────────────────────────────────────────
|
||||
//
|
||||
// Hold the preview URL alongside the File so the user can see what they
|
||||
// picked even after they navigate away from this step and back. We use
|
||||
// an object URL (cheaper than a base64 reader) and revoke it whenever
|
||||
// the file changes or the component unmounts.
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||
const previewUrl = ref<string>("");
|
||||
|
||||
watch(
|
||||
() => draft.value.avatar,
|
||||
(file, prev) => {
|
||||
if (previewUrl.value) {
|
||||
URL.revokeObjectURL(previewUrl.value);
|
||||
previewUrl.value = "";
|
||||
}
|
||||
if (file && file !== prev) {
|
||||
previewUrl.value = URL.createObjectURL(file);
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (previewUrl.value) URL.revokeObjectURL(previewUrl.value);
|
||||
});
|
||||
const previewUrl = useObjectUrl(() => draft.value.avatar);
|
||||
|
||||
const avatarSrc = computed(() => previewUrl.value || defaultAvatarPath);
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
RVirtualScroller,
|
||||
} from "@v2/lib";
|
||||
import {
|
||||
useDebounceFn,
|
||||
useEventListener,
|
||||
useIntersectionObserver,
|
||||
useResizeObserver,
|
||||
@@ -533,7 +534,7 @@ const viewportRange = ref<{ first: number; last: number }>({
|
||||
});
|
||||
function onViewportRangeChange(range: { first: number; last: number }) {
|
||||
viewportRange.value = range;
|
||||
scheduleFetchSync(range);
|
||||
void scheduleFetchSync(range);
|
||||
}
|
||||
|
||||
// Rows kept rendered beyond the viewport. Adaptive so the rendered CARD count
|
||||
@@ -642,8 +643,6 @@ const currentLetter = computed<string>(() => {
|
||||
// `FETCH_DEBOUNCE_MS` do we sync. Both layouts share this one path, so the
|
||||
// list is debounced too (list rows no longer self-fetch on mount).
|
||||
const FETCH_DEBOUNCE_MS = 80;
|
||||
let fetchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pendingRange: { first: number; last: number } | null = null;
|
||||
|
||||
function collectVisiblePositions(range: {
|
||||
first: number;
|
||||
@@ -670,28 +669,14 @@ function syncFetches(range: { first: number; last: number }) {
|
||||
galleryRoms.syncVisibleWindows(collectVisiblePositions(range));
|
||||
}
|
||||
|
||||
function scheduleFetchSync(range: { first: number; last: number }) {
|
||||
pendingRange = range;
|
||||
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
|
||||
fetchDebounceTimer = setTimeout(() => {
|
||||
fetchDebounceTimer = null;
|
||||
if (pendingRange) {
|
||||
syncFetches(pendingRange);
|
||||
pendingRange = null;
|
||||
}
|
||||
}, FETCH_DEBOUNCE_MS);
|
||||
}
|
||||
const scheduleFetchSync = useDebounceFn(syncFetches, FETCH_DEBOUNCE_MS);
|
||||
|
||||
// When the virtualItems list itself changes (gallery context switch,
|
||||
// search invalidate), drop the pending debounced sync. The store's
|
||||
// `invalidateWindows` / `resetGallery` already aborts every in-flight
|
||||
// request, so we just clear local state.
|
||||
watch(virtualItems, () => {
|
||||
if (fetchDebounceTimer) {
|
||||
clearTimeout(fetchDebounceTimer);
|
||||
fetchDebounceTimer = null;
|
||||
}
|
||||
pendingRange = null;
|
||||
scheduleFetchSync.cancel();
|
||||
// Re-sync against the current viewport so visible rows in the new
|
||||
// context start fetching immediately (no debounce: items just
|
||||
// changed, the user is staring at skeletons).
|
||||
@@ -886,7 +871,7 @@ onBeforeUnmount(() => {
|
||||
// navigation back to a non-gallery view (Home, Settings) doesn't
|
||||
// keep stale picks alive.
|
||||
gallerySelection.clear();
|
||||
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
|
||||
scheduleFetchSync.cancel();
|
||||
// When leaving the gallery entirely, stop any in-flight window fetches so
|
||||
// navigating away mid-scroll doesn't keep the network / backend busy.
|
||||
// Keeps the hydrated cache so returning to the same gallery is instant.
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import mitt from "mitt";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ClientTokenSchema } from "@/__generated__";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import CreateClientTokenDialog from "./CreateClientTokenDialog.vue";
|
||||
|
||||
const { regenerateToken, pairToken, pollPairStatus, success } = vi.hoisted(
|
||||
() => ({
|
||||
regenerateToken: vi.fn(),
|
||||
pairToken: vi.fn(),
|
||||
pollPairStatus: vi.fn(),
|
||||
success: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("vue-i18n");
|
||||
|
||||
vi.mock("@/services/api/client-token", () => ({
|
||||
default: { regenerateToken, pairToken, pollPairStatus },
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useSnackbar", () => ({
|
||||
useSnackbar: () => ({ success, error: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@/v2/composables/useClipboard", () => ({
|
||||
useClipboard: () => ({ copy: vi.fn() }),
|
||||
}));
|
||||
|
||||
const token: ClientTokenSchema = {
|
||||
id: 5,
|
||||
name: "Deck",
|
||||
scopes: [],
|
||||
expires_at: null,
|
||||
last_used_at: null,
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
user_id: 1,
|
||||
};
|
||||
|
||||
async function openPairing(expiresIn: number) {
|
||||
pairToken.mockResolvedValue({
|
||||
data: { code: "ABC123", expires_in: expiresIn },
|
||||
});
|
||||
const emitter = mitt<Events>();
|
||||
const wrapper = mount(CreateClientTokenDialog, {
|
||||
global: {
|
||||
provide: { emitter },
|
||||
stubs: {
|
||||
RDialog: {
|
||||
props: { modelValue: { type: Boolean, default: false } },
|
||||
template:
|
||||
'<div v-if="modelValue"><slot name="content" /><slot name="footer" /></div>',
|
||||
},
|
||||
RBtn: {
|
||||
emits: ["click"],
|
||||
template: "<button @click=\"$emit('click')\"><slot /></button>",
|
||||
},
|
||||
RCheckbox: true,
|
||||
RIcon: true,
|
||||
RProgressCircular: true,
|
||||
RSelect: true,
|
||||
RTextField: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
emitter.emit("showRegenerateClientTokenDialog", token);
|
||||
await flushPromises();
|
||||
const pair = wrapper
|
||||
.findAll("button")
|
||||
.find((b) => b.text() === "settings.pair-device");
|
||||
await pair!.trigger("click");
|
||||
await flushPromises();
|
||||
return { wrapper, emitter };
|
||||
}
|
||||
|
||||
function counter(wrapper: Awaited<ReturnType<typeof openPairing>>["wrapper"]) {
|
||||
return wrapper.find(".r-v2-tok-dialog__pair-counter");
|
||||
}
|
||||
|
||||
describe("CreateClientTokenDialog pairing", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
regenerateToken.mockResolvedValue({ data: { id: 5, raw_token: "rmm_x" } });
|
||||
pollPairStatus.mockResolvedValue({ data: {} });
|
||||
});
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("counts down, polling every third second, then expires", async () => {
|
||||
const { wrapper } = await openPairing(6);
|
||||
expect(counter(wrapper).text()).toBe("6s");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(counter(wrapper).text()).toBe("5s");
|
||||
expect(pollPairStatus).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(pollPairStatus).toHaveBeenCalledExactlyOnceWith("ABC123");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(pollPairStatus).toHaveBeenCalledOnce();
|
||||
expect(counter(wrapper).exists()).toBe(false);
|
||||
expect(wrapper.text()).toContain("settings.client-token-pair-expired");
|
||||
});
|
||||
|
||||
// The poll answers 4xx once the device has claimed the code.
|
||||
it("reports the claim and stops when the poll is refused", async () => {
|
||||
pollPairStatus.mockRejectedValue(new Error("gone"));
|
||||
const { wrapper } = await openPairing(9);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(success).toHaveBeenCalledWith(
|
||||
"settings.client-token-pair-claimed",
|
||||
expect.anything(),
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
expect(pollPairStatus).toHaveBeenCalledOnce();
|
||||
expect(wrapper.text()).not.toContain("settings.client-token-pair-expired");
|
||||
});
|
||||
|
||||
it("stops polling once the dialog closes", async () => {
|
||||
const { wrapper } = await openPairing(9);
|
||||
|
||||
const close = wrapper
|
||||
.findAll("button")
|
||||
.find((b) => b.text() === "common.close");
|
||||
await close!.trigger("click");
|
||||
await vi.advanceTimersByTimeAsync(9000);
|
||||
|
||||
expect(pollPairStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -18,9 +18,10 @@ import {
|
||||
RSelect,
|
||||
RTextField,
|
||||
} from "@v2/lib";
|
||||
import { useCountdown } from "@vueuse/core";
|
||||
import type { Emitter } from "mitt";
|
||||
import qrcode from "qrcode";
|
||||
import { computed, inject, nextTick, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { computed, inject, nextTick, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import clientTokenApi, {
|
||||
type ClientTokenSchema,
|
||||
@@ -55,10 +56,17 @@ const rawToken = ref("");
|
||||
const tokenId = ref<number | null>(null);
|
||||
|
||||
const pairCode = ref("");
|
||||
const pairCountdown = ref(0);
|
||||
const pairStatus = ref<PairStatus>("pending");
|
||||
const pairLoading = ref(false);
|
||||
let pairTimer: ReturnType<typeof setInterval> | null = null;
|
||||
const {
|
||||
remaining: pairCountdown,
|
||||
start: startPairCountdown,
|
||||
pause: stopPairPolling,
|
||||
stop: resetPairCountdown,
|
||||
} = useCountdown(0, {
|
||||
onTick: pollPairStatus,
|
||||
onComplete: () => (pairStatus.value = "expired"),
|
||||
});
|
||||
|
||||
const regenerateToken = ref<ClientTokenSchema | null>(null);
|
||||
const isRegenerate = computed(() => regenerateToken.value !== null);
|
||||
@@ -183,17 +191,9 @@ function resetDialog() {
|
||||
tokenId.value = null;
|
||||
pairCode.value = "";
|
||||
pairStatus.value = "pending";
|
||||
pairCountdown.value = 0;
|
||||
loading.value = false;
|
||||
pairLoading.value = false;
|
||||
clearPairTimer();
|
||||
}
|
||||
|
||||
function clearPairTimer() {
|
||||
if (pairTimer) {
|
||||
clearInterval(pairTimer);
|
||||
pairTimer = null;
|
||||
}
|
||||
resetPairCountdown();
|
||||
}
|
||||
|
||||
async function createToken() {
|
||||
@@ -262,11 +262,10 @@ async function startPairing() {
|
||||
try {
|
||||
const { data } = await clientTokenApi.pairToken(tokenId.value);
|
||||
pairCode.value = data.code;
|
||||
pairCountdown.value = data.expires_in;
|
||||
pairLoading.value = false;
|
||||
startPairCountdown(data.expires_in);
|
||||
await nextTick();
|
||||
renderQR(data.code);
|
||||
startPairPolling();
|
||||
} catch (err) {
|
||||
pairLoading.value = false;
|
||||
const e = err as { response?: { data?: { detail?: string } } };
|
||||
@@ -279,33 +278,23 @@ async function startPairing() {
|
||||
}
|
||||
}
|
||||
|
||||
function startPairPolling() {
|
||||
clearPairTimer();
|
||||
pairTimer = setInterval(async () => {
|
||||
pairCountdown.value -= 1;
|
||||
if (pairCountdown.value <= 0) {
|
||||
clearPairTimer();
|
||||
async function pollPairStatus() {
|
||||
if (pairCountdown.value <= 0 || pairCountdown.value % 3 !== 0) return;
|
||||
try {
|
||||
await clientTokenApi.pollPairStatus(pairCode.value);
|
||||
} catch {
|
||||
// The poll throws when the code has been claimed (4xx); treat
|
||||
// it as "claimed" if there's still time, "expired" otherwise.
|
||||
stopPairPolling();
|
||||
if (pairCountdown.value > 0) {
|
||||
pairStatus.value = "claimed";
|
||||
snackbar.success(t("settings.client-token-pair-claimed"), {
|
||||
icon: "mdi-check-bold",
|
||||
});
|
||||
} else {
|
||||
pairStatus.value = "expired";
|
||||
return;
|
||||
}
|
||||
if (pairCountdown.value % 3 === 0) {
|
||||
try {
|
||||
await clientTokenApi.pollPairStatus(pairCode.value);
|
||||
} catch {
|
||||
// The poll throws when the code has been claimed (4xx); treat
|
||||
// it as "claimed" if there's still time, "expired" otherwise.
|
||||
clearPairTimer();
|
||||
if (pairCountdown.value > 0) {
|
||||
pairStatus.value = "claimed";
|
||||
snackbar.success(t("settings.client-token-pair-claimed"), {
|
||||
icon: "mdi-check-bold",
|
||||
});
|
||||
} else {
|
||||
pairStatus.value = "expired";
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
async function regeneratePairCode() {
|
||||
@@ -315,11 +304,10 @@ async function regeneratePairCode() {
|
||||
try {
|
||||
const { data } = await clientTokenApi.pairToken(tokenId.value);
|
||||
pairCode.value = data.code;
|
||||
pairCountdown.value = data.expires_in;
|
||||
pairLoading.value = false;
|
||||
startPairCountdown(data.expires_in);
|
||||
await nextTick();
|
||||
renderQR(data.code);
|
||||
startPairPolling();
|
||||
} catch (err) {
|
||||
pairLoading.value = false;
|
||||
const e = err as { response?: { data?: { detail?: string } } };
|
||||
@@ -371,16 +359,12 @@ function renderQR(code: string) {
|
||||
}
|
||||
|
||||
function closeDialog() {
|
||||
clearPairTimer();
|
||||
stopPairPolling();
|
||||
show.value = false;
|
||||
}
|
||||
|
||||
watch(show, (val) => {
|
||||
if (!val) clearPairTimer();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearPairTimer();
|
||||
if (!val) stopPairPolling();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { nextTick } from "vue";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import { serverError } from "@/test-utils/serverError";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
import storeGallerySelection from "@/v2/stores/gallerySelection";
|
||||
import MissingGamesSection from "./MissingGamesSection.vue";
|
||||
|
||||
@@ -149,4 +150,40 @@ describe("MissingGamesSection", () => {
|
||||
wrapper.findComponent({ name: "SelectionBar" }).props("hideDownload"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
describe("viewport fetches", () => {
|
||||
const range = { first: 0, last: 0 };
|
||||
|
||||
async function mountScrolled() {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
const sync = vi.spyOn(storeGalleryRoms(), "syncVisibleWindows");
|
||||
const wrapper = mountSection();
|
||||
await flushPromises();
|
||||
sync.mockClear();
|
||||
const scroller = wrapper.findComponent({ name: "RVirtualScroller" });
|
||||
scroller.vm.$emit("update:viewport-range", range);
|
||||
scroller.vm.$emit("update:viewport-range", range);
|
||||
return { wrapper, sync };
|
||||
}
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("syncs once the scroller settles", async () => {
|
||||
const { sync } = await mountScrolled();
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(80);
|
||||
|
||||
expect(sync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("drops a pending sync on unmount", async () => {
|
||||
const { wrapper, sync } = await mountScrolled();
|
||||
|
||||
wrapper.unmount();
|
||||
vi.advanceTimersByTime(80);
|
||||
|
||||
expect(sync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
RTag,
|
||||
RVirtualScroller,
|
||||
} from "@v2/lib";
|
||||
import { useDebounceFn } from "@vueuse/core";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -226,7 +227,6 @@ function onListSort({ key, dir }: { key: ListSortKey; dir: "asc" | "desc" }) {
|
||||
// row's `getRomAt(position)` stays null and the list shows skeletons
|
||||
// forever. Mirrors GalleryShell's debounced sync + re-sync-on-items-change.
|
||||
const FETCH_DEBOUNCE_MS = 80;
|
||||
let fetchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const viewportRange = ref<{ first: number; last: number }>({
|
||||
first: 0,
|
||||
last: -1,
|
||||
@@ -250,13 +250,11 @@ function syncFetches(range: { first: number; last: number }) {
|
||||
galleryRoms.syncVisibleWindows(collectVisiblePositions(range));
|
||||
}
|
||||
|
||||
const scheduleFetchSync = useDebounceFn(syncFetches, FETCH_DEBOUNCE_MS);
|
||||
|
||||
function onViewportRange(range: { first: number; last: number }) {
|
||||
viewportRange.value = range;
|
||||
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
|
||||
fetchDebounceTimer = setTimeout(() => {
|
||||
fetchDebounceTimer = null;
|
||||
syncFetches(range);
|
||||
}, FETCH_DEBOUNCE_MS);
|
||||
void scheduleFetchSync(range);
|
||||
}
|
||||
|
||||
// Metadata resolving flips `virtualItems` from skeleton placeholders to
|
||||
@@ -265,10 +263,7 @@ function onViewportRange(range: { first: number; last: number }) {
|
||||
// immediately against the current viewport so the first window loads.
|
||||
watch(virtualItems, () => {
|
||||
listExpansion.collapse();
|
||||
if (fetchDebounceTimer) {
|
||||
clearTimeout(fetchDebounceTimer);
|
||||
fetchDebounceTimer = null;
|
||||
}
|
||||
scheduleFetchSync.cancel();
|
||||
syncFetches(viewportRange.value);
|
||||
});
|
||||
|
||||
@@ -323,7 +318,7 @@ onMounted(() => {
|
||||
onBeforeUnmount(() => {
|
||||
// A press still in flight would otherwise fire into the next surface.
|
||||
useGallerySelectionInput().cancel();
|
||||
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
|
||||
scheduleFetchSync.cancel();
|
||||
galleryFilter.setFilterMissing(prevFilterMissing);
|
||||
galleryFilter.setSelectedFilterPlatforms(prevSelectedPlatforms);
|
||||
galleryRoms.resetGallery();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { CleanupTaskStatusResponse } from "@/__generated__/models/CleanupTaskStatusResponse";
|
||||
import type { TaskInfo } from "@/__generated__/models/TaskInfo";
|
||||
import TasksSection from "./TasksSection.vue";
|
||||
@@ -99,6 +99,8 @@ describe("TasksSection", () => {
|
||||
confirm.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("runs a destructive task only once its typed confirmation passes", async () => {
|
||||
getTasks.mockResolvedValue({
|
||||
data: {
|
||||
@@ -202,6 +204,19 @@ describe("TasksSection", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("polls the status every five seconds until unmounted", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
const wrapper = await mountSection();
|
||||
getTaskStatus.mockClear();
|
||||
|
||||
vi.advanceTimersByTime(10_000);
|
||||
expect(getTaskStatus).toHaveBeenCalledTimes(2);
|
||||
|
||||
wrapper.unmount();
|
||||
vi.advanceTimersByTime(10_000);
|
||||
expect(getTaskStatus).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("describes a scheduled task's cron expression in words", async () => {
|
||||
getTasks.mockResolvedValue({
|
||||
data: { watcher: [], scheduled: [SCHEDULED_TASK], manual: [] },
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
// history feed updates in real time. Manual + scheduled tasks expose a
|
||||
// run button that posts to /tasks/{name}/run.
|
||||
import { RBtn, RIcon, RSpinner } from "@v2/lib";
|
||||
import { useIntervalFn } from "@vueuse/core";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { TaskInfo } from "@/__generated__";
|
||||
import taskApi from "@/services/api/task";
|
||||
@@ -116,19 +117,12 @@ async function fetchTaskStatus() {
|
||||
}
|
||||
}
|
||||
|
||||
let refreshInterval: number | null = null;
|
||||
|
||||
onMounted(() => {
|
||||
void tasksStore.fetchTasks();
|
||||
void fetchTaskStatus();
|
||||
refreshInterval = window.setInterval(() => {
|
||||
void fetchTaskStatus();
|
||||
}, 5000);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (refreshInterval) clearInterval(refreshInterval);
|
||||
});
|
||||
useIntervalFn(() => void fetchTaskStatus(), 5000);
|
||||
|
||||
function statusInfo(task: TaskStatusResponse) {
|
||||
return TaskStatusItem[task.status] ?? TaskStatusItem.queued;
|
||||
|
||||
30
frontend/src/v2/composables/usePageTitle/index.test.ts
Normal file
30
frontend/src/v2/composables/usePageTitle/index.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { effectScope, nextTick, ref } from "vue";
|
||||
import { usePageTitle } from "./index";
|
||||
|
||||
describe("usePageTitle", () => {
|
||||
beforeEach(() => {
|
||||
document.title = "Route title";
|
||||
});
|
||||
|
||||
it("follows the source, falling back to RomM while it is empty", async () => {
|
||||
const name = ref<string | null>(null);
|
||||
effectScope().run(() => usePageTitle(() => name.value));
|
||||
expect(document.title).toBe("RomM");
|
||||
|
||||
name.value = "Chrono Trigger";
|
||||
await nextTick();
|
||||
expect(document.title).toBe("Chrono Trigger");
|
||||
});
|
||||
|
||||
// The router has already titled the next route when the old view unmounts.
|
||||
it("leaves the title alone when its scope ends", () => {
|
||||
const scope = effectScope();
|
||||
scope.run(() => usePageTitle(() => "Chrono Trigger"));
|
||||
document.title = "Next route";
|
||||
|
||||
scope.stop();
|
||||
|
||||
expect(document.title).toBe("Next route");
|
||||
});
|
||||
});
|
||||
@@ -7,16 +7,10 @@
|
||||
//
|
||||
// The title is deliberately not restored on unmount: the router guard has
|
||||
// already set the next route's title by the time a view tears down.
|
||||
import { watch } from "vue";
|
||||
import { useTitle } from "@vueuse/core";
|
||||
|
||||
const DEFAULT_TITLE = "RomM";
|
||||
export const DEFAULT_TITLE = "RomM";
|
||||
|
||||
export function usePageTitle(source: () => string | null | undefined) {
|
||||
watch(
|
||||
source,
|
||||
(title) => {
|
||||
document.title = title || DEFAULT_TITLE;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
useTitle(() => source() || DEFAULT_TITLE, { restoreOnUnmount: false });
|
||||
}
|
||||
|
||||
84
frontend/src/v2/views/DevicePair.test.ts
Normal file
84
frontend/src/v2/views/DevicePair.test.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import DevicePair from "./DevicePair.vue";
|
||||
|
||||
const { getPending, approve } = vi.hoisted(() => ({
|
||||
getPending: vi.fn(),
|
||||
approve: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("vue-i18n");
|
||||
|
||||
vi.mock("vue-router", () => ({
|
||||
useRoute: () => ({ query: { user_code: "ABCD-1234" } }),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/device-auth", () => ({
|
||||
default: { getPending, approve, deny: vi.fn() },
|
||||
}));
|
||||
|
||||
async function mountApproved() {
|
||||
const wrapper = mount(DevicePair, {
|
||||
global: {
|
||||
stubs: {
|
||||
RBtn: {
|
||||
emits: ["click"],
|
||||
template: "<button @click=\"$emit('click')\"><slot /></button>",
|
||||
},
|
||||
RChip: true,
|
||||
RIcon: true,
|
||||
RSelect: true,
|
||||
RSpinner: true,
|
||||
RTextField: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
await wrapper.findAll("button")[1].trigger("click");
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
describe("DevicePair auto-close", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
vi.spyOn(window, "close").mockImplementation(() => undefined);
|
||||
getPending.mockResolvedValue({
|
||||
data: {
|
||||
client_device_identifier: "dev-1",
|
||||
name: "Steam Deck",
|
||||
client: "argosy",
|
||||
platform: null,
|
||||
client_version: null,
|
||||
requested_scopes: ["roms.read"],
|
||||
allowed_scopes: ["roms.read"],
|
||||
expires_at: "2030-01-01T00:00:00Z",
|
||||
},
|
||||
});
|
||||
approve.mockResolvedValue({ data: {} });
|
||||
});
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("counts down and closes the window once approved", async () => {
|
||||
const wrapper = await mountApproved();
|
||||
expect(approve).toHaveBeenCalledOnce();
|
||||
expect(wrapper.find(".r-v2-devpair__hint").exists()).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(window.close).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(window.close).toHaveBeenCalledOnce();
|
||||
expect(wrapper.find(".r-v2-devpair__hint").exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("stops counting once unmounted", async () => {
|
||||
const wrapper = await mountApproved();
|
||||
|
||||
wrapper.unmount();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
|
||||
expect(window.close).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -9,8 +9,9 @@
|
||||
* AuthLayout-style chrome and the `.r-v2` token scope.
|
||||
*/
|
||||
import { RBtn, RChip, RIcon, RSelect, RSpinner, RTextField } from "@v2/lib";
|
||||
import { useCountdown } from "@vueuse/core";
|
||||
import type { AxiosError } from "axios";
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute } from "vue-router";
|
||||
import deviceAuthApi, {
|
||||
@@ -86,29 +87,10 @@ onMounted(async () => {
|
||||
});
|
||||
|
||||
const AUTO_CLOSE_SECONDS = 3;
|
||||
const closeCountdown = ref<number>(AUTO_CLOSE_SECONDS);
|
||||
const closeIntervalId = ref<number | null>(null);
|
||||
|
||||
function scheduleAutoClose() {
|
||||
closeCountdown.value = AUTO_CLOSE_SECONDS;
|
||||
closeIntervalId.value = window.setInterval(() => {
|
||||
closeCountdown.value -= 1;
|
||||
if (closeCountdown.value <= 0) {
|
||||
if (closeIntervalId.value !== null) {
|
||||
window.clearInterval(closeIntervalId.value);
|
||||
closeIntervalId.value = null;
|
||||
}
|
||||
window.close();
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (closeIntervalId.value !== null) {
|
||||
window.clearInterval(closeIntervalId.value);
|
||||
closeIntervalId.value = null;
|
||||
}
|
||||
});
|
||||
const { remaining: closeCountdown, start: scheduleAutoClose } = useCountdown(
|
||||
AUTO_CLOSE_SECONDS,
|
||||
{ onComplete: () => window.close() },
|
||||
);
|
||||
|
||||
async function approve() {
|
||||
if (!pending.value || selectedScopes.value.length === 0) return;
|
||||
|
||||
Reference in New Issue
Block a user