diff --git a/frontend/src/locales/bg_BG/gallery.json b/frontend/src/locales/bg_BG/gallery.json index ed738e435..53cb27722 100644 --- a/frontend/src/locales/bg_BG/gallery.json +++ b/frontend/src/locales/bg_BG/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} са добавени в любими", "selection-n-selected": "{n} избрани", "selection-refresh-metadata": "Обнови метаданните", - "selection-select-all": "Избери всички заредени", + "selection-select-all": "Избери всички", + "selection-select-all-count": "Избери всички ({n})", + "selection-select-all-fail": "Неуспешно избиране на всички игри", "selection-status": "Задаване на статус", "selection-status-fail": "Неуспешно обновяване на статуса", "selection-status-partial": "Обновени {n} от {total} игри", diff --git a/frontend/src/locales/cs_CZ/gallery.json b/frontend/src/locales/cs_CZ/gallery.json index dd43efbf4..7d3b7089a 100644 --- a/frontend/src/locales/cs_CZ/gallery.json +++ b/frontend/src/locales/cs_CZ/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} přidáno mezi oblíbené", "selection-n-selected": "{n} vybráno", "selection-refresh-metadata": "Obnovit metadata", - "selection-select-all": "Vybrat vše načtené", + "selection-select-all": "Vybrat vše", + "selection-select-all-count": "Vybrat vše ({n})", + "selection-select-all-fail": "Nepodařilo se vybrat všechny hry", "selection-status": "Nastavit stav", "selection-status-fail": "Aktualizace stavu se nezdařila", "selection-status-partial": "Aktualizováno {n} z {total} her", diff --git a/frontend/src/locales/de_DE/gallery.json b/frontend/src/locales/de_DE/gallery.json index 21da84367..d47a44813 100644 --- a/frontend/src/locales/de_DE/gallery.json +++ b/frontend/src/locales/de_DE/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} zu Favoriten hinzugefügt", "selection-n-selected": "{n} ausgewählt", "selection-refresh-metadata": "Metadaten aktualisieren", - "selection-select-all": "Alle geladenen auswählen", + "selection-select-all": "Alle auswählen", + "selection-select-all-count": "Alle auswählen ({n})", + "selection-select-all-fail": "Auswahl aller Spiele fehlgeschlagen", "selection-status": "Status festlegen", "selection-status-fail": "Status konnte nicht aktualisiert werden", "selection-status-partial": "{n} von {total} Spielen aktualisiert", diff --git a/frontend/src/locales/en_GB/gallery.json b/frontend/src/locales/en_GB/gallery.json index eefea52ed..101cda682 100644 --- a/frontend/src/locales/en_GB/gallery.json +++ b/frontend/src/locales/en_GB/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} added to favourites", "selection-n-selected": "{n} selected", "selection-refresh-metadata": "Refresh metadata", - "selection-select-all": "Select all loaded", + "selection-select-all": "Select all", + "selection-select-all-count": "Select all ({n})", + "selection-select-all-fail": "Failed to select all games", "selection-status": "Set status", "selection-status-fail": "Failed to update status", "selection-status-partial": "Updated {n} of {total} games", diff --git a/frontend/src/locales/en_US/gallery.json b/frontend/src/locales/en_US/gallery.json index ea61d9af7..526c98e66 100644 --- a/frontend/src/locales/en_US/gallery.json +++ b/frontend/src/locales/en_US/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} added to favorites", "selection-n-selected": "{n} selected", "selection-refresh-metadata": "Refresh metadata", - "selection-select-all": "Select all loaded", + "selection-select-all": "Select all", + "selection-select-all-count": "Select all ({n})", + "selection-select-all-fail": "Failed to select all games", "selection-status": "Set status", "selection-status-fail": "Failed to update status", "selection-status-partial": "Updated {n} of {total} games", diff --git a/frontend/src/locales/es_ES/gallery.json b/frontend/src/locales/es_ES/gallery.json index 53c4150b5..5f769e5c8 100644 --- a/frontend/src/locales/es_ES/gallery.json +++ b/frontend/src/locales/es_ES/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} añadidos a favoritos", "selection-n-selected": "{n} seleccionados", "selection-refresh-metadata": "Actualizar metadatos", - "selection-select-all": "Seleccionar todos los cargados", + "selection-select-all": "Seleccionar todo", + "selection-select-all-count": "Seleccionar todo ({n})", + "selection-select-all-fail": "Error al seleccionar todos los juegos", "selection-status": "Establecer estado", "selection-status-fail": "Error al actualizar el estado", "selection-status-partial": "Actualizados {n} de {total} juegos", diff --git a/frontend/src/locales/fr_FR/gallery.json b/frontend/src/locales/fr_FR/gallery.json index 00bd51cfa..5ea254a67 100644 --- a/frontend/src/locales/fr_FR/gallery.json +++ b/frontend/src/locales/fr_FR/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} ajouté(s) aux favoris", "selection-n-selected": "{n} sélectionné(s)", "selection-refresh-metadata": "Actualiser les métadonnées", - "selection-select-all": "Sélectionner tous les chargés", + "selection-select-all": "Tout sélectionner", + "selection-select-all-count": "Tout sélectionner ({n})", + "selection-select-all-fail": "Échec de la sélection de tous les jeux", "selection-status": "Définir le statut", "selection-status-fail": "Échec de la mise à jour du statut", "selection-status-partial": "{n} sur {total} jeux mis à jour", diff --git a/frontend/src/locales/hu_HU/gallery.json b/frontend/src/locales/hu_HU/gallery.json index 206ab4504..15d96f174 100644 --- a/frontend/src/locales/hu_HU/gallery.json +++ b/frontend/src/locales/hu_HU/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} hozzáadva a kedvencekhez", "selection-n-selected": "{n} kiválasztva", "selection-refresh-metadata": "Metaadatok frissítése", - "selection-select-all": "Összes betöltött kijelölése", + "selection-select-all": "Összes kijelölése", + "selection-select-all-count": "Összes kijelölése ({n})", + "selection-select-all-fail": "Az összes játék kijelölése sikertelen", "selection-status": "Állapot beállítása", "selection-status-fail": "Az állapot frissítése sikertelen", "selection-status-partial": "{n} / {total} játék frissítve", diff --git a/frontend/src/locales/it_IT/gallery.json b/frontend/src/locales/it_IT/gallery.json index 07a6c42f1..d1420d159 100644 --- a/frontend/src/locales/it_IT/gallery.json +++ b/frontend/src/locales/it_IT/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} aggiunti ai preferiti", "selection-n-selected": "{n} selezionati", "selection-refresh-metadata": "Aggiorna metadati", - "selection-select-all": "Seleziona tutti i caricati", + "selection-select-all": "Seleziona tutti", + "selection-select-all-count": "Seleziona tutti ({n})", + "selection-select-all-fail": "Impossibile selezionare tutti i giochi", "selection-status": "Imposta stato", "selection-status-fail": "Impossibile aggiornare lo stato", "selection-status-partial": "Aggiornati {n} di {total} giochi", diff --git a/frontend/src/locales/ja_JP/gallery.json b/frontend/src/locales/ja_JP/gallery.json index 4a8bdc784..e748f8469 100644 --- a/frontend/src/locales/ja_JP/gallery.json +++ b/frontend/src/locales/ja_JP/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n}件をお気に入りに追加しました", "selection-n-selected": "{n}件選択中", "selection-refresh-metadata": "メタデータを更新", - "selection-select-all": "読み込み済みをすべて選択", + "selection-select-all": "すべて選択", + "selection-select-all-count": "すべて選択 ({n})", + "selection-select-all-fail": "すべてのゲームの選択に失敗しました", "selection-status": "ステータスを設定", "selection-status-fail": "ステータスの更新に失敗しました", "selection-status-partial": "{total} 件中 {n} 件のゲームを更新しました", diff --git a/frontend/src/locales/ko_KR/gallery.json b/frontend/src/locales/ko_KR/gallery.json index 0491153ed..fb7880a66 100644 --- a/frontend/src/locales/ko_KR/gallery.json +++ b/frontend/src/locales/ko_KR/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n}개를 즐겨찾기에 추가했습니다", "selection-n-selected": "{n}개 선택됨", "selection-refresh-metadata": "메타데이터 새로 고침", - "selection-select-all": "불러온 항목 모두 선택", + "selection-select-all": "모두 선택", + "selection-select-all-count": "모두 선택 ({n})", + "selection-select-all-fail": "모든 게임을 선택하지 못했습니다", "selection-status": "상태 설정", "selection-status-fail": "상태 업데이트에 실패했습니다", "selection-status-partial": "게임 {total}개 중 {n}개를 업데이트했습니다", diff --git a/frontend/src/locales/pl_PL/gallery.json b/frontend/src/locales/pl_PL/gallery.json index 11216db10..d707121d8 100644 --- a/frontend/src/locales/pl_PL/gallery.json +++ b/frontend/src/locales/pl_PL/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} dodano do ulubionych", "selection-n-selected": "{n} wybrano", "selection-refresh-metadata": "Odśwież metadane", - "selection-select-all": "Zaznacz wszystkie załadowane", + "selection-select-all": "Zaznacz wszystkie", + "selection-select-all-count": "Zaznacz wszystkie ({n})", + "selection-select-all-fail": "Nie udało się zaznaczyć wszystkich gier", "selection-status": "Ustaw status", "selection-status-fail": "Nie udało się zaktualizować statusu", "selection-status-partial": "Zaktualizowano {n} z {total} gier", diff --git a/frontend/src/locales/pt_BR/gallery.json b/frontend/src/locales/pt_BR/gallery.json index ec616da15..7526a1ad0 100644 --- a/frontend/src/locales/pt_BR/gallery.json +++ b/frontend/src/locales/pt_BR/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} adicionado(s) aos favoritos", "selection-n-selected": "{n} selecionado(s)", "selection-refresh-metadata": "Atualizar metadados", - "selection-select-all": "Selecionar todos os carregados", + "selection-select-all": "Selecionar todos", + "selection-select-all-count": "Selecionar todos ({n})", + "selection-select-all-fail": "Falha ao selecionar todos os jogos", "selection-status": "Definir status", "selection-status-fail": "Falha ao atualizar o status", "selection-status-partial": "Atualizados {n} de {total} jogos", diff --git a/frontend/src/locales/ro_RO/gallery.json b/frontend/src/locales/ro_RO/gallery.json index b121de09e..57295d695 100644 --- a/frontend/src/locales/ro_RO/gallery.json +++ b/frontend/src/locales/ro_RO/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} adăugate la favorite", "selection-n-selected": "{n} selectate", "selection-refresh-metadata": "Actualizează metadatele", - "selection-select-all": "Selectează tot ce este încărcat", + "selection-select-all": "Selectează tot", + "selection-select-all-count": "Selectează tot ({n})", + "selection-select-all-fail": "Selectarea tuturor jocurilor a eșuat", "selection-status": "Setează starea", "selection-status-fail": "Actualizarea stării a eșuat", "selection-status-partial": "Actualizate {n} din {total} jocuri", diff --git a/frontend/src/locales/ru_RU/gallery.json b/frontend/src/locales/ru_RU/gallery.json index 1ab154c4e..7237a6119 100644 --- a/frontend/src/locales/ru_RU/gallery.json +++ b/frontend/src/locales/ru_RU/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "{n} добавлено в избранное", "selection-n-selected": "{n} выбрано", "selection-refresh-metadata": "Обновить метаданные", - "selection-select-all": "Выбрать все загруженные", + "selection-select-all": "Выбрать все", + "selection-select-all-count": "Выбрать все ({n})", + "selection-select-all-fail": "Не удалось выбрать все игры", "selection-status": "Задать статус", "selection-status-fail": "Не удалось обновить статус", "selection-status-partial": "Обновлено {n} из {total} игр", diff --git a/frontend/src/locales/tr_TR/gallery.json b/frontend/src/locales/tr_TR/gallery.json index f6b0fd9b0..f64b74bfb 100644 --- a/frontend/src/locales/tr_TR/gallery.json +++ b/frontend/src/locales/tr_TR/gallery.json @@ -18,6 +18,8 @@ "selection-n-selected": "{n} seçildi", "selection-refresh-metadata": "Meta verileri yenile", "selection-select-all": "Tümünü seç", + "selection-select-all-count": "Tümünü seç ({n})", + "selection-select-all-fail": "Tüm oyunlar seçilemedi", "selection-status": "Durum ayarla", "selection-status-fail": "Durum güncellenemedi", "selection-status-partial": "{total} oyundan {n} tanesi güncellendi", diff --git a/frontend/src/locales/zh_CN/gallery.json b/frontend/src/locales/zh_CN/gallery.json index c34e8b08b..160285c06 100644 --- a/frontend/src/locales/zh_CN/gallery.json +++ b/frontend/src/locales/zh_CN/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "已添加 {n} 个到喜好", "selection-n-selected": "已选择 {n} 个", "selection-refresh-metadata": "刷新元数据", - "selection-select-all": "选择所有已加载项", + "selection-select-all": "全选", + "selection-select-all-count": "全选 ({n})", + "selection-select-all-fail": "全选游戏失败", "selection-status": "设置状态", "selection-status-fail": "更新状态失败", "selection-status-partial": "已更新 {total} 个游戏中的 {n} 个", diff --git a/frontend/src/locales/zh_TW/gallery.json b/frontend/src/locales/zh_TW/gallery.json index a0dc334b7..70de68c02 100644 --- a/frontend/src/locales/zh_TW/gallery.json +++ b/frontend/src/locales/zh_TW/gallery.json @@ -17,7 +17,9 @@ "selection-favorite-success": "已將 {n} 個加入喜好", "selection-n-selected": "已選擇 {n} 個", "selection-refresh-metadata": "更新元數據", - "selection-select-all": "選擇所有已載入項目", + "selection-select-all": "全選", + "selection-select-all-count": "全選 ({n})", + "selection-select-all-fail": "全選遊戲失敗", "selection-status": "設定狀態", "selection-status-fail": "更新狀態失敗", "selection-status-partial": "已更新 {total} 個遊戲中的 {n} 個", diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index 126202298..29ccb3461 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -72,6 +72,7 @@ import { useDebugMode } from "@/v2/composables/useDebugMode"; import { useGalleryCoverRatios } from "@/v2/composables/useGalleryCoverRatios"; import { useGalleryFilterUrl } from "@/v2/composables/useGalleryFilterUrl"; import { useGalleryMode } from "@/v2/composables/useGalleryMode"; +import { useGallerySelectAll } from "@/v2/composables/useGallerySelectAll"; import { useGalleryViewModeUrl } from "@/v2/composables/useGalleryViewModeUrl"; import { useGalleryVirtualItems, @@ -780,8 +781,12 @@ onBeforeRouteLeave((_to, from) => { gallerySelection.clear(); }); +// Whole-result select-all, shared with the SelectionBar button and +// the list header checkbox. +const { selectAll } = useGallerySelectAll(); + // Global hotkeys scoped to the gallery shell — Esc clears the -// selection, Ctrl/Cmd+A selects every currently-loaded rom. Both are +// selection, Ctrl/Cmd+A selects the whole filtered result. Both are // guarded against editable elements so the search field's native // Cmd+A still selects the input text. function onShellKey(e: KeyboardEvent) { @@ -802,7 +807,7 @@ function onShellKey(e: KeyboardEvent) { } if ((e.ctrlKey || e.metaKey) && (e.key === "a" || e.key === "A")) { e.preventDefault(); - gallerySelection.selectAllLoaded(galleryRoms.byPosition.values()); + void selectAll(); } } diff --git a/frontend/src/v2/components/Gallery/GameListHeader.vue b/frontend/src/v2/components/Gallery/GameListHeader.vue index 62b7f14ef..4b8fbf484 100644 --- a/frontend/src/v2/components/Gallery/GameListHeader.vue +++ b/frontend/src/v2/components/Gallery/GameListHeader.vue @@ -12,7 +12,7 @@ import { RCheckbox, RIcon } from "@v2/lib"; import { computed } from "vue"; import { useI18n } from "vue-i18n"; -import storeGalleryRoms from "@/v2/stores/galleryRoms"; +import { useGallerySelectAll } from "@/v2/composables/useGallerySelectAll"; import storeGallerySelection from "@/v2/stores/gallerySelection"; import { getListColumns, @@ -55,37 +55,20 @@ const gridStyle = computed(() => ({ ), })); -const galleryRoms = storeGalleryRoms(); const selection = storeGallerySelection(); - -// Select-all state derived from the *loaded* ROMs (sparse galleries -// don't have everything in memory until the user scrolls there). Three -// states drive the checkbox glyph: -// * "off" — no loaded rom is selected (or there are none) -// * "all" — every loaded rom is selected -// * "some" — at least one but not all loaded roms are selected -const loadedSelectionState = computed<"off" | "some" | "all">(() => { - const loaded = galleryRoms.byPosition; - if (loaded.size === 0) return "off"; - let selected = 0; - for (const rom of loaded.values()) { - if (selection.isSelected(rom.id)) selected += 1; - } - if (selected === 0) return "off"; - if (selected === loaded.size) return "all"; - return "some"; -}); +// Whole-result select-all shared with the SelectionBar and Ctrl/Cmd+A; +// `selectionState` drives the tri-state checkbox glyph. +const { selectionState, selectAll } = useGallerySelectAll(); function onSelectAllClick(e: MouseEvent) { e.preventDefault(); e.stopPropagation(); - const state = loadedSelectionState.value; // Indeterminate behaves like "off → all" (typical file-manager UX: // a tri-state checkbox click resolves to "all checked"). - if (state === "all") { + if (selectionState.value === "all") { selection.clear(); } else { - selection.selectAllLoaded(galleryRoms.byPosition.values()); + void selectAll(); } } @@ -107,24 +90,23 @@ function handleClick(col: ListColumn) { @@ -563,6 +593,12 @@ html[data-bp~="xs"] .selection-bar__count { font-size: var(--r-font-size-sm); } +/* The count icon is decorative; on xs its width budget goes to the + select-all button so the bar still fits a 320px viewport. */ +html[data-bp~="xs"] .selection-bar__count-icon { + display: none; +} + /* Tighten the action row on phones so all buttons + the count + divider fit a 320px width: squeeze the inter-button gaps and side padding. */ html[data-bp~="xs"] .selection-bar__panel { diff --git a/frontend/src/v2/composables/useGallerySelectAll/index.test.ts b/frontend/src/v2/composables/useGallerySelectAll/index.test.ts new file mode 100644 index 000000000..487622c48 --- /dev/null +++ b/frontend/src/v2/composables/useGallerySelectAll/index.test.ts @@ -0,0 +1,179 @@ +import { flushPromises } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { 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 storeGallerySelection from "@/v2/stores/gallerySelection"; + +const { getRoms, snackbarError } = vi.hoisted(() => ({ + getRoms: vi.fn(), + snackbarError: vi.fn(), +})); + +vi.mock("@/services/api/rom", () => ({ + default: { getRoms }, +})); + +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ + success: vi.fn(), + error: snackbarError, + warning: vi.fn(), + info: vi.fn(), + }), +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); + +function rom(id: number): SimpleRom { + return { id, name: `Game ${id}`, platform_id: 1 } as SimpleRom; +} + +function resultPage(items: SimpleRom[]) { + return { + data: { total: null, items, char_index: {}, rom_id_index: [] }, + }; +} + +interface Deferred { + promise: Promise; + resolve: (value: unknown) => void; +} + +function deferred(): Deferred { + let resolve!: (value: unknown) => void; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} + +describe("useGallerySelectAll", () => { + beforeEach(() => { + setActivePinia(createPinia()); + vi.clearAllMocks(); + }); + + it("selects the whole filtered result, not just the loaded windows", async () => { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + galleryRoms.romIdIndex = [1, 2, 3, 4]; + 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, allSelected } = useGallerySelectAll(); + await selectAll(); + + expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2, 3, 4]); + expect(allSelected.value).toBe(true); + // One whole-result request, sidecar aggregations off. + expect(getRoms).toHaveBeenCalledTimes(1); + expect(getRoms.mock.calls[0][0]).toMatchObject({ + limit: 10_000, + offset: 0, + withCharIndex: false, + withFilterValues: false, + withRomIdIndex: false, + withTotal: false, + }); + }); + + it("merges the loaded roms before the whole-result fetch resolves", async () => { + const galleryRoms = storeGalleryRoms(); + 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 done = selectAll(); + expect(selection.ids).toEqual([1]); + + d.resolve(resultPage([rom(1), rom(2), rom(3)])); + await done; + expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2, 3]); + }); + + it("skips the fetch when the whole result is already selected", async () => { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + galleryRoms.romIdIndex = [1, 2]; + galleryRoms.byPosition.set(0, rom(1)); + galleryRoms.byPosition.set(1, rom(2)); + selection.selectMany([rom(1), rom(2)]); + + const { selectAll, selectionState } = useGallerySelectAll(); + await selectAll(); + + expect(getRoms).not.toHaveBeenCalled(); + expect(selectionState.value).toBe("all"); + }); + + it("drops a late result when the selection was cleared mid-fetch", async () => { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + galleryRoms.romIdIndex = [1, 2]; + galleryRoms.byPosition.set(0, rom(1)); + const d = deferred(); + getRoms.mockReturnValue(d.promise); + + const { selectAll } = useGallerySelectAll(); + const done = selectAll(); + selection.clear(); + d.resolve(resultPage([rom(1), rom(2)])); + await done; + + expect(selection.count).toBe(0); + }); + + it("falls back to loaded-only coverage without a rom id index", async () => { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + galleryRoms.byPosition.set(0, rom(1)); + galleryRoms.byPosition.set(1, rom(2)); + + const { selectAll, allSelected } = useGallerySelectAll(); + await selectAll(); + + // The instant merge already covers everything the surface knows + // about, so no whole-result fetch is issued. + expect(getRoms).not.toHaveBeenCalled(); + expect(selection.ids.sort((a, b) => a - b)).toEqual([1, 2]); + expect(allSelected.value).toBe(true); + }); + + it("surfaces a snackbar when the whole-result fetch fails", async () => { + const galleryRoms = storeGalleryRoms(); + galleryRoms.romIdIndex = [1, 2]; + getRoms.mockRejectedValue(new Error("boom")); + + const { selectAll, selectingAll } = useGallerySelectAll(); + await selectAll(); + await flushPromises(); + + expect(snackbarError).toHaveBeenCalledWith( + "gallery.selection-select-all-fail", + ); + expect(selectingAll.value).toBe(false); + }); + + it("reports tri-state coverage for the header checkbox", () => { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + galleryRoms.romIdIndex = [1, 2]; + + const { selectionState } = useGallerySelectAll(); + expect(selectionState.value).toBe("off"); + + selection.selectMany([rom(1)]); + expect(selectionState.value).toBe("some"); + + selection.selectMany([rom(2)]); + expect(selectionState.value).toBe("all"); + }); +}); diff --git a/frontend/src/v2/composables/useGallerySelectAll/index.ts b/frontend/src/v2/composables/useGallerySelectAll/index.ts new file mode 100644 index 000000000..6fb912f35 --- /dev/null +++ b/frontend/src/v2/composables/useGallerySelectAll/index.ts @@ -0,0 +1,74 @@ +// 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"; +import { useI18n } from "vue-i18n"; +import { useSnackbar } from "@/v2/composables/useSnackbar"; +import storeGalleryRoms from "@/v2/stores/galleryRoms"; +import storeGallerySelection from "@/v2/stores/gallerySelection"; + +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); + +export function useGallerySelectAll() { + const galleryRoms = storeGalleryRoms(); + const selection = storeGallerySelection(); + 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. */ + const allSelected = computed(() => { + const ids = galleryRoms.romIdIndex; + if (ids.length > 0) { + return ids.every((id) => selection.selected.has(id)); + } + const loaded = galleryRoms.byPosition; + if (loaded.size === 0) return false; + for (const rom of loaded.values()) { + if (!selection.selected.has(rom.id)) return false; + } + return true; + }); + + /** Tri-state for the list header checkbox glyph. */ + const selectionState = computed(() => { + if (selection.count === 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). */ + async function selectAll(): Promise { + selection.selectMany(galleryRoms.byPosition.values()); + if (selectingAll.value || allSelected.value) return; + const epochAtStart = selection.epoch; + selectingAll.value = true; + try { + const roms = await galleryRoms.fetchAllFilteredRoms(); + if (roms && selection.epoch === epochAtStart) { + selection.selectMany(roms); + } + } catch { + snackbar.error(t("gallery.selection-select-all-fail")); + } finally { + selectingAll.value = false; + } + } + + return { selectingAll, allSelected, selectionState, selectAll }; +} diff --git a/frontend/src/v2/stores/galleryRoms.test.ts b/frontend/src/v2/stores/galleryRoms.test.ts index 23d86c338..afa875fee 100644 --- a/frontend/src/v2/stores/galleryRoms.test.ts +++ b/frontend/src/v2/stores/galleryRoms.test.ts @@ -314,6 +314,65 @@ describe("galleryRoms windowed fetch", () => { }); }); +describe("galleryRoms whole-result fetch", () => { + beforeEach(() => { + setActivePinia(createPinia()); + getRoms.mockReset(); + }); + + 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 }]; + getRoms.mockImplementation((params: { offset: number }) => + Promise.resolve({ + data: { + total: null, + items: params.offset === 0 ? fullPage : lastPage, + char_index: {}, + rom_id_index: [], + }, + }), + ); + const store = storeGalleryRoms(); + + const roms = await store.fetchAllFilteredRoms(); + + expect(roms).toHaveLength(10_002); + expect(getRoms).toHaveBeenCalledTimes(2); + expect(getRoms.mock.calls.map((c) => c[0].offset)).toEqual([0, 10_000]); + // Whole-result pages skip every sidecar aggregation. + expect(getRoms.mock.calls[0][0]).toMatchObject({ + withCharIndex: false, + withFilterValues: false, + withRomIdIndex: false, + withTotal: false, + }); + // Loaded windows stay untouched: the result goes to the selection, + // not into the sparse gallery cache. + expect(store.byPosition.size).toBe(0); + }); + + it("returns null when the gallery context is invalidated mid-flight", async () => { + const d = deferred(); + getRoms.mockReturnValue(d.promise); + const store = storeGalleryRoms(); + + const fetching = store.fetchAllFilteredRoms(); + store.invalidateWindows(); + d.resolve({ + data: { + total: null, + items: [{ id: 1 }], + char_index: {}, + rom_id_index: [], + }, + }); + + expect(await fetching).toBeNull(); + }); +}); + describe("galleryRoms length filter", () => { beforeEach(() => { setActivePinia(createPinia()); diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index 2268047d9..0c5810af7 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -63,6 +63,11 @@ type GalleryFilterStore = ExtractPiniaStoreType; // 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; + // In-flight `AbortController`s keyed by request: `window:${offset}` // for a windowed fetch, `bootstrap` for the lightweight metadata // bootstrap. Lives outside store state so Pinia doesn't @@ -645,6 +650,56 @@ 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. + * + * Returns: + * The full result set, or null when aborted or superseded. + * Non-cancel errors are rethrown for the caller to surface. */ + async fetchAllFilteredRoms(): Promise { + const galleryFilter = storeGalleryFilter(); + const params = this._buildRequestParams(galleryFilter, 0); + const ctrlKey = "select-all"; + // A re-trigger supersedes the previous run. + inFlightControllers.get(ctrlKey)?.abort(); + const controller = new AbortController(); + inFlightControllers.set(ctrlKey, controller); + + try { + const all: SimpleRom[] = []; + let offset = 0; + for (;;) { + const response = await romApi.getRoms({ + ...params, + limit: SELECT_ALL_PAGE_SIZE, + offset, + withCharIndex: false, + withFilterValues: false, + withRomIdIndex: false, + withTotal: false, + 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; + } + } catch (err) { + if (axios.isCancel(err)) return null; + throw err; + } finally { + if (inFlightControllers.get(ctrlKey) === controller) { + inFlightControllers.delete(ctrlKey); + } + } + }, + /** Start queued windows as in-flight slots free up. Called from a * window fetch's `finally`; the cap in `fetchWindowAt` guards the * ceiling, so this just feeds it the next parked offset. */ diff --git a/frontend/src/v2/stores/gallerySelection.ts b/frontend/src/v2/stores/gallerySelection.ts index d2dab23af..3028f2b19 100644 --- a/frontend/src/v2/stores/gallerySelection.ts +++ b/frontend/src/v2/stores/gallerySelection.ts @@ -11,8 +11,9 @@ // API calls without re-resolving against the sparse gallery // cache (`galleryRoms.byPosition`), which may have evicted the // rom by the time the user runs the action. Memory is bounded -// by the size of the selection — well within the gallery's -// working set. +// by the size of the selection; a whole-result select-all holds +// the full filtered set, the price of bulk actions needing real +// objects rather than ids. // - `lastSelectedPosition: number | null` — anchor for shift-range // selection. Stored as a *position* in the sparse gallery (matches // `galleryRoms.byPosition` keys) rather than an index into a dense @@ -38,11 +39,16 @@ 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. */ + epoch: number; } const defaults = (): State => ({ selected: new Map(), lastSelectedPosition: null, + epoch: 0, }); export default defineStore("v2GallerySelection", { @@ -116,15 +122,13 @@ export default defineStore("v2GallerySelection", { this.lastSelectedPosition = position; }, - /** Add every currently-loaded ROM in the gallery to the - * selection. v2 galleries are sparse (only fetched windows are - * present in `byPosition`), so this is "select all loaded" — not - * "select all in the entire filtered set". Matches v1's UX (its - * select-all also only touched ROMs already in memory) without - * the perf cost of fetching every page upfront. */ - selectAllLoaded(loadedRoms: Iterable) { + /** 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. */ + selectMany(roms: Iterable) { const next = new Map(this.selected); - for (const rom of loadedRoms) next.set(rom.id, rom); + for (const rom of roms) next.set(rom.id, rom); this.selected = next; }, @@ -136,8 +140,11 @@ export default defineStore("v2GallerySelection", { }, /** Drop the selection and anchor. Bound to Esc, the SelectionBar - * clear button, and view route-leave. */ + * 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() { + this.epoch += 1; if (this.selected.size === 0 && this.lastSelectedPosition === null) { return; }