mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 10:32:57 +01:00
review(pr-ready step 2): harden select-all against races and bad contexts
Code-review pass fixes: a re-triggered select-all re-arms the pending epoch instead of no-opping; the loaded-only fallback waits for the metadata bootstrap; deselections made during the fetch survive the merge; fetches are refused off the gallery view and on empty results; the Missing tab clears the selection on unmount; Esc cancels an in-flight select-all even before anything is selected; hot-path scans short-circuit on count and read through toRaw; the sidecar-skip flags and page size get one home; failures reach the console. Six new tests pin the races. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ldi4YaXJWDDmFdbKfQay8L
This commit is contained in:
@@ -783,7 +783,7 @@ onBeforeRouteLeave((_to, from) => {
|
||||
|
||||
// Whole-result select-all, shared with the SelectionBar button and
|
||||
// the list header checkbox.
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
const { selectAll, selectingAll } = useGallerySelectAll();
|
||||
|
||||
// Global hotkeys scoped to the gallery shell — Esc clears the
|
||||
// selection, Ctrl/Cmd+A selects the whole filtered result. Both are
|
||||
@@ -800,14 +800,17 @@ function onShellKey(e: KeyboardEvent) {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape" && gallerySelection.enabled) {
|
||||
// `selectingAll` keeps Esc working while a whole-result fetch is
|
||||
// still in flight with nothing selected yet (clear() abandons it).
|
||||
if (e.key === "Escape" && (gallerySelection.enabled || selectingAll.value)) {
|
||||
e.preventDefault();
|
||||
gallerySelection.clear();
|
||||
return;
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === "a" || e.key === "A")) {
|
||||
e.preventDefault();
|
||||
void selectAll();
|
||||
// A held chord repeats keydown at the OS rate; one trigger is enough.
|
||||
if (!e.repeat) void selectAll();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,11 +90,8 @@ function handleClick(col: ListColumn) {
|
||||
<template>
|
||||
<div class="game-list-header" :style="gridStyle" role="row">
|
||||
<template v-for="col in columns" :key="String(col.key)">
|
||||
<!-- Select-all column. Tri-state checkbox: off → some → all,
|
||||
judged against the whole filtered result. RCheckbox draws
|
||||
the dash glyph for the indeterminate state and the tick for
|
||||
"all", so we just pipe the derived state through and
|
||||
intercept the click. -->
|
||||
<!-- Tri-state select-all checkbox (off → some → all), judged
|
||||
against the whole filtered result. -->
|
||||
<RCheckbox
|
||||
v-if="col.key === 'select'"
|
||||
class="game-list-header__check"
|
||||
|
||||
@@ -84,7 +84,7 @@ const { ensureFavoriteCollection } = useFavoriteToggle();
|
||||
const { syncCachedRom, removeCachedRoms, refreshAfterUserStateChange } =
|
||||
useRomSync();
|
||||
// Whole-result select-all, shared with the list header checkbox and
|
||||
// Ctrl/Cmd+A. In grid mode this button is the only visible affordance.
|
||||
// Ctrl/Cmd+A.
|
||||
const { selectingAll, allSelected, selectAll } = useGallerySelectAll();
|
||||
|
||||
// The filtered-result size, so the label says how many "all" is. Falls
|
||||
@@ -326,10 +326,8 @@ function clear() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Select all: extends the selection to the whole filtered
|
||||
result (not just the loaded windows). Sits by the count so
|
||||
both read as "selection scope"; the sole grid-mode
|
||||
affordance (the list header has its own checkbox). -->
|
||||
<!-- Extends the selection to the whole filtered result; the
|
||||
sole grid-mode affordance (list mode has the header checkbox). -->
|
||||
<RTooltip :text="selectAllLabel">
|
||||
<template #activator="{ props: tipProps }">
|
||||
<RBtn
|
||||
|
||||
@@ -43,6 +43,7 @@ import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useTaskCompletion } from "@/v2/composables/useTaskCompletion";
|
||||
import { useWebpSupport } from "@/v2/composables/useWebpSupport";
|
||||
import storeGalleryRoms, { type SidecarOptions } from "@/v2/stores/galleryRoms";
|
||||
import storeGallerySelection from "@/v2/stores/gallerySelection";
|
||||
|
||||
interface PlatformItem {
|
||||
id: number;
|
||||
@@ -278,6 +279,9 @@ onBeforeUnmount(() => {
|
||||
galleryFilter.setFilterMissing(prevFilterMissing);
|
||||
galleryFilter.setSelectedFilterPlatforms(prevSelectedPlatforms);
|
||||
galleryRoms.resetGallery();
|
||||
// Selection is surface-scoped: drop it so the next gallery's
|
||||
// SelectionBar doesn't resurface picks made on this tab.
|
||||
storeGallerySelection().clear();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { flushPromises } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
import { useGallerySelectAll } from "@/v2/composables/useGallerySelectAll";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
import storeGalleryRoms, {
|
||||
SELECT_ALL_PAGE_SIZE,
|
||||
} from "@/v2/stores/galleryRoms";
|
||||
import storeGallerySelection from "@/v2/stores/gallerySelection";
|
||||
|
||||
const { getRoms, snackbarError } = vi.hoisted(() => ({
|
||||
@@ -51,14 +53,27 @@ function deferred(): Deferred {
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
// A gallery context is required for the whole-result fetch; Search is
|
||||
// the lightest one to fake.
|
||||
function galleryContext() {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
galleryRoms.currentSearch = true;
|
||||
return galleryRoms;
|
||||
}
|
||||
|
||||
describe("useGallerySelectAll", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Un-stub the console.error spy from the failure-path test.
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("selects the whole filtered result, not just the loaded windows", async () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2, 3, 4];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
@@ -73,7 +88,7 @@ describe("useGallerySelectAll", () => {
|
||||
// One whole-result request, sidecar aggregations off.
|
||||
expect(getRoms).toHaveBeenCalledTimes(1);
|
||||
expect(getRoms.mock.calls[0][0]).toMatchObject({
|
||||
limit: 10_000,
|
||||
limit: SELECT_ALL_PAGE_SIZE,
|
||||
offset: 0,
|
||||
withCharIndex: false,
|
||||
withFilterValues: false,
|
||||
@@ -83,7 +98,7 @@ describe("useGallerySelectAll", () => {
|
||||
});
|
||||
|
||||
it("merges the loaded roms before the whole-result fetch resolves", async () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2, 3];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
@@ -99,8 +114,24 @@ describe("useGallerySelectAll", () => {
|
||||
expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("fetches the whole result while the bootstrap is still pending", async () => {
|
||||
// Loaded windows can resolve before the metadata bootstrap fills
|
||||
// `romIdIndex`; select-all must not mistake them for full coverage.
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
galleryRoms.byPosition.set(1, rom(2));
|
||||
getRoms.mockResolvedValue(resultPage([rom(1), rom(2), rom(3), rom(4)]));
|
||||
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
await selectAll();
|
||||
|
||||
expect(getRoms).toHaveBeenCalledTimes(1);
|
||||
expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it("skips the fetch when the whole result is already selected", async () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
@@ -115,7 +146,7 @@ describe("useGallerySelectAll", () => {
|
||||
});
|
||||
|
||||
it("drops a late result when the selection was cleared mid-fetch", async () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
@@ -131,9 +162,51 @@ describe("useGallerySelectAll", () => {
|
||||
expect(selection.count).toBe(0);
|
||||
});
|
||||
|
||||
it("re-arms the running fetch when re-triggered after a clear", async () => {
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2, 3];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
const d = deferred();
|
||||
getRoms.mockReturnValue(d.promise);
|
||||
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
const first = selectAll();
|
||||
selection.clear();
|
||||
// The re-trigger must not need a second fetch: the in-flight one is
|
||||
// revalidated for the fresh intent.
|
||||
const second = selectAll();
|
||||
d.resolve(resultPage([rom(1), rom(2), rom(3)]));
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(getRoms).toHaveBeenCalledTimes(1);
|
||||
expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("keeps a rom deselected during the fetch out of the merge", async () => {
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2, 3];
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
galleryRoms.byPosition.set(1, rom(2));
|
||||
const d = deferred();
|
||||
getRoms.mockReturnValue(d.promise);
|
||||
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
const done = selectAll();
|
||||
selection.toggle(rom(1), 0);
|
||||
d.resolve(resultPage([rom(1), rom(2), rom(3)]));
|
||||
await done;
|
||||
|
||||
expect(selection.ids.sort((a, b) => a - b)).toEqual([2, 3]);
|
||||
});
|
||||
|
||||
it("falls back to loaded-only coverage without a rom id index", async () => {
|
||||
// Surfaces that opt out of the sidecar (Settings "Missing" tab)
|
||||
// finish the bootstrap with an empty index.
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.metadataLoaded = true;
|
||||
galleryRoms.byPosition.set(0, rom(1));
|
||||
galleryRoms.byPosition.set(1, rom(2));
|
||||
|
||||
@@ -147,8 +220,33 @@ describe("useGallerySelectAll", () => {
|
||||
expect(allSelected.value).toBe(true);
|
||||
});
|
||||
|
||||
it("surfaces a snackbar when the whole-result fetch fails", async () => {
|
||||
it("stays loaded-only on opt-out surfaces even before any window lands", async () => {
|
||||
// Like the Missing tab: no gallery context, bootstrap resolved with
|
||||
// no id index, rows still skeletons.
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
galleryRoms.metadataLoaded = true;
|
||||
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
await selectAll();
|
||||
|
||||
expect(getRoms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does nothing on an empty filtered result", async () => {
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.metadataLoaded = true;
|
||||
|
||||
const { selectAll } = useGallerySelectAll();
|
||||
await selectAll();
|
||||
|
||||
expect(getRoms).not.toHaveBeenCalled();
|
||||
expect(selection.count).toBe(0);
|
||||
});
|
||||
|
||||
it("surfaces a snackbar when the whole-result fetch fails", async () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const galleryRoms = galleryContext();
|
||||
galleryRoms.romIdIndex = [1, 2];
|
||||
getRoms.mockRejectedValue(new Error("boom"));
|
||||
|
||||
@@ -163,7 +261,7 @@ describe("useGallerySelectAll", () => {
|
||||
});
|
||||
|
||||
it("reports tri-state coverage for the header checkbox", () => {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
const galleryRoms = galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
galleryRoms.romIdIndex = [1, 2];
|
||||
|
||||
@@ -176,4 +274,13 @@ describe("useGallerySelectAll", () => {
|
||||
selection.selectMany([rom(2)]);
|
||||
expect(selectionState.value).toBe("all");
|
||||
});
|
||||
|
||||
it("reports off over an empty result despite out-of-filter picks", () => {
|
||||
galleryContext();
|
||||
const selection = storeGallerySelection();
|
||||
selection.selectMany([rom(9)]);
|
||||
|
||||
const { selectionState } = useGallerySelectAll();
|
||||
expect(selectionState.value).toBe("off");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
// useGallerySelectAll: whole-result "select all" shared by the
|
||||
// SelectionBar button, the list header checkbox and the shell's
|
||||
// Ctrl/Cmd+A. It selects the entire filtered result, not just the
|
||||
// loaded windows: loaded ROMs apply instantly, then the rest of the
|
||||
// result set is fetched (the selection store keeps full SimpleRoms so
|
||||
// bulk actions keep working) and merged when it lands.
|
||||
//
|
||||
// Coverage is judged against `romIdIndex`, the full ordered id list of
|
||||
// the current filtered result that the gallery bootstrap already
|
||||
// fetches for virtual scrolling. Surfaces that opt out of that sidecar
|
||||
// (Settings "Missing" tab) fall back to loaded-only coverage, where the
|
||||
// instant merge already satisfies `allSelected` and no fetch happens.
|
||||
import { computed, ref } from "vue";
|
||||
// Whole-result "select all" shared by the SelectionBar button, the
|
||||
// list header checkbox and the shell's Ctrl/Cmd+A: loaded ROMs merge
|
||||
// instantly, then the rest of the filtered result is fetched and
|
||||
// merged. Surfaces with no rom id index after bootstrap stay loaded-only.
|
||||
import { computed, ref, toRaw } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
@@ -21,6 +13,12 @@ export type GallerySelectionState = "off" | "some" | "all";
|
||||
// Module-level so every call site shares one in-flight flag: a second
|
||||
// trigger while a fetch runs is a no-op, not a second fetch.
|
||||
const selectingAll = ref(false);
|
||||
// Selection epoch the in-flight fetch may merge against. Re-armed by
|
||||
// every trigger, so a select-all after a clear reuses the running fetch.
|
||||
let pendingEpoch = 0;
|
||||
// Ids selected when the last trigger fired: a ROM deselected while the
|
||||
// fetch runs stays deselected when the late result merges.
|
||||
let selectedAtDispatch = new Set<number>();
|
||||
|
||||
export function useGallerySelectAll() {
|
||||
const galleryRoms = storeGalleryRoms();
|
||||
@@ -28,18 +26,25 @@ export function useGallerySelectAll() {
|
||||
const snackbar = useSnackbar();
|
||||
const { t } = useI18n();
|
||||
|
||||
/** True when every ROM of the filtered result is selected. Selected
|
||||
* ROMs outside the current filter (kept across an in-view filter
|
||||
* change) don't count against it. */
|
||||
/** True when every ROM of the filtered result is selected; picks
|
||||
* outside the current filter don't count against it. */
|
||||
const allSelected = computed<boolean>(() => {
|
||||
const ids = galleryRoms.romIdIndex;
|
||||
// Raw reads: the selection Map and the id index are only ever
|
||||
// replaced wholesale, so the property-level deps suffice and
|
||||
// per-entry tracking would allocate one dep per rom per scan.
|
||||
const selected = toRaw(selection.selected);
|
||||
const ids = toRaw(galleryRoms.romIdIndex);
|
||||
if (ids.length > 0) {
|
||||
return ids.every((id) => selection.selected.has(id));
|
||||
if (selection.count < ids.length) return false;
|
||||
return ids.every((id) => selected.has(id));
|
||||
}
|
||||
// No index while the bootstrap is pending: coverage is unknown, so
|
||||
// report not-all and let `selectAll` fetch the whole result.
|
||||
if (!galleryRoms.metadataLoaded) return false;
|
||||
const loaded = galleryRoms.byPosition;
|
||||
if (loaded.size === 0) return false;
|
||||
for (const rom of loaded.values()) {
|
||||
if (!selection.selected.has(rom.id)) return false;
|
||||
if (!selected.has(rom.id)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
@@ -47,23 +52,46 @@ export function useGallerySelectAll() {
|
||||
/** Tri-state for the list header checkbox glyph. */
|
||||
const selectionState = computed<GallerySelectionState>(() => {
|
||||
if (selection.count === 0) return "off";
|
||||
// An empty result has nothing to select, whatever the count says.
|
||||
if (
|
||||
galleryRoms.romIdIndex.length === 0 &&
|
||||
galleryRoms.byPosition.size === 0
|
||||
) {
|
||||
return "off";
|
||||
}
|
||||
return allSelected.value ? "all" : "some";
|
||||
});
|
||||
|
||||
/** Select the whole filtered result. Loaded ROMs merge immediately;
|
||||
* the remainder arrives from `fetchAllFilteredRoms` and merges unless
|
||||
* the user cleared the selection in the meantime (epoch guard). */
|
||||
/** Select the whole filtered result: loaded ROMs merge immediately,
|
||||
* the remainder merges when `fetchAllFilteredRoms` lands. */
|
||||
async function selectAll(): Promise<void> {
|
||||
selection.selectMany(galleryRoms.byPosition.values());
|
||||
if (galleryRoms.byPosition.size > 0) {
|
||||
selection.selectMany(galleryRoms.byPosition.values());
|
||||
}
|
||||
pendingEpoch = selection.epoch;
|
||||
selectedAtDispatch = new Set(selection.ids);
|
||||
if (selectingAll.value || allSelected.value) return;
|
||||
const epochAtStart = selection.epoch;
|
||||
// The fetch needs a gallery context to scope the query; without one
|
||||
// (Settings "Missing" tab, a mid-switch reset) stay loaded-only.
|
||||
if (!galleryRoms.onGalleryView) return;
|
||||
// An id index still empty after bootstrap means the surface opted
|
||||
// out of it, or the result is empty: nothing more to fetch.
|
||||
if (galleryRoms.metadataLoaded && galleryRoms.romIdIndex.length === 0) {
|
||||
return;
|
||||
}
|
||||
selectingAll.value = true;
|
||||
try {
|
||||
const roms = await galleryRoms.fetchAllFilteredRoms();
|
||||
if (roms && selection.epoch === epochAtStart) {
|
||||
selection.selectMany(roms);
|
||||
if (roms && selection.epoch === pendingEpoch) {
|
||||
const selected = toRaw(selection.selected);
|
||||
selection.selectMany(
|
||||
roms.filter(
|
||||
(rom) => !selectedAtDispatch.has(rom.id) || selected.has(rom.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
console.error("[useGallerySelectAll] whole-result fetch failed", err);
|
||||
snackbar.error(t("gallery.selection-select-all-fail"));
|
||||
} finally {
|
||||
selectingAll.value = false;
|
||||
|
||||
@@ -3,7 +3,9 @@ import { createPinia, setActivePinia } from "pinia";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import storeGalleryFilter from "@/stores/galleryFilter";
|
||||
// Import after the mock so the store binds to the mocked rom API.
|
||||
import storeGalleryRoms from "@/v2/stores/galleryRoms";
|
||||
import storeGalleryRoms, {
|
||||
SELECT_ALL_PAGE_SIZE,
|
||||
} from "@/v2/stores/galleryRoms";
|
||||
|
||||
const { getRoms } = vi.hoisted(() => ({ getRoms: vi.fn() }));
|
||||
|
||||
@@ -24,8 +26,12 @@ function deferred(): Deferred {
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function windowResponse(offset: number, total = 1000) {
|
||||
return { data: { total, items: [], char_index: {}, rom_id_index: [] } };
|
||||
function windowResponse(
|
||||
offset: number,
|
||||
total: number | null = 1000,
|
||||
items: unknown[] = [],
|
||||
) {
|
||||
return { data: { total, items, char_index: {}, rom_id_index: [] } };
|
||||
}
|
||||
|
||||
describe("galleryRoms windowed fetch", () => {
|
||||
@@ -321,26 +327,29 @@ describe("galleryRoms whole-result fetch", () => {
|
||||
});
|
||||
|
||||
it("pages through backend-capped pages until a short page", async () => {
|
||||
// A full page (the backend's 10k limit cap) forces a second request.
|
||||
const fullPage = Array.from({ length: 10_000 }, (_, i) => ({ id: i }));
|
||||
const lastPage = [{ id: 10_000 }, { id: 10_001 }];
|
||||
// A full page (the backend's limit cap) forces a second request.
|
||||
const fullPage = Array.from({ length: SELECT_ALL_PAGE_SIZE }, (_, i) => ({
|
||||
id: i,
|
||||
}));
|
||||
const lastPage = [
|
||||
{ id: SELECT_ALL_PAGE_SIZE },
|
||||
{ id: SELECT_ALL_PAGE_SIZE + 1 },
|
||||
];
|
||||
getRoms.mockImplementation((params: { offset: number }) =>
|
||||
Promise.resolve({
|
||||
data: {
|
||||
total: null,
|
||||
items: params.offset === 0 ? fullPage : lastPage,
|
||||
char_index: {},
|
||||
rom_id_index: [],
|
||||
},
|
||||
}),
|
||||
Promise.resolve(
|
||||
windowResponse(0, null, params.offset === 0 ? fullPage : lastPage),
|
||||
),
|
||||
);
|
||||
const store = storeGalleryRoms();
|
||||
|
||||
const roms = await store.fetchAllFilteredRoms();
|
||||
|
||||
expect(roms).toHaveLength(10_002);
|
||||
expect(roms).toHaveLength(SELECT_ALL_PAGE_SIZE + 2);
|
||||
expect(getRoms).toHaveBeenCalledTimes(2);
|
||||
expect(getRoms.mock.calls.map((c) => c[0].offset)).toEqual([0, 10_000]);
|
||||
expect(getRoms.mock.calls.map((c) => c[0].offset)).toEqual([
|
||||
0,
|
||||
SELECT_ALL_PAGE_SIZE,
|
||||
]);
|
||||
// Whole-result pages skip every sidecar aggregation.
|
||||
expect(getRoms.mock.calls[0][0]).toMatchObject({
|
||||
withCharIndex: false,
|
||||
@@ -360,14 +369,7 @@ describe("galleryRoms whole-result fetch", () => {
|
||||
|
||||
const fetching = store.fetchAllFilteredRoms();
|
||||
store.invalidateWindows();
|
||||
d.resolve({
|
||||
data: {
|
||||
total: null,
|
||||
items: [{ id: 1 }],
|
||||
char_index: {},
|
||||
rom_id_index: [],
|
||||
},
|
||||
});
|
||||
d.resolve(windowResponse(0, null, [{ id: 1 }]));
|
||||
|
||||
expect(await fetching).toBeNull();
|
||||
});
|
||||
|
||||
@@ -63,10 +63,19 @@ type GalleryFilterStore = ExtractPiniaStoreType<typeof storeGalleryFilter>;
|
||||
// fewer requests but each one downloads more.
|
||||
const WINDOW_SIZE = 72;
|
||||
|
||||
// Page size for the whole-result fetch behind "select all". Matches the
|
||||
// backend's ceiling on the `/roms` limit param (le=10_000), so results
|
||||
// up to that size arrive in one request.
|
||||
const SELECT_ALL_PAGE_SIZE = 10_000;
|
||||
// Page size for the whole-result fetch behind "select all": the
|
||||
// backend's ceiling on the `/roms` limit param (le=10_000). Exported
|
||||
// for the tests that exercise the paging.
|
||||
export const SELECT_ALL_PAGE_SIZE = 10_000;
|
||||
|
||||
// Request params that skip every whole-result aggregation (sidecars
|
||||
// plus the COUNT) for fetches that only need their page of items.
|
||||
const SKIP_AGGREGATES = {
|
||||
withCharIndex: false,
|
||||
withFilterValues: false,
|
||||
withRomIdIndex: false,
|
||||
withTotal: false,
|
||||
} as const;
|
||||
|
||||
// In-flight `AbortController`s keyed by request: `window:${offset}`
|
||||
// for a windowed fetch, `bootstrap` for the lightweight metadata
|
||||
@@ -552,14 +561,7 @@ export default defineStore("v2GalleryRoms", {
|
||||
try {
|
||||
const response = await romApi.getRoms({
|
||||
...params,
|
||||
...(withAggregations
|
||||
? {}
|
||||
: {
|
||||
withCharIndex: false,
|
||||
withFilterValues: false,
|
||||
withRomIdIndex: false,
|
||||
withTotal: false,
|
||||
}),
|
||||
...(withAggregations ? {} : SKIP_AGGREGATES),
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Re-check identity: invalidateWindows / resetGallery / a context
|
||||
@@ -650,13 +652,8 @@ export default defineStore("v2GalleryRoms", {
|
||||
}
|
||||
},
|
||||
|
||||
/** Fetch every ROM of the current filtered result, in backend-capped
|
||||
* pages. Powers the whole-result "select all": the selection store
|
||||
* keeps full `SimpleRom`s (bulk actions need real objects), so ids
|
||||
* from `romIdIndex` alone are not enough. Loaded windows are left
|
||||
* untouched; the result goes straight to the selection. Registered
|
||||
* in `inFlightControllers`, so `invalidateWindows` / `resetGallery`
|
||||
* / a context switch aborts it.
|
||||
/** Fetch every ROM of the current filtered result in backend-capped
|
||||
* pages, for the whole-result "select all".
|
||||
*
|
||||
* Returns:
|
||||
* The full result set, or null when aborted or superseded.
|
||||
@@ -672,24 +669,20 @@ export default defineStore("v2GalleryRoms", {
|
||||
|
||||
try {
|
||||
const all: SimpleRom[] = [];
|
||||
let offset = 0;
|
||||
for (;;) {
|
||||
let page: SimpleRom[];
|
||||
do {
|
||||
const response = await romApi.getRoms({
|
||||
...params,
|
||||
...SKIP_AGGREGATES,
|
||||
limit: SELECT_ALL_PAGE_SIZE,
|
||||
offset,
|
||||
withCharIndex: false,
|
||||
withFilterValues: false,
|
||||
withRomIdIndex: false,
|
||||
withTotal: false,
|
||||
offset: all.length,
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (inFlightControllers.get(ctrlKey) !== controller) return null;
|
||||
all.push(...response.data.items);
|
||||
// A short page is the last page.
|
||||
if (response.data.items.length < SELECT_ALL_PAGE_SIZE) return all;
|
||||
offset += SELECT_ALL_PAGE_SIZE;
|
||||
}
|
||||
page = response.data.items;
|
||||
for (const rom of page) all.push(rom);
|
||||
} while (page.length === SELECT_ALL_PAGE_SIZE);
|
||||
return all;
|
||||
} catch (err) {
|
||||
if (axios.isCancel(err)) return null;
|
||||
throw err;
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
// to a platform should drop the selection, but we let the view
|
||||
// decide so an in-page filter change can preserve it.
|
||||
import { defineStore } from "pinia";
|
||||
import { toRaw } from "vue";
|
||||
import type { SimpleRom } from "@/stores/roms";
|
||||
|
||||
interface State {
|
||||
@@ -39,9 +40,8 @@ interface State {
|
||||
* ROM. Used as the anchor for shift-range selection. `null` means
|
||||
* no anchor yet (next shift-click acts as a single toggle). */
|
||||
lastSelectedPosition: number | null;
|
||||
/** Bumped by `clear()`. Async select flows (useGallerySelectAll)
|
||||
* snapshot it before fetching and drop a late result if the user
|
||||
* abandoned the selection in the meantime. */
|
||||
/** Bumped by `clear()`; async select flows (useGallerySelectAll)
|
||||
* compare it before merging a late fetch result. */
|
||||
epoch: number;
|
||||
}
|
||||
|
||||
@@ -122,14 +122,20 @@ export default defineStore("v2GallerySelection", {
|
||||
this.lastSelectedPosition = position;
|
||||
},
|
||||
|
||||
/** Add every given ROM to the selection (existing picks are kept).
|
||||
* `useGallerySelectAll` feeds it the loaded windows for instant
|
||||
* feedback, then the fetched whole-result set. One Map swap per
|
||||
* call, so a large merge is a single reactive invalidation. */
|
||||
/** Merge the given ROMs into the selection (existing picks kept).
|
||||
* One Map swap per call, skipped when nothing changed. */
|
||||
selectMany(roms: Iterable<SimpleRom>) {
|
||||
const next = new Map(this.selected);
|
||||
for (const rom of roms) next.set(rom.id, rom);
|
||||
this.selected = next;
|
||||
// Clone from the raw Map: the swap below is the reactive trigger,
|
||||
// so per-entry proxy wrapping during the copy is pure overhead.
|
||||
const next = new Map(toRaw(this.selected));
|
||||
let changed = false;
|
||||
for (const rom of roms) {
|
||||
if (next.get(rom.id) !== rom) {
|
||||
next.set(rom.id, rom);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) this.selected = next;
|
||||
},
|
||||
|
||||
/** Replace the selection with exactly the given ROMs. Used by
|
||||
@@ -140,9 +146,8 @@ export default defineStore("v2GallerySelection", {
|
||||
},
|
||||
|
||||
/** Drop the selection and anchor. Bound to Esc, the SelectionBar
|
||||
* clear button, and view route-leave. Bumps `epoch` even when the
|
||||
* selection is already empty, so a select-all fetch launched from
|
||||
* an empty selection is still abandoned by a clear gesture. */
|
||||
* clear button, and view route-leave. Bumps `epoch` first (even
|
||||
* when already empty) so in-flight select-all merges are abandoned. */
|
||||
clear() {
|
||||
this.epoch += 1;
|
||||
if (this.selected.size === 0 && this.lastSelectedPosition === null) {
|
||||
|
||||
Reference in New Issue
Block a user