diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index f8d3d29da..32e844f02 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -666,9 +666,11 @@ def get_roms( request.user.id, order_by, order_dir, filters.group_by_meta_id, is_unscoped ) - # Get the char index for the roms + # Get the char index for the roms. Relevance order has no letter runs. char_index_dict = {} - if with_char_index: + if with_char_index and not db_rom_handler.search_relevance_leads( + order_by, filters.search_term + ): char_index = db_rom_handler.with_char_index( query=query, order_by_attr=sort_key.column, diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index 2a155f2d7..d1a478669 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1815,6 +1815,12 @@ class DBRomsHandler(DBBaseHandler): return query + def search_relevance_leads(self, order_by: str, search_term: str | None) -> bool: + """Whether a gallery query orders by search relevance ahead of its sort key.""" + return not order_by and bool( + search_term and self._build_search_phrases(search_term) + ) + def _gallery_order_clauses( self, *, diff --git a/backend/tests/endpoints/roms/test_rom_sidecar_cache.py b/backend/tests/endpoints/roms/test_rom_sidecar_cache.py index 42178ca4a..d12cd8841 100644 --- a/backend/tests/endpoints/roms/test_rom_sidecar_cache.py +++ b/backend/tests/endpoints/roms/test_rom_sidecar_cache.py @@ -30,6 +30,7 @@ from typing import Any, cast import pytest from fastapi import status from fastapi.testclient import TestClient +from tests.factories import make_rom from endpoints.roms import ( build_unscoped_filter_values_cache_key, @@ -238,6 +239,31 @@ def test_unfiltered_request_still_reads_unscoped_char_index_cache( assert body["char_index"] == {"Z": 41} +@pytest.mark.parametrize( + ("params", "expected"), + [ + # Relevance leads, so the rows run in no letter order. + ({"search_term": "final fantasy"}, {}), + ({"search_term": "final fantasy", "order_by": "name"}, {"f": 0}), + # One word has no phrase to rank by, so the name order stands. + ({"search_term": "fantasy"}, {"f": 0}), + ], +) +def test_char_index_follows_whether_relevance_leads( + client: TestClient, + access_token: str, + platform: Platform, + params: dict[str, str], + expected: dict[str, int], +): + make_rom(platform, "Final Fantasy") + make_rom(platform, "Final Fantasy VII") + + body = _get_roms(client, access_token, **params) + + assert body["char_index"] == expected + + def _put_props( client: TestClient, access_token: str, diff --git a/frontend/src/locales/bg_BG/gallery.json b/frontend/src/locales/bg_BG/gallery.json index ecd006f26..53f82b5dc 100644 --- a/frontend/src/locales/bg_BG/gallery.json +++ b/frontend/src/locales/bg_BG/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Сортирай възходящо", "sort-by": "Сортирай по", "sort-descending": "Сортирай низходящо", + "sort-relevance": "Уместност", "view-flat": "Плосък изглед", "view-grid": "Решетка", "view-grouped": "Групирай по буква", diff --git a/frontend/src/locales/cs_CZ/gallery.json b/frontend/src/locales/cs_CZ/gallery.json index 896a006b1..a2913f924 100644 --- a/frontend/src/locales/cs_CZ/gallery.json +++ b/frontend/src/locales/cs_CZ/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Seřadit vzestupně", "sort-by": "Seřadit podle", "sort-descending": "Seřadit sestupně", + "sort-relevance": "Relevance", "view-flat": "Plochý pohled", "view-grid": "Mřížka", "view-grouped": "Seskupit podle písmene", diff --git a/frontend/src/locales/de_DE/gallery.json b/frontend/src/locales/de_DE/gallery.json index 42f2a6d62..812b5705b 100644 --- a/frontend/src/locales/de_DE/gallery.json +++ b/frontend/src/locales/de_DE/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Aufsteigend sortieren", "sort-by": "Sortieren nach", "sort-descending": "Absteigend sortieren", + "sort-relevance": "Relevanz", "view-flat": "Flache Ansicht", "view-grid": "Raster", "view-grouped": "Nach Buchstaben gruppieren", diff --git a/frontend/src/locales/en_GB/gallery.json b/frontend/src/locales/en_GB/gallery.json index 15049afb5..e8d4aab33 100644 --- a/frontend/src/locales/en_GB/gallery.json +++ b/frontend/src/locales/en_GB/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Sort ascending", "sort-by": "Sort by", "sort-descending": "Sort descending", + "sort-relevance": "Relevance", "view-flat": "Flat view", "view-grid": "Grid", "view-grouped": "Group by letter", diff --git a/frontend/src/locales/en_US/gallery.json b/frontend/src/locales/en_US/gallery.json index c6fb07df8..4189664a2 100644 --- a/frontend/src/locales/en_US/gallery.json +++ b/frontend/src/locales/en_US/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Sort ascending", "sort-by": "Sort by", "sort-descending": "Sort descending", + "sort-relevance": "Relevance", "view-flat": "Flat view", "view-grid": "Grid", "view-grouped": "Group by letter", diff --git a/frontend/src/locales/es_ES/gallery.json b/frontend/src/locales/es_ES/gallery.json index cc936096c..433046d5e 100644 --- a/frontend/src/locales/es_ES/gallery.json +++ b/frontend/src/locales/es_ES/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Orden ascendente", "sort-by": "Ordenar por", "sort-descending": "Orden descendente", + "sort-relevance": "Relevancia", "view-flat": "Vista plana", "view-grid": "Cuadrícula", "view-grouped": "Agrupar por letra", diff --git a/frontend/src/locales/fr_FR/gallery.json b/frontend/src/locales/fr_FR/gallery.json index dcaeffc53..21945f17f 100644 --- a/frontend/src/locales/fr_FR/gallery.json +++ b/frontend/src/locales/fr_FR/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Trier par ordre croissant", "sort-by": "Trier par", "sort-descending": "Trier par ordre décroissant", + "sort-relevance": "Pertinence", "view-flat": "Vue à plat", "view-grid": "Grille", "view-grouped": "Grouper par lettre", diff --git a/frontend/src/locales/hu_HU/gallery.json b/frontend/src/locales/hu_HU/gallery.json index 4b194f22d..aeede8ec5 100644 --- a/frontend/src/locales/hu_HU/gallery.json +++ b/frontend/src/locales/hu_HU/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Növekvő sorrend", "sort-by": "Rendezés szerint", "sort-descending": "Csökkenő sorrend", + "sort-relevance": "Relevancia", "view-flat": "Sima nézet", "view-grid": "Rács", "view-grouped": "Csoportosítás betű szerint", diff --git a/frontend/src/locales/it_IT/gallery.json b/frontend/src/locales/it_IT/gallery.json index 496398d1b..6956aa56e 100644 --- a/frontend/src/locales/it_IT/gallery.json +++ b/frontend/src/locales/it_IT/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Ordina in ordine crescente", "sort-by": "Ordina per", "sort-descending": "Ordina in ordine decrescente", + "sort-relevance": "Rilevanza", "view-flat": "Vista piatta", "view-grid": "Griglia", "view-grouped": "Raggruppa per lettera", diff --git a/frontend/src/locales/ja_JP/gallery.json b/frontend/src/locales/ja_JP/gallery.json index 995ec90a3..be050e41c 100644 --- a/frontend/src/locales/ja_JP/gallery.json +++ b/frontend/src/locales/ja_JP/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "昇順に並び替え", "sort-by": "並び替え基準", "sort-descending": "降順に並び替え", + "sort-relevance": "関連度", "view-flat": "フラット表示", "view-grid": "グリッド", "view-grouped": "文字でグループ化", diff --git a/frontend/src/locales/ko_KR/gallery.json b/frontend/src/locales/ko_KR/gallery.json index e56e8705b..440eb27c6 100644 --- a/frontend/src/locales/ko_KR/gallery.json +++ b/frontend/src/locales/ko_KR/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "오름차순 정렬", "sort-by": "정렬 기준", "sort-descending": "내림차순 정렬", + "sort-relevance": "관련성", "view-flat": "단일 보기", "view-grid": "그리드", "view-grouped": "글자별 그룹화", diff --git a/frontend/src/locales/pl_PL/gallery.json b/frontend/src/locales/pl_PL/gallery.json index dc2942502..6aa644e50 100644 --- a/frontend/src/locales/pl_PL/gallery.json +++ b/frontend/src/locales/pl_PL/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Sortuj rosnąco", "sort-by": "Sortuj według", "sort-descending": "Sortuj malejąco", + "sort-relevance": "Trafność", "view-flat": "Widok płaski", "view-grid": "Siatka", "view-grouped": "Grupuj według litery", diff --git a/frontend/src/locales/pt_BR/gallery.json b/frontend/src/locales/pt_BR/gallery.json index 83f1be7d1..9875d4b6b 100644 --- a/frontend/src/locales/pt_BR/gallery.json +++ b/frontend/src/locales/pt_BR/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Ordenar crescente", "sort-by": "Ordenar por", "sort-descending": "Ordenar decrescente", + "sort-relevance": "Relevância", "view-flat": "Visualização plana", "view-grid": "Grade", "view-grouped": "Agrupar por letra", diff --git a/frontend/src/locales/ro_RO/gallery.json b/frontend/src/locales/ro_RO/gallery.json index cade7d008..af19a97b9 100644 --- a/frontend/src/locales/ro_RO/gallery.json +++ b/frontend/src/locales/ro_RO/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Sortează crescător", "sort-by": "Sortează după", "sort-descending": "Sortează descrescător", + "sort-relevance": "Relevanță", "view-flat": "Vizualizare plată", "view-grid": "Grilă", "view-grouped": "Grupare după literă", diff --git a/frontend/src/locales/ru_RU/gallery.json b/frontend/src/locales/ru_RU/gallery.json index c6cbcd0a7..fd63e4785 100644 --- a/frontend/src/locales/ru_RU/gallery.json +++ b/frontend/src/locales/ru_RU/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Сортировать по возрастанию", "sort-by": "Сортировать по", "sort-descending": "Сортировать по убыванию", + "sort-relevance": "Релевантность", "view-flat": "Плоский вид", "view-grid": "Сетка", "view-grouped": "Группировать по буквам", diff --git a/frontend/src/locales/tr_TR/gallery.json b/frontend/src/locales/tr_TR/gallery.json index cfce3b7e6..1cdd0ae2c 100644 --- a/frontend/src/locales/tr_TR/gallery.json +++ b/frontend/src/locales/tr_TR/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "Artan sırala", "sort-by": "Sıralama ölçütü", "sort-descending": "Azalan sırala", + "sort-relevance": "İlgi düzeyi", "view-flat": "Düz görünüm", "view-grid": "Izgara", "view-grouped": "Harfe göre grupla", diff --git a/frontend/src/locales/zh_CN/gallery.json b/frontend/src/locales/zh_CN/gallery.json index d437b5788..d280e9db4 100644 --- a/frontend/src/locales/zh_CN/gallery.json +++ b/frontend/src/locales/zh_CN/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "升序排列", "sort-by": "排序方式", "sort-descending": "降序排列", + "sort-relevance": "相关性", "view-flat": "平铺视图", "view-grid": "网格", "view-grouped": "按字母分组", diff --git a/frontend/src/locales/zh_TW/gallery.json b/frontend/src/locales/zh_TW/gallery.json index 46453db41..43bb4fb07 100644 --- a/frontend/src/locales/zh_TW/gallery.json +++ b/frontend/src/locales/zh_TW/gallery.json @@ -32,6 +32,7 @@ "sort-ascending": "升冪排序", "sort-by": "排序方式", "sort-descending": "降冪排序", + "sort-relevance": "相關性", "view-flat": "平面檢視", "view-grid": "網格", "view-grouped": "依字母分組", diff --git a/frontend/src/v2/components/Gallery/GalleryShell.vue b/frontend/src/v2/components/Gallery/GalleryShell.vue index 6b58afcb0..02adc7400 100644 --- a/frontend/src/v2/components/Gallery/GalleryShell.vue +++ b/frontend/src/v2/components/Gallery/GalleryShell.vue @@ -81,6 +81,8 @@ import { useResponsiveColumns } from "@/v2/composables/useResponsiveColumns"; import { useVirtualScrollDebug } from "@/v2/composables/useVirtualScrollDebug"; import { useWebpSupport } from "@/v2/composables/useWebpSupport"; import storeGalleryRoms, { + DEFAULT_ORDER_BY, + type GalleryOrderKey, orderSupportsLetters, } from "@/v2/stores/galleryRoms"; import storeGallerySelection from "@/v2/stores/gallerySelection"; @@ -116,6 +118,9 @@ interface Props { * (every row shares the same platform); true on cross-platform views * (Search, Collection, Missing games) where the column carries info. */ showPlatformColumn?: boolean; + /** Sort applied while the URL names none. `null` orders by search + * relevance (Search). */ + defaultOrderBy?: GalleryOrderKey | null; } const props = withDefaults(defineProps(), { @@ -127,6 +132,7 @@ const props = withDefaults(defineProps(), { skeletonRowCount: 4, showPlatformsInFilter: true, showPlatformColumn: true, + defaultOrderBy: DEFAULT_ORDER_BY, }); defineSlots<{ @@ -138,7 +144,7 @@ defineSlots<{ }>(); useGalleryFilterUrl(); -useGalleryOrderUrl(); +useGalleryOrderUrl(props.defaultOrderBy); useGalleryViewModeUrl(); const { t } = useI18n(); @@ -309,9 +315,11 @@ const { groupBy, layout, toolbarPosition } = useGalleryMode(); // CSS grid `minmax(--r-card-art-w, 1fr)` stay in lock-step. const { xs, smAndDown } = useBreakpoint(); const sectionEl = ref(null); -// A jump to "M" means nothing when the gallery is sorted by size or date, so -// the letter affordances go away with the letters themselves. -const lettersSupported = computed(() => orderSupportsLetters(orderBy.value)); +// A jump to "M" means nothing unless the gallery is in letter order. +const lettersSupported = computed(() => { + const key = galleryRoms.effectiveOrderBy; + return key !== null && orderSupportsLetters(key); +}); const stripVisible = computed(() => !smAndDown.value && lettersSupported.value); const jumpMenuVisible = computed( () => smAndDown.value && lettersSupported.value, @@ -767,7 +775,7 @@ const { input: searchInput, setSearch } = useDebouncedSearch(searchTerm); // write the store; `useGalleryOrderUrl` mirrors it to the URL and the // watch below owns the refetch. const listSortKey = computed(() => { - const key = orderBy.value; + const key = galleryRoms.effectiveOrderBy; return isListSortKey(key) ? key : null; }); @@ -776,6 +784,11 @@ function onListSort(payload: { key: ListSortKey; dir: "asc" | "desc" }) { galleryRoms.setOrderDir(payload.dir); } +// Search's relevance has no sort key; the other views have no unsorted order. +const unsortedLabel = computed(() => + props.defaultOrderBy === null ? t("gallery.sort-relevance") : undefined, +); + // The toolbar's sort axes, matching the list column headers. const sortOptions = computed(() => getSortOptions(props.showPlatformColumn)); @@ -1037,6 +1050,8 @@ defineExpose({ :sort-dir="orderDir" :sort-key="listSortKey" :sort-key-items="sortOptions" + :unsorted-label="unsortedLabel" + :unsorted="galleryRoms.effectiveOrderBy === null" show-search :search="searchInput" :search-placeholder="searchPlaceholder" @@ -1079,7 +1094,10 @@ defineExpose({ :sort-key="listSortKey" :sort-dir="orderDir" :show-platform-column="showPlatformColumn" + :unsorted-label="unsortedLabel" + :unsorted="galleryRoms.effectiveOrderBy === null" @sort="onListSort" + @unsort="galleryRoms.setOrderBy(null)" /> @@ -1097,7 +1115,10 @@ defineExpose({ :sort-dir="orderDir" :show-platform-column="showPlatformColumn" aria-rowindex="1" + :unsorted-label="unsortedLabel" + :unsorted="galleryRoms.effectiveOrderBy === null" @sort="onListSort" + @unsort="galleryRoms.setOrderBy(null)" /> @@ -1224,6 +1245,8 @@ defineExpose({ :sort-dir="orderDir" :sort-key="listSortKey" :sort-key-items="sortOptions" + :unsorted-label="unsortedLabel" + :unsorted="galleryRoms.effectiveOrderBy === null" show-filter :filter-active-count="filterActiveCount" @update:group-by="groupBy = $event" diff --git a/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts b/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts index 6419d3e51..45b74f455 100644 --- a/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts +++ b/frontend/src/v2/components/Gallery/GalleryToolbar.test.ts @@ -143,6 +143,76 @@ describe("GalleryToolbar sort axis", () => { wrapper.unmount(); }); + it("offers the unsorted order and emits a null key for it", async () => { + const wrapper = mountWithSortOptions({ unsortedLabel: "Relevance" }); + + const relevance = wrapper + .findAllComponents({ name: "RMenuItem" }) + .find((item) => item.props("label") === "Relevance"); + expect(relevance?.props("variant")).toBe("default"); + await relevance!.trigger("click"); + + expect(wrapper.emitted("update:sortKey")).toEqual([[null]]); + wrapper.unmount(); + }); + + // Relevance has no direction, so the toggle would claim one it can't apply. + it("hides the direction toggle while the unsorted order is active", () => { + const sorted = mountWithSortOptions({ unsortedLabel: "Relevance" }); + const togglesWhenSorted = sorted.findAllComponents({ + name: "RSliderBtnGroup", + }).length; + sorted.unmount(); + + const wrapper = mountWithSortOptions({ + unsortedLabel: "Relevance", + sortKey: null, + unsorted: true, + }); + + expect(wrapper.findAllComponents({ name: "RSliderBtnGroup" })).toHaveLength( + togglesWhenSorted - 1, + ); + const relevance = wrapper + .findAllComponents({ name: "RMenuItem" }) + .find((item) => item.props("label") === "Relevance"); + expect(relevance?.props("variant")).toBe("active"); + expect(relevance?.props("icon")).toBe("mdi-check"); + wrapper.unmount(); + }); + + // A sort the selector doesn't offer (`last_played`) leaves no axis key, but + // it is still a sort. + it("ticks nothing and keeps the toggle for a sort it doesn't offer", () => { + const sorted = mountWithSortOptions({ unsortedLabel: "Relevance" }); + const togglesWhenSorted = sorted.findAllComponents({ + name: "RSliderBtnGroup", + }).length; + sorted.unmount(); + + const wrapper = mountWithSortOptions({ + unsortedLabel: "Relevance", + sortKey: null, + unsorted: false, + }); + + expect(wrapper.findAllComponents({ name: "RSliderBtnGroup" })).toHaveLength( + togglesWhenSorted, + ); + const ticked = wrapper + .findAllComponents({ name: "RMenuItem" }) + .filter( + (item) => + item.props("variant") === "active" && + (item.props("label") === "Relevance" || + SORT_OPTIONS.some( + (option) => option.label === item.props("label"), + )), + ); + expect(ticked).toHaveLength(0); + wrapper.unmount(); + }); + // List mode sorts through the column headers, so the toolbar's axis // control steps aside rather than offer a second, competing one. it("drops the control in list mode only", () => { diff --git a/frontend/src/v2/components/Gallery/GalleryToolbar.vue b/frontend/src/v2/components/Gallery/GalleryToolbar.vue index 85349d6e6..099c8d5a7 100644 --- a/frontend/src/v2/components/Gallery/GalleryToolbar.vue +++ b/frontend/src/v2/components/Gallery/GalleryToolbar.vue @@ -83,6 +83,11 @@ const props = withDefaults( /** Axes for the sort selector. Empty hides the control, as on index * views, which sort their tiles themselves. */ sortKeyItems?: readonly SortOption[]; + /** Offers the gallery's order without a sort key (Search's relevance) + * under this name; it has no direction, so the toggle hides under it. */ + unsortedLabel?: string; + /** Whether that order is the one applied. */ + unsorted?: boolean; /** Show the search field on the left. v-model:search controls its value. */ showSearch?: boolean; search?: string; @@ -112,6 +117,8 @@ const props = withDefaults( sortDir: "asc", sortKey: null, sortKeyItems: () => [], + unsortedLabel: undefined, + unsorted: false, showSearch: false, search: "", searchPlaceholder: "", @@ -126,7 +133,7 @@ const emit = defineEmits<{ (e: "update:groupBy", value: GroupByMode): void; (e: "update:layout", value: LayoutMode): void; (e: "update:sortDir", value: "asc" | "desc"): void; - (e: "update:sortKey", value: ListSortKey): void; + (e: "update:sortKey", value: ListSortKey | null): void; (e: "update:search", value: string): void; (e: "update:segmentFilter", payload: { key: string; value: string }): void; (e: "click:filter"): void; @@ -148,6 +155,7 @@ const groupByValue = computed(() => toValue(props.groupBy)); const layoutValue = computed(() => toValue(props.layout)); const sortDirValue = computed(() => toValue(props.sortDir)); const sortKeyValue = computed(() => toValue(props.sortKey)); +const unsorted = computed(() => !!props.unsortedLabel && props.unsorted); // List mode sorts from its own column header, so the toolbar's sort and // grouping controls step aside rather than sit there inert. const listMode = computed(() => layoutValue.value === "list"); @@ -239,7 +247,7 @@ function selectionMark(selected: boolean) { }; } -function setSortKey(value: ListSortKey) { +function setSortKey(value: ListSortKey | null) { emit("update:sortKey", value); } @@ -353,6 +361,12 @@ const { smAndUp } = useBreakpoint(); :aria-label="t('gallery.sort-by')" /> + ({ useBreakpoint: () => ({ smAndDown }), })); -function mountHeader() { +function mountHeader(props: Record = {}) { return mount(GameListHeader, { - props: { sortKey: "name", sortDir: "asc" }, + props: { sortKey: "name", sortDir: "asc", ...props }, global: { stubs: { RIcon: true, ListSortMenu: true } }, }); } +function nameHeader(wrapper: ReturnType) { + const header = wrapper + .findAll("[role=columnheader]") + .find((h) => h.attributes("aria-sort") === "descending"); + if (!header) throw new Error("no descending column header"); + return header.find("button"); +} + describe("GameListHeader", () => { beforeEach(() => { setActivePinia(createPinia()); @@ -51,6 +59,27 @@ describe("GameListHeader", () => { } }); + it("returns a descending column to the unsorted order when one is offered", async () => { + const wrapper = mountHeader({ + sortDir: "desc", + unsortedLabel: "gallery.sort-relevance", + }); + + await nameHeader(wrapper).trigger("click"); + + expect(wrapper.emitted("unsort")).toHaveLength(1); + expect(wrapper.emitted("sort")).toBeUndefined(); + }); + + it("flips a descending column back to ascending otherwise", async () => { + const wrapper = mountHeader({ sortDir: "desc" }); + + await nameHeader(wrapper).trigger("click"); + + expect(wrapper.emitted("sort")).toEqual([[{ key: "name", dir: "asc" }]]); + expect(wrapper.emitted("unsort")).toBeUndefined(); + }); + it("is a plain toolbar on phones, outside any grid", () => { smAndDown.value = true; const wrapper = mountHeader(); diff --git a/frontend/src/v2/components/Gallery/GameListHeader.vue b/frontend/src/v2/components/Gallery/GameListHeader.vue index 5a8344bcf..12416c66f 100644 --- a/frontend/src/v2/components/Gallery/GameListHeader.vue +++ b/frontend/src/v2/components/Gallery/GameListHeader.vue @@ -4,7 +4,8 @@ // Layout: a single CSS-grid div sharing `LIST_GRID_TEMPLATE` with every // `GameListRow` underneath, so columns line up regardless of viewport. // Click on a sortable column toggles asc → desc → asc (single-key sort, -// matching the rest of the gallery surface). +// matching the rest of the gallery surface), or asc → desc → unsorted when +// the gallery has an order of its own to fall back to. // // Sticky positioning is owned by the parent (`GalleryShell` pins this // below the toolbar at `top: --r-v2-shell-toolbar-h`). The header @@ -36,14 +37,22 @@ interface Props { * name on `GameListRow` + `GameListSkeletonRow` so all three stay in * lockstep. */ showPlatformColumn?: boolean; + /** Names the gallery's order without a sort key (Search's relevance), and + * lets a third click on a column return to it. */ + unsortedLabel?: string; + /** Whether that order is the one applied. */ + unsorted?: boolean; } const props = withDefaults(defineProps(), { showPlatformColumn: true, + unsortedLabel: undefined, + unsorted: false, }); const emit = defineEmits<{ (e: "sort", payload: { key: ListSortKey; dir: "asc" | "desc" }): void; + (e: "unsort"): void; }>(); const { t } = useI18n(); @@ -82,6 +91,14 @@ function ariaSort(col: ListColumn) { function handleClick(col: ListColumn) { if (!isSortableColumn(col)) return; + if ( + props.unsortedLabel && + props.sortKey === col.key && + props.sortDir === "desc" + ) { + emit("unsort"); + return; + } // Toggle direction when re-clicking the active column; otherwise start the // new one ascending, like every other sortable table in the app. const nextDir: "asc" | "desc" = @@ -113,7 +130,10 @@ function handleClick(col: ListColumn) { :options="sortOptions" :sort-key="sortKey" :sort-dir="sortDir" + :unsorted-label="unsortedLabel" + :unsorted="unsorted" @sort="emit('sort', $event)" + @unsort="emit('unsort')" /> diff --git a/frontend/src/v2/components/Gallery/listColumns.ts b/frontend/src/v2/components/Gallery/listColumns.ts index 0b5f3430e..43ccd5fd8 100644 --- a/frontend/src/v2/components/Gallery/listColumns.ts +++ b/frontend/src/v2/components/Gallery/listColumns.ts @@ -275,6 +275,6 @@ const LIST_SORT_KEYS: ReadonlySet = new Set( ); /** Whether the gallery's current order key is one list mode can sort by. */ -export function isListSortKey(key: string): key is ListSortKey { - return LIST_SORT_KEYS.has(key); +export function isListSortKey(key: string | null): key is ListSortKey { + return key !== null && LIST_SORT_KEYS.has(key); } diff --git a/frontend/src/v2/components/shared/ListSortMenu.vue b/frontend/src/v2/components/shared/ListSortMenu.vue index dae63df10..48ccc9e88 100644 --- a/frontend/src/v2/components/shared/ListSortMenu.vue +++ b/frontend/src/v2/components/shared/ListSortMenu.vue @@ -11,10 +11,15 @@ const props = defineProps<{ /** Null when the list's order is one the columns don't carry. */ sortKey: K | null; sortDir: "asc" | "desc"; + /** Offers the list's order without a sort key (Search's relevance) under this name. */ + unsortedLabel?: string; + /** Whether that order is the one applied. */ + unsorted?: boolean; }>(); const emit = defineEmits<{ (e: "sort", payload: { key: K; dir: "asc" | "desc" }): void; + (e: "unsort"): void; }>(); const { t } = useI18n(); @@ -26,6 +31,7 @@ const dirIcon = computed(() => const label = computed( () => props.options.find((option) => option.key === props.sortKey)?.label ?? + (props.unsorted ? props.unsortedLabel : undefined) ?? t("gallery.sort-by"), ); @@ -43,9 +49,20 @@ function pick(key: K) { + " }; -const Host = { - setup() { - useGalleryOrderUrl(); - }, - template: "
", -}; - -async function mountAt(router: Router, path: string) { +async function mountAt( + router: Router, + path: string, + defaultOrderBy: GalleryOrderKey | null = DEFAULT_ORDER_BY, +) { await router.push(path); await router.isReady(); + const Host = { + setup() { + useGalleryOrderUrl(defaultOrderBy); + }, + template: "
", + }; const wrapper = mount(Host, { global: { plugins: [router] } }); await nextTick(); return wrapper; @@ -33,6 +39,7 @@ function makeRouter() { history: createMemoryHistory(), routes: [ { path: "/platform/:platform", name: "platform", component: Blank }, + { path: "/search", name: "search", component: Blank }, ], }); } @@ -143,6 +150,48 @@ describe("useGalleryOrderUrl", () => { }); }); +describe("useGalleryOrderUrl with a relevance default", () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + const mountSearch = (router: Router, path: string) => + mountAt(router, path, null); + + it("leaves the sort unset when the URL names none", async () => { + const gallery = storeGalleryRoms(); + gallery.setOrderBy("created_at"); + + const router = makeRouter(); + await mountSearch(router, "/search?search=final+fantasy+7"); + + expect(gallery.orderBy).toBeNull(); + }); + + it("keeps a picked title sort in the query", async () => { + const router = makeRouter(); + await mountSearch(router, "/search?search=zelda"); + const gallery = storeGalleryRoms(); + + gallery.setOrderBy("name"); + await flushQueryWrite(); + + expect(router.currentRoute.value.query.orderBy).toBe("name"); + }); + + it("drops the param when the sort returns to relevance", async () => { + const router = makeRouter(); + await mountSearch(router, "/search?search=zelda&orderBy=name"); + const gallery = storeGalleryRoms(); + expect(gallery.orderBy).toBe("name"); + + gallery.setOrderBy(null); + await flushQueryWrite(); + + expect(router.currentRoute.value.query.orderBy).toBeUndefined(); + }); +}); + // `main.ts` mounts without awaiting `router.isReady()`, so setup-only // hydration holds solely because RouterView withholds the matched component // until the initial navigation resolves. @@ -152,10 +201,10 @@ describe("useGalleryOrderUrl on a cold load", () => { }); it("sees the URL in setup() without awaiting router.isReady", async () => { - const seenAtSetup: string[] = []; + const seenAtSetup: (string | null)[] = []; const GalleryView = { setup() { - useGalleryOrderUrl(); + useGalleryOrderUrl(DEFAULT_ORDER_BY); seenAtSetup.push(storeGalleryRoms().orderBy); return () => h("div"); }, diff --git a/frontend/src/v2/composables/useGalleryOrderUrl/index.ts b/frontend/src/v2/composables/useGalleryOrderUrl/index.ts index 50cde2b5b..5e6d55fa0 100644 --- a/frontend/src/v2/composables/useGalleryOrderUrl/index.ts +++ b/frontend/src/v2/composables/useGalleryOrderUrl/index.ts @@ -1,8 +1,11 @@ // useGalleryOrderUrl - bookmarkable gallery sort via URL query params. // -// ?orderBy=fs_size_bytes (omitted at "name", the default) +// ?orderBy=fs_size_bytes (omitted at the view's default) // ?orderDir=desc (omitted at "asc", the default) // +// A `null` default (Search) leaves the order to the backend, which ranks +// by relevance until the user picks a column. +// // An unrecognised or absent param resolves to the default, so a link // without them lands on the same sort whatever the last gallery left in // the store. Hydration runs during setup, before the shell registers its @@ -11,7 +14,6 @@ import { storeToRefs } from "pinia"; import { watch } from "vue"; import { useRoute, useRouter } from "vue-router"; import storeGalleryRoms, { - DEFAULT_ORDER_BY, DEFAULT_ORDER_DIR, type GalleryOrderDir, type GalleryOrderKey, @@ -20,10 +22,13 @@ import storeGalleryRoms, { } from "@/v2/stores/galleryRoms"; import { syncQueryParam } from "@/v2/utils/routeQuery"; -function parseOrderBy(value: unknown): GalleryOrderKey { +function parseOrderBy( + value: unknown, + fallback: GalleryOrderKey | null, +): GalleryOrderKey | null { return typeof value === "string" && isGalleryOrderKey(value) ? value - : DEFAULT_ORDER_BY; + : fallback; } function parseOrderDir(value: unknown): GalleryOrderDir { @@ -32,14 +37,14 @@ function parseOrderDir(value: unknown): GalleryOrderDir { : DEFAULT_ORDER_DIR; } -export function useGalleryOrderUrl() { +export function useGalleryOrderUrl(defaultOrderBy: GalleryOrderKey | null) { const route = useRoute(); const router = useRouter(); const galleryRoms = storeGalleryRoms(); const { orderBy, orderDir } = storeToRefs(galleryRoms); function applyFromUrl() { - const by = parseOrderBy(route.query.orderBy); + const by = parseOrderBy(route.query.orderBy, defaultOrderBy); const dir = parseOrderDir(route.query.orderDir); if (by !== orderBy.value) galleryRoms.setOrderBy(by); if (dir !== orderDir.value) galleryRoms.setOrderDir(dir); @@ -51,7 +56,11 @@ export function useGalleryOrderUrl() { // Drop the param when the value is the default, which keeps URLs clean. watch([orderBy, orderDir], ([by, dir]) => { - syncQueryParam(router, "orderBy", by === DEFAULT_ORDER_BY ? undefined : by); + syncQueryParam( + router, + "orderBy", + by === defaultOrderBy || by === null ? undefined : by, + ); syncQueryParam( router, "orderDir", diff --git a/frontend/src/v2/composables/useRomSync/index.test.ts b/frontend/src/v2/composables/useRomSync/index.test.ts index 2339b8d0c..9dd451409 100644 --- a/frontend/src/v2/composables/useRomSync/index.test.ts +++ b/frontend/src/v2/composables/useRomSync/index.test.ts @@ -124,6 +124,32 @@ describe("useRomSync", () => { expect(getRoms).not.toHaveBeenCalled(); }); + it("applyRomWrite refetches a search ranked by relevance", () => { + const gallery = seedGallery(makeRom({ name_sort_key: "chrono trigger" })); + gallery.setOrderBy(null); + gallery.relevanceLed = true; + + useRomSync().applyRomWrite( + makeRom({ name_sort_key: "chrono trigger", fs_name: "renamed.sfc" }), + ); + + expect(gallery.byPosition.size).toBe(0); + expect(getRoms).toHaveBeenCalled(); + }); + + it("applyRomWrite reads an unset sort the backend kept in name order as the name", () => { + const gallery = seedGallery(makeRom({ name_sort_key: "chrono trigger" })); + gallery.setOrderBy(null); + gallery.relevanceLed = false; + + useRomSync().applyRomWrite( + makeRom({ name_sort_key: "chrono trigger", summary: "edited" }), + ); + + expect(gallery.byPosition.size).toBe(1); + expect(getRoms).not.toHaveBeenCalled(); + }); + it("applyRomWrite keeps an unfiltered gallery when nothing it orders by moved", () => { const gallery = seedGallery(makeRom({ name_sort_key: "chrono trigger" })); gallery.setOrderBy("name"); diff --git a/frontend/src/v2/composables/useRomSync/index.ts b/frontend/src/v2/composables/useRomSync/index.ts index 0b3cf3bb0..6e4062ca5 100644 --- a/frontend/src/v2/composables/useRomSync/index.ts +++ b/frontend/src/v2/composables/useRomSync/index.ts @@ -95,8 +95,11 @@ export function useRomSync() { * case there's no row on screen to reorder. */ function sortValueChanged(previous: SimpleRom | null, next: SimpleRom) { if (!previous) return false; - const resolve = SORT_VALUE[galleryRomsStore.orderBy]; - return resolve(previous) !== resolve(next); + // Relevance also weighs the filename and search aliases, which the row + // doesn't carry, so only the server can place it. + const key = galleryRomsStore.effectiveOrderBy; + if (key === null) return true; + return SORT_VALUE[key](previous) !== SORT_VALUE[key](next); } /** Sync a deliberate metadata write (the edit / match dialogs) and refetch diff --git a/frontend/src/v2/stores/galleryRoms.test.ts b/frontend/src/v2/stores/galleryRoms.test.ts index 1a76e9085..10713b92a 100644 --- a/frontend/src/v2/stores/galleryRoms.test.ts +++ b/frontend/src/v2/stores/galleryRoms.test.ts @@ -72,6 +72,17 @@ describe("galleryRoms windowed fetch", () => { vi.unstubAllGlobals(); }); + // The backend ranks a search by relevance only when no sort key is sent. + it("sends an empty sort key when no sort is set", () => { + getRoms.mockImplementation(() => Promise.resolve(windowResponse())); + const store = storeGalleryRoms(); + store.setOrderBy(null); + + store.syncVisibleWindows([0]); + + expect(getRoms.mock.calls[0][0].orderBy).toBe(""); + }); + it("collapses many visible positions into one request per 72-item window", async () => { getRoms.mockImplementation(() => Promise.resolve(windowResponse())); const store = storeGalleryRoms(); @@ -477,6 +488,71 @@ describe("galleryRoms length filter", () => { }); }); +describe("galleryRoms relevance order", () => { + beforeEach(() => { + setActivePinia(createPinia()); + getRoms.mockReset(); + vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => { + cb(0); + return 0; + }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + async function answeredWith(charIndex: Record, total = 5) { + getRoms.mockResolvedValue({ + data: { total, items: [], char_index: charIndex, rom_id_index: [] }, + }); + setActivePinia(createPinia()); + const store = storeGalleryRoms(); + store.setOrderBy(null); + await store.fetchInitialMetadata(); + return store; + } + + it("reads an unset sort answered without letters as relevance", async () => { + const store = await answeredWith({}); + + expect(store.effectiveOrderBy).toBeNull(); + }); + + it("reads an unset sort answered with letters as the name order", async () => { + const store = await answeredWith({ a: 0 }); + + expect(store.effectiveOrderBy).toBe("name"); + }); + + it("keeps the answer through a refetch, so the controls don't flicker", async () => { + const store = await answeredWith({}); + + store.invalidateWindows(); + + expect(store.effectiveOrderBy).toBeNull(); + }); + + it("reads an empty result or a picked sort as no relevance", async () => { + expect((await answeredWith({}, 0)).effectiveOrderBy).toBe("name"); + + const sorted = await answeredWith({}); + sorted.setOrderBy("fs_size_bytes"); + expect(sorted.effectiveOrderBy).toBe("fs_size_bytes"); + }); + + it("clears the direction along with the sort key", () => { + const store = storeGalleryRoms(); + store.setOrderBy("name"); + store.setOrderDir("desc"); + + store.setOrderBy(null); + + expect(store.orderBy).toBeNull(); + expect(store.orderDir).toBe("asc"); + }); +}); + describe("orderSupportsLetters", () => { // The backend indexes first letters off a text column only, so every other // order answers with an empty char_index. Spelling out every key means a new diff --git a/frontend/src/v2/stores/galleryRoms.ts b/frontend/src/v2/stores/galleryRoms.ts index 0e19a6025..5e247efff 100644 --- a/frontend/src/v2/stores/galleryRoms.ts +++ b/frontend/src/v2/stores/galleryRoms.ts @@ -247,9 +247,13 @@ interface State { metadataLoaded: boolean; // True while a whole-result select-all fetch is in flight. selectingAll: boolean; + // Whether the last answer to an unset sort came back in relevance order, + // which the backend signals with no letter positions. Kept across refetches. + relevanceLed: boolean; // Order params: gallery-list scoped (separate from v1's localStorage - // keys so v1/v2 don't fight over the same value). - orderBy: GalleryOrderKey; + // keys so v1/v2 don't fight over the same value). `null` leaves the + // order to the backend, which ranks a search by relevance. + orderBy: GalleryOrderKey | null; orderDir: GalleryOrderDir; } @@ -269,6 +273,7 @@ const defaults = (): State => ({ initialFetching: false, metadataLoaded: false, selectingAll: false, + relevanceLed: false, orderBy: DEFAULT_ORDER_BY, orderDir: DEFAULT_ORDER_DIR, }); @@ -291,6 +296,10 @@ export default defineStore("v2GalleryRoms", { ), /** True when at least the first window has loaded. */ hasInitial: (state) => state.loadedWindows.size > 0, + /** The order the backend applied: null for relevance, and an unset sort + * it kept by name reads as name. */ + effectiveOrderBy: (state): GalleryOrderKey | null => + state.orderBy ?? (state.relevanceLed ? null : DEFAULT_ORDER_BY), /** The full ordered id list of the current filtered result, or null * while it is unknown (off the gallery view, or bootstrap pending). */ filteredRomIds(): number[] | null { @@ -312,8 +321,10 @@ export default defineStore("v2GalleryRoms", { this.currentSmartCollection = collection; }, - setOrderBy(key: GalleryOrderKey) { + /** An unset sort orders by relevance, which has no direction. */ + setOrderBy(key: GalleryOrderKey | null) { this.orderBy = key; + if (key === null) this.orderDir = DEFAULT_ORDER_DIR; }, setOrderDir(dir: GalleryOrderDir) { this.orderDir = dir; @@ -356,6 +367,7 @@ export default defineStore("v2GalleryRoms", { this.initialFetching = false; this.metadataLoaded = false; this.selectingAll = false; + this.relevanceLed = false; }, /** Drop the loaded windows but keep the gallery context. Used when @@ -399,7 +411,7 @@ export default defineStore("v2GalleryRoms", { smartCollectionId: this.currentSmartCollection?.id ?? null, limit: WINDOW_SIZE, offset, - orderBy: this.orderBy, + orderBy: this.orderBy ?? "", orderDir: this.orderDir, groupByMetaId: this._shouldGroupRoms() && this.onGalleryView, filterMatched: galleryFilter.filterMatched, @@ -466,6 +478,10 @@ export default defineStore("v2GalleryRoms", { // guards with `withAggregations`). if (sidecars.withCharIndex !== false && data.char_index) { this.charIndex = data.char_index; + this.relevanceLed = + this.orderBy === null && + this.total > 0 && + Object.keys(data.char_index).length === 0; } if (sidecars.withRomIdIndex !== false && data.rom_id_index) { this.romIdIndex = data.rom_id_index; diff --git a/frontend/src/v2/views/Gallery/Search.vue b/frontend/src/v2/views/Gallery/Search.vue index 51c086440..a969c05a2 100644 --- a/frontend/src/v2/views/Gallery/Search.vue +++ b/frontend/src/v2/views/Gallery/Search.vue @@ -46,6 +46,7 @@ onMounted(async () => { :empty-message="t('rom.no-games-match')" empty-icon="mdi-magnify-close" :skeleton-row-count="4" + :default-order-by="null" >