feat(search): Order v2 search results by relevance until a sort is picked (#4995)

* Order v2 search results by relevance until a sort is picked

The Search page fell back to the gallery-wide title sort whenever the URL
named none, so the backend only used search relevance to break ties
between identical titles. Search now sends an empty order_by by default,
letting relevance lead; clicking a column still sorts by it and lands in
the URL as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready step 2 (code-review): fix relevance-order edge cases

The backend now decides whether relevance leads and returns an empty
char_index when it does, so single-word searches (still name-ordered)
keep the A-Z strip and letter grouping, and multi-word searches get no
letter headers over rows that are not in letter order. A write under a
relevance-ordered search refetches, since the row lacks the filename and
aliases relevance ranks on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready step 3 (simplify): drop duplicated defaults and test setup

Gallery order clauses check order_by directly again, since the phrases
are already known there; useGalleryOrderUrl takes its default from the
caller only; the default key comes from DEFAULT_ORDER_BY in useRomSync;
and the new tests reuse the existing setup and mount helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Offer Relevance as a sort on Search and read it off the backend

Search's sort menu (grid toolbar and the compact list header) now lists
Relevance, and a third click on a desktop column header returns to it,
so the default order is reachable again after picking a column. The
direction toggle hides under relevance, which has no direction.

useRomSync's refetch now follows the backend's own signal for a
relevance order (an unset sort answered without letter positions)
instead of treating every search as one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Check the Relevance sort entry when it is active

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Show the order the backend applied in Search's sort controls

An unset sort the backend still answered by name (an empty or one-word
search) now reads as Title in the sort controls, with its direction
toggle, rather than as Relevance. The store records whether the last
answer led with relevance and keeps it through refetches, so the controls
don't flicker while a search reloads. Picking Relevance from the toolbar
now also resets the direction, as the list header's third click does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* pr-ready simplify: read the applied order from effectiveOrderBy

- The letter strip reads `effectiveOrderBy` instead of re-checking
  `charIndex`, which also stops it vanishing during every refetch of a
  relevance-ordered search.
- `useRomSync` reads `effectiveOrderBy`, so `relevanceLeads` goes.
- `setOrderBy(null)` resets the direction itself, so `clearOrder` and
  the shell's toolbar handler go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

* Tell the sort controls whether relevance is applied

The controls read a null sort key as "unsorted", but the shell also
passes null for a gallery key no column carries, so
`/search?orderBy=last_played` ticked Relevance and hid the direction
toggle. The toolbar, list header and phone sort menu now take an
explicit `unsorted` flag from the store's `effectiveOrderBy`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015iCApu4gYrGBWDX8JD9JH6

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sam Dornan
2026-10-01 16:56:36 -04:00
committed by GitHub
parent 25ee88e5dc
commit 4080cee68e
35 changed files with 466 additions and 52 deletions

View File

@@ -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,

View File

@@ -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,
*,

View File

@@ -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,

View File

@@ -32,6 +32,7 @@
"sort-ascending": "Сортирай възходящо",
"sort-by": "Сортирай по",
"sort-descending": "Сортирай низходящо",
"sort-relevance": "Уместност",
"view-flat": "Плосък изглед",
"view-grid": "Решетка",
"view-grouped": "Групирай по буква",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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",

View File

@@ -32,6 +32,7 @@
"sort-ascending": "昇順に並び替え",
"sort-by": "並び替え基準",
"sort-descending": "降順に並び替え",
"sort-relevance": "関連度",
"view-flat": "フラット表示",
"view-grid": "グリッド",
"view-grouped": "文字でグループ化",

View File

@@ -32,6 +32,7 @@
"sort-ascending": "오름차순 정렬",
"sort-by": "정렬 기준",
"sort-descending": "내림차순 정렬",
"sort-relevance": "관련성",
"view-flat": "단일 보기",
"view-grid": "그리드",
"view-grouped": "글자별 그룹화",

View File

@@ -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",

View File

@@ -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",

View File

@@ -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ă",

View File

@@ -32,6 +32,7 @@
"sort-ascending": "Сортировать по возрастанию",
"sort-by": "Сортировать по",
"sort-descending": "Сортировать по убыванию",
"sort-relevance": "Релевантность",
"view-flat": "Плоский вид",
"view-grid": "Сетка",
"view-grouped": "Группировать по буквам",

View File

@@ -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",

View File

@@ -32,6 +32,7 @@
"sort-ascending": "升序排列",
"sort-by": "排序方式",
"sort-descending": "降序排列",
"sort-relevance": "相关性",
"view-flat": "平铺视图",
"view-grid": "网格",
"view-grouped": "按字母分组",

View File

@@ -32,6 +32,7 @@
"sort-ascending": "升冪排序",
"sort-by": "排序方式",
"sort-descending": "降冪排序",
"sort-relevance": "相關性",
"view-flat": "平面檢視",
"view-grid": "網格",
"view-grouped": "依字母分組",

View File

@@ -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<Props>(), {
@@ -127,6 +132,7 @@ const props = withDefaults(defineProps<Props>(), {
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<HTMLElement | null>(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<ListSortKey | null>(() => {
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)"
/>
</template>
</template>
@@ -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)"
/>
</template>
@@ -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"

View File

@@ -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", () => {

View File

@@ -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')"
/>
</template>
<RMenuItem
v-if="unsortedLabel"
:label="unsortedLabel"
v-bind="selectionMark(unsorted)"
@click="setSortKey(null)"
/>
<RMenuItem
v-for="item in sortKeyItems"
:key="item.key"
@@ -363,6 +377,7 @@ const { smAndUp } = useBreakpoint();
</RMenu>
<RSliderBtnGroup
v-if="!unsorted"
:model-value="sortDirValue"
:items="sortDirItems"
variant="segmented"
@@ -425,6 +440,12 @@ const { smAndUp } = useBreakpoint();
<RDivider />
</template>
<template v-if="!listMode">
<RMenuItem
v-if="unsortedLabel && sortKeyItems.length > 0"
:label="unsortedLabel"
v-bind="selectionMark(unsorted)"
@click="setSortKey(null)"
/>
<RMenuItem
v-for="item in sortKeyItems"
:key="item.key"
@@ -433,19 +454,21 @@ const { smAndUp } = useBreakpoint();
@click="setSortKey(item.key)"
/>
<RDivider v-if="sortKeyItems.length > 0" />
<RMenuItem
:label="t('gallery.sort-ascending')"
icon="mdi-sort-ascending"
:variant="sortDirValue === 'asc' ? 'active' : 'default'"
@click="setSortDir('asc')"
/>
<RMenuItem
:label="t('gallery.sort-descending')"
icon="mdi-sort-descending"
:variant="sortDirValue === 'desc' ? 'active' : 'default'"
@click="setSortDir('desc')"
/>
<RDivider />
<template v-if="!unsorted">
<RMenuItem
:label="t('gallery.sort-ascending')"
icon="mdi-sort-ascending"
:variant="sortDirValue === 'asc' ? 'active' : 'default'"
@click="setSortDir('asc')"
/>
<RMenuItem
:label="t('gallery.sort-descending')"
icon="mdi-sort-descending"
:variant="sortDirValue === 'desc' ? 'active' : 'default'"
@click="setSortDir('desc')"
/>
<RDivider />
</template>
</template>
<RMenuItem
:label="t('gallery.view-grid')"

View File

@@ -13,13 +13,21 @@ vi.mock("@/v2/composables/useBreakpoint", () => ({
useBreakpoint: () => ({ smAndDown }),
}));
function mountHeader() {
function mountHeader(props: Record<string, unknown> = {}) {
return mount(GameListHeader, {
props: { sortKey: "name", sortDir: "asc" },
props: { sortKey: "name", sortDir: "asc", ...props },
global: { stubs: { RIcon: true, ListSortMenu: true } },
});
}
function nameHeader(wrapper: ReturnType<typeof mountHeader>) {
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();

View File

@@ -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<Props>(), {
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')"
/>
</div>

View File

@@ -275,6 +275,6 @@ const LIST_SORT_KEYS: ReadonlySet<string> = new Set<string>(
);
/** 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);
}

View File

@@ -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) {
<template #activator="{ props: activatorProps }">
<button v-bind="activatorProps" type="button" class="list-sort-menu">
<span class="list-sort-menu__label">{{ label }}</span>
<RIcon :icon="dirIcon" size="14" class="list-sort-menu__icon" />
<RIcon
v-if="!unsorted || !unsortedLabel"
:icon="dirIcon"
size="14"
class="list-sort-menu__icon"
/>
</button>
</template>
<RMenuItem
v-if="unsortedLabel"
:label="unsortedLabel"
:variant="unsorted ? 'active' : 'default'"
@click="emit('unsort')"
/>
<RMenuItem
v-for="option in options"
:key="option.key"

View File

@@ -8,21 +8,27 @@ import {
type Router,
RouterView,
} from "vue-router";
import storeGalleryRoms from "@/v2/stores/galleryRoms";
import storeGalleryRoms, {
DEFAULT_ORDER_BY,
type GalleryOrderKey,
} from "@/v2/stores/galleryRoms";
import { useGalleryOrderUrl } from "./index";
const Blank = { template: "<div />" };
const Host = {
setup() {
useGalleryOrderUrl();
},
template: "<div />",
};
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: "<div />",
};
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");
},

View File

@@ -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",

View File

@@ -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");

View File

@@ -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

View File

@@ -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<string, number>, 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

View File

@@ -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;

View File

@@ -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"
>
<!-- HEADER (Section 1): title + result-count chip. The shell
auto-measures this slot; no need to declare a height. -->