feat(platforms): facet filters and a group-by menu on the platforms index (#5434)

This commit is contained in:
Sam Dornan
2026-11-01 09:28:17 -06:00
committed by GitHub
parent f6002a76a3
commit 63d9a39656
26 changed files with 879 additions and 14 deletions

View File

@@ -227,3 +227,47 @@ describe("GalleryToolbar sort axis", () => {
wrapper.unmount();
});
});
describe("GalleryToolbar group-by control", () => {
const MANY_MODES = [
{ id: "none", icon: "mdi-view-agenda-outline", title: "Flat view" },
{
id: "letter",
icon: "mdi-alphabetical-variant",
title: "Group by letter",
},
{ id: "family", icon: "mdi-family-tree", title: "Group by family" },
];
it("keeps the segmented slider for the default two modes", () => {
const wrapper = mountToolbar({}, RMenuPassthrough);
expect(
wrapper
.findAllComponents({ name: "RSegmentedControl" })
.some((c) => c.props("items")?.length === 2),
).toBe(true);
wrapper.unmount();
});
it("lists more than two modes in a labelled menu with the active one checked", () => {
const wrapper = mountToolbar(
{ groupBy: "family", groupByItems: MANY_MODES },
RMenuPassthrough,
);
expect(
wrapper
.findAllComponents({ name: "RSegmentedControl" })
.some((c) => c.props("items") === MANY_MODES),
).toBe(false);
const family = wrapper
.findAllComponents({ name: "RMenuItem" })
.filter((item) => item.props("label") === "Group by family");
expect(family.length).toBeGreaterThan(0);
expect(family.some((item) => item.props("variant") === "active")).toBe(
true,
);
wrapper.unmount();
});
});

View File

@@ -228,6 +228,14 @@ const autofocusSearchField = computed(
shouldAutofocusSearch(),
);
// Two modes fit a segmented slider; more read better as a labelled menu.
const groupByAsMenu = computed(() => effectiveGroupByItems.value.length > 2);
const activeGroupByIcon = computed(
() =>
effectiveGroupByItems.value.find((i) => i.id === groupByValue.value)
?.icon ?? "mdi-format-list-group",
);
function setGroupBy(value: GroupByMode) {
emit("update:groupBy", value);
}
@@ -335,13 +343,37 @@ const { smAndUp } = useBreakpoint();
<!-- Grouping and sort: list mode sorts from its column header instead. -->
<template v-if="smAndUp && !listMode">
<RSegmentedControl
v-if="showGroupBy"
v-if="showGroupBy && !groupByAsMenu"
:model-value="groupByValue"
:items="effectiveGroupByItems"
variant="segmented"
:aria-label="t('settings.platforms-drawer-group-by')"
@update:model-value="setGroupBy"
/>
<RMenu
v-else-if="showGroupBy"
location="bottom end"
:offset="8"
width="220px"
>
<template #activator="{ props: activatorProps }">
<RBtn
v-bind="activatorProps"
variant="outlined"
surface
:icon="activeGroupByIcon"
rounded="circle"
:aria-label="t('settings.platforms-drawer-group-by')"
/>
</template>
<RMenuItem
v-for="item in effectiveGroupByItems"
:key="item.id"
:label="item.label ?? item.title ?? item.ariaLabel ?? item.id"
v-bind="selectionMark(groupByValue === item.id)"
@click="setGroupBy(item.id)"
/>
</RMenu>
<!-- A menu, not a slider: too many axes for the segmented pattern
the neighbouring clusters use. -->

View File

@@ -0,0 +1,122 @@
<script setup lang="ts">
// PlatformFilterDrawer: the Platforms index facets, laid out like the ROM
// gallery's FilterDrawer. The view owns the URL-backed selection and counts.
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { RBtn, RDrawer, RIcon, RSelect, RTag } from "@/lib";
import type { FacetOption, PlatformFacetKey } from "@/utils/platformFacets";
defineOptions({ inheritAttrs: false });
export interface PlatformFacet {
key: PlatformFacetKey;
label: string;
icon: string;
options: FacetOption[];
selected: readonly string[];
}
interface Props {
modelValue: boolean;
facets: PlatformFacet[];
}
const props = defineProps<Props>();
const emit = defineEmits<{
(e: "update:modelValue", value: boolean): void;
(e: "update", payload: { key: PlatformFacetKey; values: string[] }): void;
(e: "clear"): void;
}>();
const { t } = useI18n();
// A long list (families on a big library) is easier to scan with a filter.
const SEARCHABLE_FROM = 8;
const activeCount = computed(
() => props.facets.filter((f) => f.selected.length > 0).length,
);
const optionTitle = (o: FacetOption) => `${o.label} (${o.count})`;
</script>
<template>
<RDrawer
v-bind="$attrs"
:model-value="modelValue"
side="right"
:width="440"
icon="mdi-filter-variant"
hide-close
@update:model-value="(v) => emit('update:modelValue', v)"
>
<template #header>
<span>{{ t("platform.filters") }}</span>
<RTag v-if="activeCount > 0" tone="brand" size="x-small">
{{ activeCount }}
</RTag>
</template>
<div class="r-pfd__rows">
<RSelect
v-for="f in facets"
:key="f.key"
:model-value="[...f.selected]"
:items="f.options"
:item-title="optionTitle"
item-value="value"
:placeholder="t('common.all')"
:searchable="f.options.length >= SEARCHABLE_FROM"
:disabled="!f.options.length"
:data-facet="f.key"
multiple
clearable
hide-details
prefix-label="stacked"
@update:model-value="
(v) => emit('update', { key: f.key, values: v as string[] })
"
>
<template #prefix-label>
<RIcon :icon="f.icon" size="14" />
{{ f.label }}
</template>
<template #selection="{ item, index }">
<span v-if="index > 0">,&nbsp;</span>
<span>{{ (item.raw as FacetOption).label }}</span>
</template>
</RSelect>
</div>
<template #footer>
<RBtn
variant="outlined"
prepend-icon="mdi-restore"
:disabled="activeCount === 0"
@click="emit('clear')"
>
{{ t("platform.reset-filters") }}
</RBtn>
<div class="r-pfd__spacer" />
<RBtn
variant="flat"
color="primary"
@click="emit('update:modelValue', false)"
>
{{ t("common.close") }}
</RBtn>
</template>
</RDrawer>
</template>
<style scoped>
.r-pfd__rows {
display: flex;
flex-direction: column;
gap: 14px;
}
.r-pfd__spacer {
flex: 1;
}
</style>

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Доставчик на метаданни",
"no-firmware-found": "Няма намерен фърмуер",
"no-platforms-empty": "Няма намерени платформи. Стартирай сканиране, за да попълниш библиотеката си.",
"no-platforms-filters": "Няма платформи, отговарящи на тези филтри.",
"no-platforms-search": "Няма платформи, отговарящи на \"{query}\".",
"no-platforms-with-games": "Няма платформи с игри. Използвай филтъра, за да включиш празните платформи.",
"not-found": "Платформата не е намерена.",
@@ -61,6 +62,10 @@
"on-disk": "На диск",
"only-with-games": "Само платформи с игри",
"platform-deleted": "Платформата „{name}“ е изтрита",
"play-mode": "Режим на игра",
"play-mode-browser": "В браузъра",
"play-mode-native": "Локален емулатор",
"play-mode-stream": "Стрийминг",
"playable": "Може да се играе",
"playable-both": "Може да се играе в браузъра и да се стриймва от {label}",
"playable-browser-dosbox": "Може да се играе в браузъра чрез DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Poskytovatel metadat",
"no-firmware-found": "Nenalezen žádný firmware",
"no-platforms-empty": "Nebyly nalezeny žádné platformy. Spusťte skenování pro naplnění knihovny.",
"no-platforms-filters": "Těmto filtrům neodpovídají žádné platformy.",
"no-platforms-search": "Žádné platformy neodpovídají „{query}“.",
"no-platforms-with-games": "Žádné platformy s hrami. Pomocí filtru zahrňte prázdné platformy.",
"not-found": "Platforma nebyla nalezena.",
@@ -61,6 +62,10 @@
"on-disk": "Na disku",
"only-with-games": "Pouze platformy s hrami",
"platform-deleted": "Platforma „{name}“ byla smazána",
"play-mode": "Režim hraní",
"play-mode-browser": "V prohlížeči",
"play-mode-native": "Místní emulátor",
"play-mode-stream": "Streamování",
"playable": "Hratelné",
"playable-both": "Hratelné v prohlížeči a streamovatelné z {label}",
"playable-browser-dosbox": "Hratelné v prohlížeči přes DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Metadatenanbieter",
"no-firmware-found": "Keine Firmware gefunden",
"no-platforms-empty": "Keine Plattformen gefunden. Führe einen Scan aus, um deine Bibliothek zu füllen.",
"no-platforms-filters": "Keine Plattformen entsprechen diesen Filtern.",
"no-platforms-search": "Keine Plattformen entsprechen \"{query}\".",
"no-platforms-with-games": "Keine Plattformen mit Spielen. Nutze den Filter, um leere Plattformen einzuschließen.",
"not-found": "Plattform nicht gefunden.",
@@ -61,6 +62,10 @@
"on-disk": "Auf Datenträger",
"only-with-games": "Nur Plattformen mit Spielen",
"platform-deleted": "Plattform „{name}“ gelöscht",
"play-mode": "Spielmodus",
"play-mode-browser": "Im Browser",
"play-mode-native": "Lokaler Emulator",
"play-mode-stream": "Streaming",
"playable": "Spielbar",
"playable-both": "Im Browser spielbar und streambar über {label}",
"playable-browser-dosbox": "Im Browser spielbar über DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Metadata provider",
"no-firmware-found": "No firmware found",
"no-platforms-empty": "No platforms found. Run a scan to populate your library.",
"no-platforms-filters": "No platforms match these filters.",
"no-platforms-search": "No platforms match \"{query}\".",
"no-platforms-with-games": "No platforms with games. Use the filter to include empty platforms.",
"not-found": "Platform not found.",
@@ -61,6 +62,10 @@
"on-disk": "On disk",
"only-with-games": "Only platforms with games",
"platform-deleted": "Platform \"{name}\" deleted",
"play-mode": "Play mode",
"play-mode-browser": "In browser",
"play-mode-native": "Local emulator",
"play-mode-stream": "Streaming",
"playable": "Playable",
"playable-both": "Playable in browser and streamable from {label}",
"playable-browser-dosbox": "Playable in browser through DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Metadata provider",
"no-firmware-found": "No firmware found",
"no-platforms-empty": "No platforms found. Run a scan to populate your library.",
"no-platforms-filters": "No platforms match these filters.",
"no-platforms-search": "No platforms match \"{query}\".",
"no-platforms-with-games": "No platforms with games. Use the filter to include empty platforms.",
"not-found": "Platform not found.",
@@ -61,6 +62,10 @@
"on-disk": "On disk",
"only-with-games": "Only platforms with games",
"platform-deleted": "Platform \"{name}\" deleted",
"play-mode": "Play mode",
"play-mode-browser": "In browser",
"play-mode-native": "Local emulator",
"play-mode-stream": "Streaming",
"playable": "Playable",
"playable-both": "Playable in browser and streamable from {label}",
"playable-browser-dosbox": "Playable in browser through DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Proveedor de metadatos",
"no-firmware-found": "No se encontraron firmwares",
"no-platforms-empty": "No se encontraron plataformas. Ejecuta un escaneo para rellenar tu biblioteca.",
"no-platforms-filters": "Ninguna plataforma coincide con estos filtros.",
"no-platforms-search": "Ninguna plataforma coincide con \"{query}\".",
"no-platforms-with-games": "No hay plataformas con juegos. Usa el filtro para incluir las plataformas vacías.",
"not-found": "Plataforma no encontrada.",
@@ -61,6 +62,10 @@
"on-disk": "En disco",
"only-with-games": "Solo plataformas con juegos",
"platform-deleted": "Plataforma «{name}» eliminada",
"play-mode": "Modo de juego",
"play-mode-browser": "En el navegador",
"play-mode-native": "Emulador local",
"play-mode-stream": "Streaming",
"playable": "Jugable",
"playable-both": "Jugable en el navegador y transmisible desde {label}",
"playable-browser-dosbox": "Jugable en el navegador mediante DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Fournisseur de métadonnées",
"no-firmware-found": "Aucun firmware trouvé",
"no-platforms-empty": "Aucune plateforme trouvée. Lancez une analyse pour remplir votre bibliothèque.",
"no-platforms-filters": "Aucune plateforme ne correspond à ces filtres.",
"no-platforms-search": "Aucune plateforme ne correspond à « {query} ».",
"no-platforms-with-games": "Aucune plateforme avec des jeux. Utilisez le filtre pour inclure les plateformes vides.",
"not-found": "Plateforme introuvable.",
@@ -61,6 +62,10 @@
"on-disk": "Sur le disque",
"only-with-games": "Uniquement les plateformes avec des jeux",
"platform-deleted": "Plateforme « {name} » supprimée",
"play-mode": "Mode de jeu",
"play-mode-browser": "Dans le navigateur",
"play-mode-native": "Émulateur local",
"play-mode-stream": "Streaming",
"playable": "Jouable",
"playable-both": "Jouable dans le navigateur et diffusable depuis {label}",
"playable-browser-dosbox": "Jouable dans le navigateur via DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Metaadat-szolgáltató",
"no-firmware-found": "Firmware nem található",
"no-platforms-empty": "Nincsenek platformok. Indíts szkennelést a könyvtár feltöltéséhez.",
"no-platforms-filters": "Nincs a szűrőknek megfelelő platform.",
"no-platforms-search": "Nincs platform a következőre: „{query}”.",
"no-platforms-with-games": "Nincs játékokat tartalmazó platform. A szűrővel megjelenítheted az üres platformokat is.",
"not-found": "A platform nem található.",
@@ -61,6 +62,10 @@
"on-disk": "Lemezen",
"only-with-games": "Csak játékokkal rendelkező platformok",
"platform-deleted": "A(z) „{name}” platform törölve",
"play-mode": "Játékmód",
"play-mode-browser": "Böngészőben",
"play-mode-native": "Helyi emulátor",
"play-mode-stream": "Streamelés",
"playable": "Játszható",
"playable-both": "Böngészőben játszható és streamelhető innen: {label}",
"playable-browser-dosbox": "Böngészőben játszható DOSBox segítségével",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Fornitore di metadati",
"no-firmware-found": "Nessun firmware trovato",
"no-platforms-empty": "Nessuna piattaforma trovata. Esegui una scansione per popolare la tua libreria.",
"no-platforms-filters": "Nessuna piattaforma corrisponde a questi filtri.",
"no-platforms-search": "Nessuna piattaforma corrisponde a \"{query}\".",
"no-platforms-with-games": "Nessuna piattaforma con giochi. Usa il filtro per includere le piattaforme vuote.",
"not-found": "Piattaforma non trovata.",
@@ -61,6 +62,10 @@
"on-disk": "Su disco",
"only-with-games": "Solo piattaforme con giochi",
"platform-deleted": "Piattaforma \"{name}\" eliminata",
"play-mode": "Modalità di gioco",
"play-mode-browser": "Nel browser",
"play-mode-native": "Emulatore locale",
"play-mode-stream": "Streaming",
"playable": "Giocabile",
"playable-both": "Giocabile nel browser e trasmissibile da {label}",
"playable-browser-dosbox": "Giocabile nel browser tramite DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "メタデータプロバイダー",
"no-firmware-found": "ファームウェアが見つかりません",
"no-platforms-empty": "プラットフォームが見つかりません。スキャンを実行してライブラリを構築してください。",
"no-platforms-filters": "これらのフィルタに一致するプラットフォームはありません。",
"no-platforms-search": "「{query}」に一致するプラットフォームはありません。",
"no-platforms-with-games": "ゲームのあるプラットフォームがありません。フィルタで空のプラットフォームを表示できます。",
"not-found": "プラットフォームが見つかりません。",
@@ -61,6 +62,10 @@
"on-disk": "ディスク上",
"only-with-games": "ゲームがあるプラットフォームのみ",
"platform-deleted": "プラットフォーム「{name}」を削除しました",
"play-mode": "プレイ方法",
"play-mode-browser": "ブラウザ",
"play-mode-native": "ローカルエミュレーター",
"play-mode-stream": "ストリーミング",
"playable": "プレイ可能",
"playable-both": "ブラウザでプレイ可能、{label} からストリーミング可能",
"playable-browser-dosbox": "DOSBox によりブラウザでプレイ可能",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "메타데이터 제공자",
"no-firmware-found": "펌웨어 없음",
"no-platforms-empty": "플랫폼을 찾을 수 없습니다. 스캔을 실행하여 라이브러리를 채우세요.",
"no-platforms-filters": "이 필터와 일치하는 플랫폼이 없습니다.",
"no-platforms-search": "\"{query}\"와(과) 일치하는 플랫폼이 없습니다.",
"no-platforms-with-games": "게임이 있는 플랫폼이 없습니다. 필터를 사용하여 빈 플랫폼을 포함하세요.",
"not-found": "플랫폼을 찾을 수 없습니다.",
@@ -61,6 +62,10 @@
"on-disk": "디스크에 있음",
"only-with-games": "게임이 있는 플랫폼만",
"platform-deleted": "플랫폼 \"{name}\"을(를) 삭제했습니다",
"play-mode": "플레이 방식",
"play-mode-browser": "브라우저",
"play-mode-native": "로컬 에뮬레이터",
"play-mode-stream": "스트리밍",
"playable": "플레이 가능",
"playable-both": "브라우저에서 플레이 가능, {label}에서 스트리밍 가능",
"playable-browser-dosbox": "DOSBox를 통해 브라우저에서 플레이 가능",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Dostawca metadanych",
"no-firmware-found": "Nie znaleziono oprogramowania",
"no-platforms-empty": "Nie znaleziono platform. Uruchom skanowanie, aby zapełnić bibliotekę.",
"no-platforms-filters": "Brak platform pasujących do tych filtrów.",
"no-platforms-search": "Brak platform pasujących do \"{query}\".",
"no-platforms-with-games": "Brak platform z grami. Użyj filtra, aby uwzględnić puste platformy.",
"not-found": "Nie znaleziono platformy.",
@@ -61,6 +62,10 @@
"on-disk": "Na dysku",
"only-with-games": "Tylko platformy z grami",
"platform-deleted": "Usunięto platformę „{name}”",
"play-mode": "Tryb gry",
"play-mode-browser": "W przeglądarce",
"play-mode-native": "Lokalny emulator",
"play-mode-stream": "Streaming",
"playable": "Grywalne",
"playable-both": "Grywalne w przeglądarce i dostępne w streamingu z {label}",
"playable-browser-dosbox": "Grywalne w przeglądarce przez DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Provedor de metadados",
"no-firmware-found": "Nenhum firmware encontrado",
"no-platforms-empty": "Nenhuma plataforma encontrada. Execute uma varredura para popular sua biblioteca.",
"no-platforms-filters": "Nenhuma plataforma corresponde a estes filtros.",
"no-platforms-search": "Nenhuma plataforma corresponde a \"{query}\".",
"no-platforms-with-games": "Nenhuma plataforma com jogos. Use o filtro para incluir as plataformas vazias.",
"not-found": "Plataforma não encontrada.",
@@ -61,6 +62,10 @@
"on-disk": "No disco",
"only-with-games": "Apenas plataformas com jogos",
"platform-deleted": "Plataforma \"{name}\" excluída",
"play-mode": "Modo de jogo",
"play-mode-browser": "No navegador",
"play-mode-native": "Emulador local",
"play-mode-stream": "Streaming",
"playable": "Jogável",
"playable-both": "Jogável no navegador e transmissível de {label}",
"playable-browser-dosbox": "Jogável no navegador via DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Furnizor de metadate",
"no-firmware-found": "Niciun firmware găsit",
"no-platforms-empty": "Nicio platformă găsită. Rulează o scanare pentru a popula biblioteca.",
"no-platforms-filters": "Nicio platformă nu corespunde acestor filtre.",
"no-platforms-search": "Nicio platformă nu corespunde căutării „{query}”.",
"no-platforms-with-games": "Nicio platformă cu jocuri. Folosește filtrul pentru a include platformele goale.",
"not-found": "Platforma nu a fost găsită.",
@@ -61,6 +62,10 @@
"on-disk": "Pe disc",
"only-with-games": "Doar platformele cu jocuri",
"platform-deleted": "Platforma „{name}” a fost ștearsă",
"play-mode": "Mod de joc",
"play-mode-browser": "În browser",
"play-mode-native": "Emulator local",
"play-mode-stream": "Streaming",
"playable": "Se poate juca",
"playable-both": "Se poate juca în browser și se poate transmite de pe {label}",
"playable-browser-dosbox": "Se poate juca în browser prin DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Источник метаданных",
"no-firmware-found": "Прошивка не найдена",
"no-platforms-empty": "Платформы не найдены. Запустите сканирование, чтобы наполнить библиотеку.",
"no-platforms-filters": "Нет платформ, соответствующих этим фильтрам.",
"no-platforms-search": "Нет платформ, соответствующих \"{query}\".",
"no-platforms-with-games": "Нет платформ с играми. Используйте фильтр, чтобы показать пустые платформы.",
"not-found": "Платформа не найдена.",
@@ -61,6 +62,10 @@
"on-disk": "На диске",
"only-with-games": "Только платформы с играми",
"platform-deleted": "Платформа «{name}» удалена",
"play-mode": "Способ игры",
"play-mode-browser": "В браузере",
"play-mode-native": "Локальный эмулятор",
"play-mode-stream": "Стриминг",
"playable": "Можно играть",
"playable-both": "Запускается в браузере и транслируется с {label}",
"playable-browser-dosbox": "Запускается в браузере через DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Metadataleverantör",
"no-firmware-found": "Ingen firmware hittades",
"no-platforms-empty": "Inga plattformar hittades. Kör en genomsökning för att fylla biblioteket.",
"no-platforms-filters": "Inga plattformar matchar dessa filter.",
"no-platforms-search": "Inga plattformar matchar ”{query}”.",
"no-platforms-with-games": "Inga plattformar har spel. Använd filtret för att inkludera tomma plattformar.",
"not-found": "Plattformen hittades inte.",
@@ -61,6 +62,10 @@
"on-disk": "På disken",
"only-with-games": "Endast plattformar med spel",
"platform-deleted": "Plattformen ”{name}” togs bort",
"play-mode": "Spelläge",
"play-mode-browser": "I webbläsaren",
"play-mode-native": "Lokal emulator",
"play-mode-stream": "Strömning",
"playable": "Spelbar",
"playable-both": "Spelbar i webbläsaren och kan strömmas från {label}",
"playable-browser-dosbox": "Spelbar i webbläsaren via DOSBox",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "Üst veri sağlayıcısı",
"no-firmware-found": "Firmware bulunamadı",
"no-platforms-empty": "Platform bulunamadı. Kütüphanenizi doldurmak için tarama başlatın.",
"no-platforms-filters": "Bu filtrelerle eşleşen platform bulunamadı.",
"no-platforms-search": "\"{query}\" ile eşleşen platform bulunamadı.",
"no-platforms-with-games": "Oyunu olan platform yok. Boş platformları dahil etmek için filtreyi kullanın.",
"not-found": "Platform bulunamadı.",
@@ -61,6 +62,10 @@
"on-disk": "Diskte",
"only-with-games": "Yalnızca oyunu olan platformlar",
"platform-deleted": "\"{name}\" platformu silindi",
"play-mode": "Oynama modu",
"play-mode-browser": "Tarayıcıda",
"play-mode-native": "Yerel emülatör",
"play-mode-stream": "Yayın",
"playable": "Oynanabilir",
"playable-both": "Tarayıcıda oynanabilir ve {label} üzerinden yayınlanabilir",
"playable-browser-dosbox": "DOSBox ile tarayıcıda oynanabilir",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "元数据提供方",
"no-firmware-found": "没有找到固件",
"no-platforms-empty": "未找到平台。运行扫描以填充您的游戏库。",
"no-platforms-filters": "没有符合这些筛选条件的平台。",
"no-platforms-search": "没有符合 \"{query}\" 的平台。",
"no-platforms-with-games": "没有包含游戏的平台。使用筛选器可显示空平台。",
"not-found": "未找到该平台。",
@@ -61,6 +62,10 @@
"on-disk": "磁盘上",
"only-with-games": "仅显示有游戏的平台",
"platform-deleted": "已删除平台“{name}”",
"play-mode": "游玩方式",
"play-mode-browser": "浏览器",
"play-mode-native": "本地模拟器",
"play-mode-stream": "串流",
"playable": "可玩",
"playable-both": "可在浏览器中游玩,也可从 {label} 串流",
"playable-browser-dosbox": "可通过 DOSBox 在浏览器中游玩",

View File

@@ -54,6 +54,7 @@
"metadata-provider": "中繼資料提供者",
"no-firmware-found": "没有找到韌體",
"no-platforms-empty": "找不到任何平台。執行掃描以填充您的遊戲庫。",
"no-platforms-filters": "沒有符合這些篩選條件的平台。",
"no-platforms-search": "找不到符合「{query}」的平台。",
"no-platforms-with-games": "沒有包含遊戲的平台。使用篩選器可顯示空平台。",
"not-found": "找不到平台。",
@@ -61,6 +62,10 @@
"on-disk": "在磁碟上",
"only-with-games": "僅顯示有遊戲的平台",
"platform-deleted": "已刪除平台「{name}」",
"play-mode": "遊玩方式",
"play-mode-browser": "瀏覽器",
"play-mode-native": "本機模擬器",
"play-mode-stream": "串流",
"playable": "可遊玩",
"playable-both": "可在瀏覽器中遊玩,也可從 {label} 串流",
"playable-browser-dosbox": "可透過 DOSBox 在瀏覽器中遊玩",

View File

@@ -0,0 +1,136 @@
import { describe, expect, it } from "vitest";
import {
facetOptions,
filterByFacets,
formatFacetParam,
parseFacetParam,
sameFacetOptions,
} from "@/utils/platformFacets";
type Key = "category" | "play";
interface Item {
name: string;
category: string;
play: string[];
}
const items: Item[] = [
{ name: "snes", category: "console", play: ["browser"] },
{ name: "gba", category: "portable", play: ["browser", "stream"] },
{ name: "ps2", category: "console", play: [] },
{ name: "dos", category: "computer", play: ["browser"] },
];
const valuesOf = (item: Item, key: Key): readonly string[] =>
key === "category" ? [item.category] : item.play;
const names = (list: Item[]) => list.map((i) => i.name);
describe("filterByFacets", () => {
it("returns everything when nothing is picked", () => {
expect(names(filterByFacets(items, { category: [] }, valuesOf))).toEqual([
"snes",
"gba",
"ps2",
"dos",
]);
});
it("ORs values within a facet and ANDs across facets", () => {
const picked = filterByFacets(
items,
{ category: ["console", "portable"], play: ["browser"] },
valuesOf,
);
expect(names(picked)).toEqual(["snes", "gba"]);
});
it("ignores the excepted facet", () => {
const picked = filterByFacets(
items,
{ category: ["computer"], play: ["stream"] },
valuesOf,
"category",
);
expect(names(picked)).toEqual(["gba"]);
});
});
describe("facetOptions", () => {
it("counts each option against the other facets only", () => {
const options = facetOptions(
items,
"category",
{ category: ["console"], play: ["browser"] },
valuesOf,
(v) => v,
);
expect(options).toEqual([
{ value: "computer", label: "computer", count: 1 },
{ value: "console", label: "console", count: 1 },
{ value: "portable", label: "portable", count: 1 },
]);
});
it("keeps options the other facets narrow to zero", () => {
const options = facetOptions(
items,
"category",
{ play: ["stream"] },
valuesOf,
(v) => v,
);
expect(options.find((o) => o.value === "console")?.count).toBe(0);
});
it("lists a selected value even when no item carries it", () => {
const options = facetOptions(
items,
"category",
{ category: ["arcade"] },
valuesOf,
(v) => v.toUpperCase(),
);
expect(options[0]).toEqual({ value: "arcade", label: "ARCADE", count: 0 });
});
it("honours a custom order", () => {
const options = facetOptions(
items,
"play",
{},
valuesOf,
(v) => v,
(a, b) => b.count - a.count,
);
expect(options.map((o) => o.value)).toEqual(["browser", "stream"]);
});
});
describe("facet query params", () => {
it("round-trips, dropping empties and duplicates", () => {
expect(parseFacetParam("")).toEqual([]);
expect(parseFacetParam("a,,b,a")).toEqual(["a", "b"]);
expect(formatFacetParam(["a", "b", "a"])).toBe("a,b");
});
});
describe("sameFacetOptions", () => {
const a = [{ value: "x", label: "X", count: 1 }];
it("matches equal lists held in different arrays", () => {
expect(sameFacetOptions(a, [{ value: "x", label: "X", count: 1 }])).toBe(
true,
);
});
it("notices a changed count, label, or length", () => {
expect(sameFacetOptions(a, [{ value: "x", label: "X", count: 2 }])).toBe(
false,
);
expect(sameFacetOptions(a, [{ value: "x", label: "Y", count: 1 }])).toBe(
false,
);
expect(sameFacetOptions(a, [])).toBe(false);
});
});

View File

@@ -0,0 +1,100 @@
// Platforms index faceting: values OR within a facet, facets AND together,
// and a facet's counts ignore its own selection.
export const PLATFORM_FACET_KEYS = [
"category",
"generation",
"family",
"play",
] as const;
export type PlatformFacetKey = (typeof PLATFORM_FACET_KEYS)[number];
export type FacetSelection<K extends string> = Partial<
Record<K, readonly string[]>
>;
export type FacetValuesOf<T, K extends string> = (
item: T,
key: K,
) => readonly string[];
export interface FacetOption {
value: string;
label: string;
count: number;
}
export function filterByFacets<T, K extends string>(
items: readonly T[],
selection: NoInfer<FacetSelection<K>>,
valuesOf: FacetValuesOf<T, K>,
except?: NoInfer<K>,
): T[] {
const active = (Object.entries(selection) as [K, readonly string[]][]).filter(
([key, picked]) => key !== except && picked.length > 0,
);
if (!active.length) return [...items];
return items.filter((item) =>
active.every(([key, picked]) =>
valuesOf(item, key).some((v) => picked.includes(v)),
),
);
}
/**
* Options for one facet, counted against every other facet's selection.
*
* Args:
* universe: items the facet may describe (already search-filtered).
* labelOf: display label for a raw value.
* compare: option order; defaults to label order.
*/
export function facetOptions<T, K extends string>(
universe: readonly T[],
key: NoInfer<K>,
selection: NoInfer<FacetSelection<K>>,
valuesOf: FacetValuesOf<T, K>,
labelOf: (value: string) => string,
compare: (a: FacetOption, b: FacetOption) => number = (a, b) =>
a.label.localeCompare(b.label),
): FacetOption[] {
// Seed from the whole universe so an option narrowed to zero stays put
// in the menu instead of vanishing under the cursor.
const counts = new Map<string, number>();
for (const item of universe) {
for (const v of valuesOf(item, key)) counts.set(v, 0);
}
for (const v of selection[key] ?? []) counts.set(v, 0);
for (const item of filterByFacets(universe, selection, valuesOf, key)) {
for (const v of valuesOf(item, key)) {
counts.set(v, (counts.get(v) ?? 0) + 1);
}
}
return [...counts.entries()]
.map(([value, count]) => ({ value, label: labelOf(value), count }))
.sort(compare);
}
export function sameFacetOptions(
a: readonly FacetOption[],
b: readonly FacetOption[],
): boolean {
return (
a.length === b.length &&
a.every(
(o, i) =>
o.value === b[i]!.value &&
o.label === b[i]!.label &&
o.count === b[i]!.count,
)
);
}
/** Comma-separated query value ⇄ list, dropping empties and duplicates. */
export function parseFacetParam(raw: string): string[] {
return [...new Set(raw.split(",").filter(Boolean))];
}
export function formatFacetParam(values: readonly string[]): string {
return [...new Set(values)].join(",");
}

View File

@@ -2,6 +2,10 @@
import { mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, ref } from "vue";
import GalleryToolbar from "@/components/Gallery/GalleryToolbar.vue";
import PlatformFilterDrawer, {
type PlatformFacet,
} from "@/components/Platforms/PlatformFilterDrawer.vue";
import storePlatforms, { type Platform } from "@/stores/platforms";
import { platformFixture } from "@/utils/platform.fixtures";
import PlatformsIndex from "./PlatformsIndex.vue";
@@ -35,7 +39,17 @@ vi.mock("@/lib", () => ({
}));
vi.mock("@/components/Gallery/GalleryToolbar.vue", () => ({
default: defineComponent({ template: "<div />" }),
default: defineComponent({
props: { filterActiveCount: { type: Number, default: 0 } },
template: "<div />",
}),
}));
vi.mock("@/components/Platforms/PlatformFilterDrawer.vue", () => ({
default: defineComponent({
props: { facets: { type: Array, default: () => [] } },
template: "<div />",
}),
}));
vi.mock("@/components/Platforms/PlatformListHeader.vue", () => ({
@@ -372,4 +386,138 @@ describe("PlatformsIndex", () => {
expect(wrapper.text()).toContain("Arcade 7");
});
});
describe("facets", () => {
function seed() {
streamableSlugs.add("gba");
storePlatforms().set([
platform(1, "PlayStation", 30, {
slug: "ps",
category: "console",
generation: 5,
family_slug: "playstation",
family_name: "PlayStation",
}),
platform(2, "Nintendo 64", 12, {
slug: "n64",
category: "console",
generation: 5,
family_slug: "nintendo",
family_name: "Nintendo",
}),
platform(3, "Game Boy Advance", 5, {
slug: "gba",
category: "portable_console",
generation: 6,
family_slug: "nintendo",
family_name: "Nintendo",
}),
]);
}
function facet(
wrapper: ReturnType<typeof mount>,
key: string,
): PlatformFacet | undefined {
const facets = wrapper
.findComponent(PlatformFilterDrawer)
.props("facets") as PlatformFacet[];
return facets.find((f) => f.key === key);
}
it("ORs values picked in one facet", () => {
seed();
routeState.query = { category: "portable_console,console" };
const wrapper = mount(PlatformsIndex);
expect(wrapper.text()).toContain("PlayStation 30");
expect(wrapper.text()).toContain("Game Boy Advance 5");
});
it("ANDs across facets", () => {
seed();
routeState.query = { category: "console", family: "nintendo" };
const wrapper = mount(PlatformsIndex);
expect(wrapper.text()).toContain("Nintendo 64 12");
expect(wrapper.text()).not.toContain("PlayStation 30");
expect(wrapper.text()).not.toContain("Game Boy Advance 5");
expect(wrapper.text()).toContain("common.platforms 3");
});
it("filters by play mode", () => {
seed();
routeState.query = { play: "stream" };
const wrapper = mount(PlatformsIndex);
expect(wrapper.text()).toContain("Game Boy Advance 5");
expect(wrapper.text()).not.toContain("Nintendo 64 12");
});
it("counts each facet's options against the other facets", () => {
seed();
routeState.query = { family: "nintendo", gen: "5" };
const wrapper = mount(PlatformsIndex);
expect(facet(wrapper, "category")?.options).toEqual([
{ value: "console", label: "Console", count: 1 },
{ value: "portable_console", label: "Portable Console", count: 0 },
]);
expect(facet(wrapper, "generation")?.options).toEqual([
{ value: "5", label: "5th generation", count: 1 },
{ value: "6", label: "6th generation", count: 1 },
]);
expect(facet(wrapper, "family")?.selected).toEqual(["nintendo"]);
});
it("only offers play modes some platform supports", () => {
seed();
const wrapper = mount(PlatformsIndex);
expect(facet(wrapper, "play")?.options).toEqual([
{ value: "stream", label: "platform.play-mode-stream", count: 1 },
]);
});
it("falls back to the raw value for an unknown play mode", () => {
seed();
routeState.query = { play: "__proto__" };
const wrapper = mount(PlatformsIndex);
expect(facet(wrapper, "play")?.options).toContainEqual({
value: "__proto__",
label: "__proto__",
count: 0,
});
});
it("badges the toolbar filter button with the active facet count", () => {
seed();
routeState.query = {
category: "console,portable_console",
play: "stream",
};
const wrapper = mount(PlatformsIndex);
expect(
wrapper.findComponent(GalleryToolbar).props("filterActiveCount"),
).toBe(2);
});
it("says the filters matched nothing", () => {
seed();
routeState.query = { category: "portable_console", gen: "5" };
const wrapper = mount(PlatformsIndex);
expect(wrapper.text()).toContain("platform.no-platforms-filters");
});
});
});

View File

@@ -14,13 +14,19 @@
// blindly. When the global groupBy lands on a value with no usable
// data on the loaded platforms, the view falls through to flat: the
// toolbar's mode is the user's intent, not a hard requirement.
//
// Facets (category / generation / family / play mode) filter on top of the
// search and live in the URL, so a narrowed view can be shared or bookmarked.
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
import { computed, onMounted, type Ref, ref } from "vue";
import { useI18n } from "vue-i18n";
import GalleryToolbar, {
type GroupByItem,
type SegmentFilter,
} from "@/components/Gallery/GalleryToolbar.vue";
import PlatformFilterDrawer, {
type PlatformFacet,
} from "@/components/Platforms/PlatformFilterDrawer.vue";
import PlatformListHeader from "@/components/Platforms/PlatformListHeader.vue";
import PlatformListRow from "@/components/Platforms/PlatformListRow.vue";
import PlatformTile from "@/components/Platforms/PlatformTile.vue";
@@ -40,6 +46,17 @@ import { useRouteQueryParam } from "@/composables/useRouteQueryParam";
import { useTileSearchUrl } from "@/composables/useTileSearchUrl";
import { RDivider, REmptyState, RLetterHeading, RSkeletonBlock } from "@/lib";
import storePlatforms, { type Platform } from "@/stores/platforms";
import {
type FacetOption,
type FacetSelection,
facetOptions,
filterByFacets,
formatFacetParam,
parseFacetParam,
PLATFORM_FACET_KEYS,
type PlatformFacetKey,
sameFacetOptions,
} from "@/utils/platformFacets";
import { platformMatchesSearch } from "@/utils/platformSearch";
const { t } = useI18n();
@@ -87,20 +104,30 @@ useGridNav(gridRoot, { cellSelector: ".plat-tile" });
// streaming container, or in a local emulator when the desktop shell is
// there to launch one -- a platform with no in-browser core at all, PS2
// being the example, is playable inside the shell and has to sort as such.
const playableById = computed(() => {
const PLAY_MODES = ["browser", "stream", "native"] as const;
type PlayMode = (typeof PLAY_MODES)[number];
const playModesById = computed(() => {
const playableFn = isPlayable.value;
const streamableFn = isStreamable.value;
const nativeFn = isNativeSupported.value;
const map = new Map<number | string, boolean>();
const map = new Map<number | string, PlayMode[]>();
for (const p of allPlatforms.value) {
map.set(
p.id,
playableFn(p.slug) || streamableFn(p.slug) || nativeFn(p.slug),
);
const modes: PlayMode[] = [];
if (playableFn(p.slug)) modes.push("browser");
if (streamableFn(p.slug)) modes.push("stream");
if (nativeFn(p.slug)) modes.push("native");
map.set(p.id, modes);
}
return map;
});
const playableById = computed(() => {
const map = new Map<number | string, boolean>();
for (const [id, modes] of playModesById.value) map.set(id, modes.length > 0);
return map;
});
// Two independent sort states. The list view's column headers drive
// `listSortKey` + `listSortDir`; the grid view's toolbar asc/desc toggle
// drives `gridSortDir`, with the implicit axis tied to the active
@@ -265,12 +292,163 @@ onMounted(() => {
}
});
const filtered = computed<Platform[]>(() => {
const searched = computed<Platform[]>(() => {
const term = searchTerm.value.trim().toLowerCase();
if (!term) return visiblePlatforms.value;
return visiblePlatforms.value.filter((p) => platformMatchesSearch(p, term));
});
const FACET_PARAMS: Record<PlatformFacetKey, string> = {
category: "category",
generation: "gen",
family: "family",
play: "play",
};
const facetParams = Object.fromEntries(
PLATFORM_FACET_KEYS.map((key) => [
key,
useRouteQueryParam(FACET_PARAMS[key], ""),
]),
) as Record<PlatformFacetKey, Ref<string>>;
const facetSelection = computed<FacetSelection<PlatformFacetKey>>(() =>
Object.fromEntries(
PLATFORM_FACET_KEYS.map((key) => [
key,
parseFacetParam(facetParams[key].value),
]),
),
);
const activeFacetCount = computed(
() =>
PLATFORM_FACET_KEYS.filter((key) => facetParams[key].value !== "").length,
);
const hasFacetSelection = computed(() => activeFacetCount.value > 0);
const filterDrawerOpen = ref(false);
function onFacetUpdate({
key,
values,
}: {
key: PlatformFacetKey;
values: string[];
}) {
facetParams[key].value = formatFacetParam(values);
}
function clearFacets() {
for (const key of PLATFORM_FACET_KEYS) facetParams[key].value = "";
}
function facetValuesOf(p: Platform, key: PlatformFacetKey): readonly string[] {
switch (key) {
case "category":
return p.category ? [p.category] : [];
case "generation":
return typeof p.generation === "number" && p.generation > 0
? [String(p.generation)]
: [];
case "family":
return p.family_slug ? [p.family_slug] : [];
case "play":
return playModesById.value.get(p.id) ?? [];
}
}
const familyNames = computed(() => {
const map = new Map<string, string>();
for (const p of allPlatforms.value) {
if (p.family_slug && p.family_name) map.set(p.family_slug, p.family_name);
}
return map;
});
const PLAY_MODE_LABEL_KEYS: Record<PlayMode, string> = {
browser: "platform.play-mode-browser",
stream: "platform.play-mode-stream",
native: "platform.play-mode-native",
};
function facetLabel(key: PlatformFacetKey, value: string): string {
switch (key) {
case "category":
return prettifyPlatformCategory(value);
case "generation":
return platformGenerationLabel(Number(value));
case "family":
return familyNames.value.get(value) ?? value;
case "play":
return Object.hasOwn(PLAY_MODE_LABEL_KEYS, value)
? t(PLAY_MODE_LABEL_KEYS[value as PlayMode])
: value;
}
}
const byNumericValue = (a: FacetOption, b: FacetOption) =>
Number(a.value) - Number(b.value);
const byPlayModeOrder = (a: FacetOption, b: FacetOption) =>
PLAY_MODES.indexOf(a.value as PlayMode) -
PLAY_MODES.indexOf(b.value as PlayMode);
const FACET_META: Record<
PlatformFacetKey,
{
labelKey: string;
icon: string;
compare?: (a: FacetOption, b: FacetOption) => number;
}
> = {
category: { labelKey: "platform.category", icon: "mdi-shape-outline" },
generation: {
labelKey: "platform.generation",
icon: "mdi-numeric",
compare: byNumericValue,
},
family: { labelKey: "platform.family", icon: "mdi-family-tree" },
play: {
labelKey: "platform.play-mode",
icon: "mdi-play-circle-outline",
compare: byPlayModeOrder,
},
};
// An open select resets its keyboard highlight whenever its items array
// changes, so a facet whose options didn't change keeps the same array.
const lastOptions = new Map<PlatformFacetKey, FacetOption[]>();
function stableOptions(
key: PlatformFacetKey,
next: FacetOption[],
): FacetOption[] {
const prev = lastOptions.get(key);
if (prev && sameFacetOptions(prev, next)) return prev;
lastOptions.set(key, next);
return next;
}
const facets = computed<PlatformFacet[]>(() =>
PLATFORM_FACET_KEYS.map((key) => ({
key,
label: t(FACET_META[key].labelKey),
icon: FACET_META[key].icon,
options: stableOptions(
key,
facetOptions(
searched.value,
key,
facetSelection.value,
facetValuesOf,
(value) => facetLabel(key, value),
FACET_META[key].compare,
),
),
selected: facetSelection.value[key] ?? [],
})),
);
const filtered = computed<Platform[]>(() =>
filterByFacets(searched.value, facetSelection.value, facetValuesOf),
);
// Per-mode sorted views. Grid uses the toolbar asc/desc + groupBy axis;
// list uses the column-header click state. Buckets are always fed the
// grid-sorted array (Map iteration preserves insertion order, so items
@@ -295,11 +473,12 @@ const noResults = computed(
allPlatforms.value.length > 0 &&
filtered.value.length === 0,
);
const noResultsMessage = computed(() =>
searchTerm.value.trim()
const noResultsMessage = computed(() => {
if (hasFacetSelection.value) return t("platform.no-platforms-filters");
return searchTerm.value.trim()
? t("platform.no-platforms-search", { query: searchTerm.value })
: t("platform.no-platforms-with-games"),
);
: t("platform.no-platforms-with-games");
});
// Generic bucket: every grouping computed produces the same shape so
// the template can iterate one branch per non-letter mode. `key` is the
@@ -467,6 +646,8 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
:search="searchTerm"
:group-by-items="platformGroupByItems"
:segment-filters="segmentFilters"
show-filter
:filter-active-count="activeFacetCount"
show-search
:search-placeholder="t('platform.search-placeholder')"
@update:group-by="groupBy = $event"
@@ -474,6 +655,13 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
@update:sort-dir="gridSortDir = $event"
@update:search="searchTerm = $event"
@update:segment-filter="onSegmentFilter"
@click:filter="filterDrawerOpen = true"
/>
<PlatformFilterDrawer
v-model="filterDrawerOpen"
:facets="facets"
@update="onFacetUpdate"
@clear="clearFacets"
/>
</template>