refactor: remove MetadataSections component and update gallery sorting logic

- Deleted the MetadataSections.vue component, which handled metadata display for various providers.
- Updated AlphaStrip.vue to include a direction prop for sorting letters in ascending or descending order.
- Enhanced GalleryShell.vue to manage grid sorting direction and integrate it with the toolbar.
- Modified GalleryToolbar.vue to add sorting direction controls for grid mode.
- Adjusted PlatformTile.vue to simplify the playable indicator display.
- Refactored useGalleryVirtualItems to normalize letter sorting with new bucket logic.
- Added subtitle support to RTextField for enhanced context display.
- Updated CollectionsIndex.vue to implement grid sorting functionality.
- Refined PlatformsIndex.vue to separate list and grid sorting states, improving overall sorting logic.
This commit is contained in:
zurdi
2026-05-21 14:31:30 +00:00
parent 6ed332bce3
commit a9b19ebde7
13 changed files with 533 additions and 606 deletions

View File

@@ -535,7 +535,7 @@ def get_roms(
char_index_dict = {}
if with_char_index:
char_index = db_rom_handler.with_char_index(
query=query, order_by_attr=order_by_attr
query=query, order_by_attr=order_by_attr, order_dir=order_dir.lower()
)
char_index_dict = {char: index for (char, index) in char_index}

View File

@@ -880,6 +880,7 @@ class DBRomsHandler(DBBaseHandler):
self,
query: Query,
order_by_attr: Any,
order_dir: str = "asc",
session: Session = None, # type: ignore
) -> list[Row[tuple[str, int]]]:
if isinstance(order_by_attr.type, (String, Text)):
@@ -897,6 +898,15 @@ class DBRomsHandler(DBBaseHandler):
r"(\d+)", r"00000000000\1"
).regexp_replace(r"0*(\d{12})", r"\1")
# Apply the same direction the main query uses so the position
# numbers we emit (and the per-letter min position downstream)
# match the actual order the client paginates over. Without this
# the frontend AlphaStrip would highlight the wrong letter when
# order_dir=desc.
order_window = (
order_by_attr.desc() if order_dir.lower() == "desc" else order_by_attr.asc()
)
# Get the row number and first letter for each item
subquery = (
query.with_only_columns(Rom.id, Rom.name) # type: ignore
@@ -906,7 +916,7 @@ class DBRomsHandler(DBBaseHandler):
1,
1,
).label("letter"),
func.row_number().over(order_by=order_by_attr).label("position"),
func.row_number().over(order_by=order_window).label("position"),
)
.subquery()
)

View File

@@ -1,26 +1,34 @@
<script setup lang="ts">
// EditRomDialog — v2 chrome around the ROM-edit form. Cover actions and
// metadata expansion panels keep pulling from v1 components (GameCard +
// AdditionalDetails / MetadataIdSection / MetadataSections) because those
// are deep domain composites — rebuilding them natively is a separate
// effort. The inline confirm-delete-manual and upload-target dialogs from
// v1 are gone; those flows route through the global v2
// DeleteManualDialog / ManualUploadTargetDialog via the emitter.
import { RBtn, RCollapsible, RDialog, RIcon, RTextField } from "@v2/lib";
// EditRomDialog — v2 chrome around the ROM-edit form.
//
// Scope: identity (name / filename / summary), cover artwork, and the
// metadata override / raw provider tabs. Manual + soundtrack +
// screenshots are intentionally absent — those flows now live in the
// GameDetails Media tab (`v2/components/GameDetails/MediaTab.vue`).
// Pulling them out of the edit dialog kept it focused on "data that
// describes this ROM" and freed the form column from the icon-button
// row that fought visually with the field stack.
//
// Layout: a hero row (cover + name/filename/summary) at the top, and a
// tabbed editing surface below — "Details" and "Metadata IDs" are
// always present; one tab per metadata provider with a populated ID is
// appended dynamically (and disappears once the rom is unmatched from
// that provider). Cover actions, AdditionalDetails and MetadataIdSection
// remain deep domain composites pulled from the EditRom feature folder.
import { RBtn, RDialog, RIcon, RTabNav, RTextField } from "@v2/lib";
import type { RTabNavItem } from "@v2/lib/primitives/RTabNav/types";
import type { Emitter } from "mitt";
import { computed, inject, onBeforeUnmount, ref } from "vue";
import { computed, inject, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import romApi, { type UpdateRom } from "@/services/api/rom";
import storeHeartbeat from "@/stores/heartbeat";
import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms";
import storeUpload from "@/stores/upload";
import type { Events } from "@/types/emitter";
import { formatBytes } from "@/utils";
import { getMissingCoverImage } from "@/utils/covers";
import AdditionalDetails from "@/v2/components/EditRom/AdditionalDetails.vue";
import MetadataIdSection from "@/v2/components/EditRom/MetadataIdSection.vue";
import MetadataSections from "@/v2/components/EditRom/MetadataSections.vue";
import RawMetadataPanel from "@/v2/components/EditRom/RawMetadataPanel.vue";
import GameCard from "@/v2/components/GameCard/GameCard.vue";
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -32,44 +40,27 @@ const { lgAndUp } = useBreakpoint();
const heartbeat = storeHeartbeat();
const route = useRoute();
const show = ref(false);
// `UpdateRom = SimpleRom & {...}` but we need DetailedRom for delegating
// manual/upload flows to global v2 dialogs. We hold a DetailedRom-compatible
// shape internally and widen at edit/emit boundaries.
// `UpdateRom = SimpleRom & {...}` but we keep a DetailedRom-compatible
// shape internally so the per-provider raw-metadata panels can read
// their payloads. Widen at edit/emit boundaries.
type EditableRom = DetailedRom & UpdateRom;
const rom = ref<EditableRom | null>(null);
// Per-section open state for the metadata accordion. Each RCollapsible
// is independent; consumers expect to expand only what they want to
// edit, not a single-active enforced pattern.
const additionalOpen = ref(false);
const metaIdsOpen = ref(false);
const romsStore = storeRoms();
const imagePreviewUrl = ref<string | undefined>("");
const removeCover = ref(false);
const manualFiles = ref<File[]>([]);
const soundtrackFiles = ref<File[]>([]);
const uploadStore = storeUpload();
const coverFileInput = ref<HTMLInputElement | null>(null);
const manualFileInput = ref<HTMLInputElement | null>(null);
const soundtrackFileInput = ref<HTMLInputElement | null>(null);
const emitter = inject<Emitter<Events>>("emitter");
const snackbar = useSnackbar();
const soundtrackTracks = computed(
() =>
rom.value?.files
?.filter((f) => f.category === "soundtrack")
.slice()
.sort((a, b) => a.file_name.localeCompare(b.file_name)) ?? [],
);
const openHandler = async (romToEdit: SimpleRom) => {
show.value = true;
// Show the simple rom immediately so the dialog mounts; fetch the
// detailed version in the background so manual/soundtrack flows that
// rely on file arrays have real data.
// detailed version in the background so provider metadata panels
// have real data to render.
rom.value = romToEdit as EditableRom;
removeCover.value = false;
imagePreviewUrl.value = "";
activeTab.value = "details";
try {
const { data } = await romApi.getRom({ romId: romToEdit.id });
if (show.value) rom.value = data as EditableRom;
@@ -93,6 +84,106 @@ const missingCoverImage = computed(() =>
const validForm = computed(() => !!(rom.value?.name && rom.value?.fs_name));
const isFolderRom = computed(
() =>
!!rom.value &&
(rom.value.has_nested_single_file || rom.value.has_multiple_files),
);
const fullPath = computed(() => {
if (!rom.value) return "";
return `/romm/library/${rom.value.fs_path}/${rom.value.fs_name}`;
});
// ── Tabbed editing surface ───────────────────────────────────────
// "Details" + "Metadata IDs" are always present; each provider with a
// populated id appends its own tab so the raw-JSON editing surface
// only ever shows panels that actually have data.
interface ProviderConfig {
/** Tab id — also the discriminant for the rendered panel. */
tabId: string;
idField: keyof SimpleRom;
metadataField: keyof SimpleRom;
label: string;
}
const PROVIDERS: readonly ProviderConfig[] = [
{
tabId: "igdb",
idField: "igdb_id",
metadataField: "igdb_metadata",
label: "IGDB",
},
{
tabId: "moby",
idField: "moby_id",
metadataField: "moby_metadata",
label: "MobyGames",
},
{
tabId: "ss",
idField: "ss_id",
metadataField: "ss_metadata",
label: "ScreenScraper",
},
{
tabId: "launchbox",
idField: "launchbox_id",
metadataField: "launchbox_metadata",
label: "LaunchBox",
},
{
tabId: "hasheous",
idField: "hasheous_id",
metadataField: "hasheous_metadata",
label: "Hasheous",
},
{
tabId: "flashpoint",
idField: "flashpoint_id",
metadataField: "flashpoint_metadata",
label: "Flashpoint",
},
{
tabId: "hltb",
idField: "hltb_id",
metadataField: "hltb_metadata",
label: "HLTB",
},
];
const activeTab = ref<string>("details");
const visibleProviders = computed(() =>
rom.value ? PROVIDERS.filter((p) => rom.value?.[p.idField]) : [],
);
const tabItems = computed<RTabNavItem[]>(() => [
{
id: "details",
label: t("rom.additional-details", "Additional details"),
icon: "mdi-text-box-plus-outline",
},
{
id: "ids",
label: t("rom.metadata-ids", "Metadata IDs"),
icon: "mdi-database",
},
...visibleProviders.value.map((p) => ({ id: p.tabId, label: p.label })),
]);
const activeProvider = computed(() =>
visibleProviders.value.find((p) => p.tabId === activeTab.value),
);
// When the active provider tab vanishes (unmatch / id wiped), fall back
// to "details" so the content area never points at a missing tab.
watch(tabItems, (items) => {
if (!items.some((t) => t.id === activeTab.value)) {
activeTab.value = "details";
}
});
function previewImage(event: Event) {
if (!rom.value) return;
const input = event.target as HTMLInputElement;
@@ -141,97 +232,6 @@ async function handleRomUpdate(
}
}
function uploadManuals() {
if (!rom.value || manualFiles.value.length === 0) return;
const files = [...manualFiles.value];
manualFiles.value = [];
// Route through the global v2 ManualUploadTargetDialog so the
// resources/folder picker lives in one place. If the ROM is a simple
// single-file ROM the dialog skips the prompt and defaults to resources.
emitter?.emit("showManualUploadTargetDialog", { rom: rom.value, files });
}
function confirmRemoveManual() {
if (!rom.value) return;
emitter?.emit("showDeleteManualDialog", {
rom: rom.value,
isPrimary: true,
fileId: undefined,
});
}
async function uploadSoundtracks() {
if (!rom.value) return;
try {
const responses = await romApi.uploadSoundtracks({
romId: rom.value.id,
filesToUpload: soundtrackFiles.value,
});
const successful = responses.filter((d) => d.status === "fulfilled");
const failed = responses.filter((d) => d.status === "rejected");
if (failed.length === 0) uploadStore.reset();
if (successful.length === 0) {
snackbar.warning(t("rom.soundtracks-upload-skipped"), {
icon: "mdi-close-circle",
timeout: 5000,
});
} else {
snackbar.success(
t("rom.soundtracks-upload-success", {
count: successful.length,
failed: failed.length,
}),
{ icon: "mdi-check-bold", timeout: 3000 },
);
await refreshRomState();
}
} catch (error: unknown) {
const axiosErr = error as {
response?: { data?: { detail?: string }; statusText?: string };
message?: string;
};
snackbar.error(
t("rom.soundtracks-upload-failed", {
error:
axiosErr.response?.data?.detail ??
axiosErr.response?.statusText ??
axiosErr.message,
}),
{ icon: "mdi-close-circle", timeout: 4000 },
);
}
soundtrackFiles.value = [];
}
async function removeSoundtrack(fileId: number) {
if (!rom.value) return;
try {
await romApi.removeSoundtrack({ romId: rom.value.id, fileId });
await refreshRomState();
snackbar.success(t("rom.soundtrack-removed"), { icon: "mdi-check-bold" });
} catch (error: unknown) {
const axiosErr = error as {
response?: { data?: { detail?: string } };
message?: string;
};
snackbar.error(
t("rom.soundtrack-remove-failed", {
error: axiosErr.response?.data?.detail ?? axiosErr.message,
}),
{ icon: "mdi-close-circle" },
);
}
}
async function refreshRomState() {
if (!rom.value) return;
const { data } = await romApi.getRom({ romId: rom.value.id });
rom.value = data as EditableRom;
romsStore.update(data as SimpleRom);
if (route.name === "rom") romsStore.currentRom = data;
}
async function unmatchRom() {
if (!rom.value) return;
await handleRomUpdate(
@@ -276,8 +276,9 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
</template>
<template #content>
<div class="r-v2-edit">
<!-- Cover column -->
<!-- Hero row — cover + identity fields. Everything else hangs
off the accordion below. -->
<div class="r-v2-edit__hero">
<div class="r-v2-edit__cover-col">
<GameCard
:rom="rom"
@@ -330,8 +331,7 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
</div>
</div>
<!-- Form column -->
<div class="r-v2-edit__form-col">
<div class="r-v2-edit__fields">
<RTextField
v-model="rom.name"
prefix-label="stacked"
@@ -343,6 +343,7 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
{{ t("common.name") }}
</template>
</RTextField>
<RTextField
v-model="rom.fs_name"
prefix-label="stacked"
@@ -351,190 +352,64 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
>
<template #prefix-label>
<RIcon
:icon="
rom.has_nested_single_file || rom.has_multiple_files
? 'mdi-folder-outline'
: 'mdi-file-outline'
"
:icon="isFolderRom ? 'mdi-folder-outline' : 'mdi-file-outline'"
size="14"
/>
{{
rom.has_nested_single_file || rom.has_multiple_files
? t("rom.folder-name")
: t("rom.filename")
}}
{{ isFolderRom ? t("rom.folder-name") : t("rom.filename") }}
</template>
<template #subtitle>
<RIcon icon="mdi-folder-file-outline" size="13" color="primary" />
{{ fullPath }}
</template>
</RTextField>
<p class="r-v2-edit__path">
<RIcon icon="mdi-folder-file-outline" size="13" color="primary" />
/romm/library/{{ rom.fs_path }}/{{ rom.fs_name }}
</p>
<RTextField v-model="rom.summary" prefix-label="stacked" hide-details>
<RTextField
v-model="rom.summary"
prefix-label="stacked"
hide-details
multiline
:rows="3"
>
<template #prefix-label>
<RIcon icon="mdi-text" size="14" />
{{ t("rom.summary") }}
</template>
</RTextField>
<!-- Manual -->
<div class="r-v2-edit__row">
<div
class="r-v2-edit__badge"
:class="{ 'r-v2-edit__badge--ok': rom.has_manual }"
>
<RIcon
:icon="rom.has_manual ? 'mdi-check' : 'mdi-close'"
size="12"
/>
{{ t("rom.manual") }}
</div>
<button
type="button"
class="r-v2-edit__icon-btn"
:title="t('rom.upload-manual', 'Upload manual')"
@click="manualFileInput?.click()"
>
<RIcon icon="mdi-cloud-upload-outline" size="16" />
</button>
<input
ref="manualFileInput"
type="file"
accept="application/pdf"
multiple
:aria-label="t('rom.upload-manual', 'Upload manual')"
class="r-v2-edit__file"
@change="
($event) => {
const target = $event.target as HTMLInputElement;
if (target.files) manualFiles = Array.from(target.files);
uploadManuals();
target.value = '';
}
"
/>
<button
v-if="rom.has_manual"
type="button"
class="r-v2-edit__icon-btn r-v2-edit__icon-btn--danger"
:title="t('rom.delete-manual-button')"
@click="confirmRemoveManual"
>
<RIcon icon="mdi-delete" size="16" />
</button>
<div style="flex: 1" />
<RBtn
variant="outlined"
size="small"
color="error"
:disabled="rom.is_unidentified"
@click="unmatchRom"
>
{{ t("rom.unmatch") }}
</RBtn>
</div>
<p v-if="rom.has_manual" class="r-v2-edit__path">
<RIcon icon="mdi-folder-file-outline" size="13" color="primary" />
/romm/resources/{{ rom.path_manual }}
</p>
<!-- Soundtrack -->
<div class="r-v2-edit__row">
<div
class="r-v2-edit__badge"
:class="{ 'r-v2-edit__badge--ok': rom.has_soundtrack }"
>
<RIcon
:icon="rom.has_soundtrack ? 'mdi-check' : 'mdi-close'"
size="12"
/>
{{ t("rom.soundtrack") }}
</div>
<button
type="button"
class="r-v2-edit__icon-btn"
:title="t('rom.upload-soundtrack', 'Upload soundtrack')"
:disabled="rom.has_simple_single_file"
@click="soundtrackFileInput?.click()"
>
<RIcon icon="mdi-cloud-upload-outline" size="16" />
</button>
<input
ref="soundtrackFileInput"
type="file"
accept="audio/*,.flac,.opus"
multiple
:aria-label="t('rom.upload-soundtrack', 'Upload soundtrack')"
class="r-v2-edit__file"
@change="
($event) => {
const target = $event.target as HTMLInputElement;
if (target.files) soundtrackFiles = Array.from(target.files);
uploadSoundtracks();
target.value = '';
}
"
/>
<span v-if="rom.has_simple_single_file" class="r-v2-edit__hint">
{{ t("rom.soundtrack-folder-only") }}
</span>
</div>
<ul v-if="soundtrackTracks.length > 0" class="r-v2-edit__tracks">
<li
v-for="track in soundtrackTracks"
:key="track.id"
class="r-v2-edit__track"
>
<RIcon icon="mdi-music-note" size="14" />
<span class="r-v2-edit__track-name" :title="track.file_name">
{{ track.file_name }}
</span>
<span class="r-v2-edit__track-size">
{{ formatBytes(track.file_size_bytes) }}
</span>
<button
type="button"
class="r-v2-edit__icon-btn r-v2-edit__icon-btn--danger r-v2-edit__icon-btn--xs"
:title="t('rom.soundtrack-removed', 'Remove track')"
@click="removeSoundtrack(track.id)"
>
<RIcon icon="mdi-delete" size="13" />
</button>
</li>
</ul>
</div>
</div>
<!-- Metadata accordion — each section can open/close independently. -->
<!-- Tabbed editing surface — "Details" + "Metadata IDs" always
present, one tab per provider with a populated id appended
after. Sits under the hero so the dialog reads top-down as
"identity → editing surface". -->
<div class="r-v2-edit__panels">
<RCollapsible
v-model="additionalOpen"
icon="mdi-text-box-plus-outline"
title="Additional details"
>
<AdditionalDetails
:rom="rom"
@update:rom="handleRomUpdateFromMetadata"
/>
</RCollapsible>
<RCollapsible
v-model="metaIdsOpen"
icon="mdi-database"
title="Metadata IDs"
>
<MetadataIdSection
:rom="rom"
@update:rom="handleRomUpdateFromMetadata"
/>
</RCollapsible>
<!-- MetadataSections fans out its own RCollapsibles per provider. -->
<MetadataSections
:rom="rom"
@update:rom="handleRomUpdateFromMetadata"
<RTabNav
v-model="activeTab"
:items="tabItems"
variant="underlined"
size="small"
aria-label="Edit ROM sections"
/>
<div class="r-v2-edit__tab-content">
<AdditionalDetails
v-if="activeTab === 'details'"
:rom="rom"
@update:rom="handleRomUpdateFromMetadata"
/>
<MetadataIdSection
v-else-if="activeTab === 'ids'"
:rom="rom"
@update:rom="handleRomUpdateFromMetadata"
/>
<RawMetadataPanel
v-else-if="activeProvider"
:key="activeProvider.tabId"
:rom="rom"
:metadata-field="activeProvider.metadataField as keyof UpdateRom"
:label="activeProvider.label"
@update:rom="handleRomUpdateFromMetadata"
/>
</div>
</div>
</template>
@@ -543,6 +418,15 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
{{ t("common.cancel") }}
</RBtn>
<div style="flex: 1" />
<RBtn
v-if="!rom.is_unidentified"
variant="outlined"
color="error"
prepend-icon="mdi-link-variant-off"
@click="unmatchRom"
>
{{ t("rom.unmatch") }}
</RBtn>
<RBtn
variant="translucent"
color="primary"
@@ -557,7 +441,12 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
</template>
<style scoped>
.r-v2-edit {
/* ── Hero ──────────────────────────────────────────────────────────
Cover sits in a fixed-width left column; fields take the rest. The
`align-items: start` keeps the cover anchored to the top so taller
stacks of fields (or the multiline summary growing) don't drag the
cover down with them. */
.r-v2-edit__hero {
display: grid;
grid-template-columns: 220px 1fr;
gap: 18px;
@@ -576,6 +465,18 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
gap: 4px;
}
.r-v2-edit__fields {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
/* ── Icon buttons (cover row) ─────────────────────────────────────
Square 32px chips that share a vocabulary with the surrounding
field chrome — outlined surface, tinted hover, danger variant for
destructive actions. Kept here (not promoted to a primitive) until
we have a second consumer that needs the exact same shape. */
.r-v2-edit__icon-btn {
appearance: none;
background: var(--r-color-surface);
@@ -607,10 +508,6 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
);
color: var(--r-color-danger-fg);
}
.r-v2-edit__icon-btn--xs {
width: 24px;
height: 24px;
}
.r-v2-edit__file {
position: absolute;
@@ -620,109 +517,24 @@ function handleRomUpdateFromMetadata(updatedRom: UpdateRom) {
pointer-events: none;
}
.r-v2-edit__form-col {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.r-v2-edit__path {
display: inline-flex;
align-items: center;
gap: 6px;
margin: -4px 0 0;
font-size: 11px;
color: var(--r-color-fg-muted);
font-family: var(--r-font-family-mono, monospace);
word-break: break-all;
}
.r-v2-edit__row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 4px;
flex-wrap: wrap;
}
.r-v2-edit__badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: var(--r-radius-pill);
background: color-mix(
in srgb,
var(--r-color-status-base-danger) 12%,
transparent
);
border: 1px solid
color-mix(in srgb, var(--r-color-status-base-danger) 25%, transparent);
color: var(--r-color-danger-fg);
font-size: 12px;
font-weight: var(--r-font-weight-medium);
}
.r-v2-edit__badge--ok {
background: color-mix(
in srgb,
var(--r-color-status-base-success) 14%,
transparent
);
border-color: color-mix(
in srgb,
var(--r-color-status-base-success) 30%,
transparent
);
color: var(--r-color-success);
}
.r-v2-edit__hint {
font-size: 11px;
color: var(--r-color-fg-muted);
}
.r-v2-edit__tracks {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.r-v2-edit__track {
display: grid;
grid-template-columns: auto 1fr auto auto;
gap: 8px;
align-items: center;
padding: 6px 10px;
background: var(--r-color-bg-elevated);
border: 1px solid var(--r-color-border);
border-radius: var(--r-radius-sm);
font-size: 12px;
}
.r-v2-edit__track-name {
color: var(--r-color-fg);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}
.r-v2-edit__track-size {
font-size: 11px;
color: var(--r-color-fg-muted);
font-variant-numeric: tabular-nums;
}
/* ── Tab surface ─────────────────────────────────────────────────
The tab nav owns its own bottom border, so the only separator we
need above is breathing space — the hero ends, a margin of 20px
beats, then the tab strip begins. The tab content gets its own
inset so panels don't sit flush against the underlined strip. */
.r-v2-edit__panels {
margin-top: 18px;
margin-top: 20px;
display: flex;
flex-direction: column;
gap: 8px;
}
html[data-bp~="xs"] .r-v2-edit {
.r-v2-edit__tab-content {
padding-top: 16px;
}
/* ── Compact breakpoint ───────────────────────────────────────────
Cover stacks above the fields when the dialog is forced narrow. */
html[data-bp~="xs"] .r-v2-edit__hero {
grid-template-columns: 1fr;
}
html[data-bp~="xs"] .r-v2-edit__cover-col {

View File

@@ -1,120 +0,0 @@
<script setup lang="ts">
// MetadataSections (v2) — fans out one RCollapsible per metadata
// provider whose ID is set on the rom. The collapsible body is the
// per-provider raw-JSON editor (RawMetadataPanel). Providers without
// an ID for this rom are skipped so the dialog only ever shows panels
// that actually have data.
//
// Feature composite — knows the SimpleRom shape and the v2 R
// primitives. EditRomDialog renders this alongside AdditionalDetails
// and MetadataIdSection inside the metadata accordion.
import { RAvatar, RCollapsible } from "@v2/lib";
import { ref } from "vue";
import type { UpdateRom } from "@/services/api/rom";
import type { SimpleRom } from "@/stores/roms";
import RawMetadataPanel from "./RawMetadataPanel.vue";
defineProps<{ rom: SimpleRom }>();
const emit = defineEmits<{
"update:rom": [rom: UpdateRom];
}>();
function handleRomUpdate(updatedRom: UpdateRom) {
emit("update:rom", updatedRom);
}
interface MetadataConfig {
idField: keyof SimpleRom;
metadataField: keyof SimpleRom;
iconSrc: string;
label: string;
}
const METADATA_CONFIGS: readonly MetadataConfig[] = [
{
idField: "igdb_id",
metadataField: "igdb_metadata",
iconSrc: "/assets/scrappers/igdb.png",
label: "IGDB",
},
{
idField: "moby_id",
metadataField: "moby_metadata",
iconSrc: "/assets/scrappers/moby.png",
label: "MobyGames",
},
{
idField: "ss_id",
metadataField: "ss_metadata",
iconSrc: "/assets/scrappers/ss.png",
label: "ScreenScraper",
},
{
idField: "launchbox_id",
metadataField: "launchbox_metadata",
iconSrc: "/assets/scrappers/launchbox.png",
label: "LaunchBox",
},
{
idField: "hasheous_id",
metadataField: "hasheous_metadata",
iconSrc: "/assets/scrappers/hasheous.png",
label: "Hasheous",
},
{
idField: "flashpoint_id",
metadataField: "flashpoint_metadata",
iconSrc: "/assets/scrappers/flashpoint.png",
label: "Flashpoint",
},
{
idField: "hltb_id",
metadataField: "hltb_metadata",
iconSrc: "/assets/scrappers/hltb.png",
label: "HLTB",
},
];
// Each panel keeps its own open state. Keyed by metadataField so the
// state survives across rom mutations (the parent re-renders us when
// the user saves any provider's raw payload).
const openMap = ref<Record<string, boolean>>({});
function isOpen(key: string) {
return openMap.value[key] === true;
}
function setOpen(key: string, value: boolean) {
openMap.value = { ...openMap.value, [key]: value };
}
</script>
<template>
<template v-for="config in METADATA_CONFIGS" :key="config.idField">
<RCollapsible
v-if="rom[config.idField]"
:model-value="isOpen(String(config.metadataField))"
class="r-v2-meta-section"
@update:model-value="(v) => setOpen(String(config.metadataField), v)"
>
<template #header-prepend>
<RAvatar :image="config.iconSrc" size="24" rounded="sm" />
</template>
<template #title> {{ config.label }} metadata </template>
<RawMetadataPanel
:rom="rom as unknown as UpdateRom"
:metadata-field="config.metadataField as keyof UpdateRom"
:label="config.label"
@update:rom="handleRomUpdate"
/>
</RCollapsible>
</template>
</template>
<style scoped>
.r-v2-meta-section {
margin-bottom: 8px;
}
.r-v2-meta-section:last-child {
margin-bottom: 0;
}
</style>

View File

@@ -15,20 +15,34 @@ import { computed } from "vue";
defineOptions({ inheritAttrs: false });
const ALPHABET = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
// Two non-alphabetic buckets bookend the alphabet:
// * `#` — digits (0-9) — sits BEFORE A
// * `@` — any other non-alphanumeric first character — sits AFTER Z
// Order in asc: `# A B … Z @` — `#` at the top, `@` at the bottom.
// When the gallery sorts desc the whole array reverses (`@` to the top,
// `#` to the bottom) so the strip's visual order tracks the data's
// order and the scroll-spy highlight follows the scroll direction.
const ALPHABET = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ@".split("");
interface Props {
available?: Set<string> | string[];
current?: string;
visible?: Set<string> | string[];
/** Render order — reversed when the gallery sorts descending. */
direction?: "asc" | "desc";
}
const props = withDefaults(defineProps<Props>(), {
available: () => new Set<string>(),
current: "",
visible: () => new Set<string>(),
direction: "asc",
});
const letters = computed(() =>
props.direction === "desc" ? [...ALPHABET].reverse() : ALPHABET,
);
defineEmits<{
(e: "pick", letter: string): void;
}>();
@@ -52,7 +66,7 @@ function isActive(letter: string): boolean {
<template>
<aside class="alpha-strip" aria-label="Jump to letter">
<button
v-for="l in ALPHABET"
v-for="l in letters"
:key="l"
type="button"
class="alpha-strip__btn"

View File

@@ -507,6 +507,17 @@ function onListSort(payload: { key: ListSortKey; dir: "asc" | "desc" }) {
void galleryRoms.fetchInitialMetadata();
}
// Grid-mode direction toggle — wires the toolbar asc/desc into the
// same `orderDir` the list column-header sort writes to, then triggers
// the same invalidate+refetch path. Sort axis stays whatever the list
// last set (default "name"); grid only exposes direction.
function onGridSortDir(dir: "asc" | "desc") {
if (galleryRoms.orderDir === dir) return;
galleryRoms.setOrderDir(dir);
galleryRoms.invalidateWindows();
void galleryRoms.fetchInitialMetadata();
}
// ── Scroll restoration ─────────────────────────────────────────────
async function applyRestoredScroll() {
const saved = scrollRestoration.restore(route.fullPath);
@@ -682,6 +693,7 @@ defineExpose({
:group-by="groupBy"
:layout="layout"
:position="toolbarPosition"
:sort-dir="orderDir"
show-search
:search="searchInput"
:search-placeholder="searchPlaceholder"
@@ -689,6 +701,7 @@ defineExpose({
:filter-active-count="filterActiveCount"
@update:group-by="groupBy = $event"
@update:layout="layout = $event"
@update:sort-dir="onGridSortDir"
@update:search="setSearch"
@click:filter="filterDrawerOpen = true"
/>
@@ -794,6 +807,7 @@ defineExpose({
:group-by="groupBy"
:layout="layout"
:position="toolbarPosition"
:sort-dir="orderDir"
show-search
:search="searchInput"
:search-placeholder="searchPlaceholder"
@@ -801,6 +815,7 @@ defineExpose({
:filter-active-count="filterActiveCount"
@update:group-by="groupBy = $event"
@update:layout="layout = $event"
@update:sort-dir="onGridSortDir"
@update:search="setSearch"
@click:filter="filterDrawerOpen = true"
/>
@@ -827,6 +842,7 @@ defineExpose({
:available="availableLetters"
:current="currentLetter"
:visible="visibleLettersSet"
:direction="orderDir"
@pick="scrollToLetter"
/>
@@ -838,10 +854,12 @@ defineExpose({
:group-by="groupBy"
:layout="layout"
:position="toolbarPosition"
:sort-dir="orderDir"
show-filter
:filter-active-count="filterActiveCount"
@update:group-by="groupBy = $event"
@update:layout="layout = $event"
@update:sort-dir="onGridSortDir"
@click:filter="filterDrawerOpen = true"
/>

View File

@@ -57,6 +57,9 @@ const props = withDefaults(
* to expose richer modes (family / category / generation) beyond
* the default flat / letter pair. */
groupByItems?: GroupByItem[];
/** Direction toggle for grid-mode sort. Disabled in list mode
* (list-mode sort is driven by the column-header clicks). */
sortDir?: Ref<"asc" | "desc"> | "asc" | "desc";
/** Show the search field on the left. v-model:search controls its value. */
showSearch?: boolean;
search?: string;
@@ -96,6 +99,7 @@ const props = withDefaults(
title: "Group by letter",
},
],
sortDir: "asc",
showSearch: false,
search: "",
searchPlaceholder: "Search…",
@@ -111,6 +115,7 @@ const props = withDefaults(
const emit = defineEmits<{
(e: "update:groupBy", value: GroupByMode): void;
(e: "update:layout", value: LayoutMode): void;
(e: "update:sortDir", value: "asc" | "desc"): void;
(e: "update:search", value: string): void;
(e: "update:kindFilter", value: KindFilterValue): void;
(e: "click:filter"): void;
@@ -125,6 +130,7 @@ function toValue<T>(source: Ref<T> | T): T {
const groupByValue = computed(() => toValue(props.groupBy));
const layoutValue = computed(() => toValue(props.layout));
const sortDirValue = computed(() => toValue(props.sortDir));
const layoutItems = [
{
@@ -141,6 +147,21 @@ const layoutItems = [
},
];
const sortDirItems = [
{
id: "asc" as const,
icon: "mdi-sort-ascending",
ariaLabel: "Sort ascending",
title: "Sort ascending",
},
{
id: "desc" as const,
icon: "mdi-sort-descending",
ariaLabel: "Sort descending",
title: "Sort descending",
},
];
function setGroupBy(value: GroupByMode) {
emit("update:groupBy", value);
}
@@ -149,6 +170,10 @@ function setLayout(value: LayoutMode) {
emit("update:layout", value);
}
function setSortDir(value: "asc" | "desc") {
emit("update:sortDir", value);
}
function setSearch(value: string) {
emit("update:search", value);
}
@@ -227,6 +252,16 @@ const { smAndUp } = useBreakpoint();
@update:model-value="setGroupBy"
/>
<RSliderBtnGroup
v-if="smAndUp"
:model-value="sortDirValue"
:items="sortDirItems"
variant="segmented"
aria-label="Sort direction"
:disabled="layoutValue === 'list'"
@update:model-value="setSortDir"
/>
<RSliderBtnGroup
v-if="smAndUp"
:model-value="layoutValue"
@@ -273,6 +308,21 @@ const { smAndUp } = useBreakpoint();
/>
<RDivider />
</template>
<RMenuItem
label="Sort ascending"
icon="mdi-sort-ascending"
:variant="sortDirValue === 'asc' ? 'active' : 'default'"
:disabled="layoutValue === 'list'"
@click="setSortDir('asc')"
/>
<RMenuItem
label="Sort descending"
icon="mdi-sort-descending"
:variant="sortDirValue === 'desc' ? 'active' : 'default'"
:disabled="layoutValue === 'list'"
@click="setSortDir('desc')"
/>
<RDivider />
<RMenuItem
label="Grid"
icon="mdi-view-grid-outline"

View File

@@ -93,11 +93,8 @@ const playableLabel = computed(() => playableTooltip(emulator.value));
:show-tooltip="false"
/>
</div>
<span
class="plat-tile__playable"
:class="{ 'plat-tile__playable--off': !playable }"
>
<RIcon :icon="playable ? 'mdi-play-circle' : 'mdi-cancel'" size="16" />
<span v-if="playable" class="plat-tile__playable">
<RIcon icon="mdi-play-circle" size="16" />
<RTooltip activator="parent" :text="playableLabel" location="top" />
</span>
<div class="plat-tile__name">
@@ -171,10 +168,6 @@ const playableLabel = computed(() => playableTooltip(emulator.value));
color: var(--r-color-success);
}
.plat-tile__playable--off {
color: var(--r-color-fg-faint);
}
.plat-tile:hover .plat-tile__icon {
opacity: 1;
}

View File

@@ -80,12 +80,14 @@ interface Options {
skeletonRowCount?: number;
}
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split("");
const ALPHABET = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ@".split("");
function normaliseBackendLetter(raw: string): string {
if (!raw) return "#";
if (!raw) return "@";
const c = raw.charAt(0).toUpperCase();
return /[A-Z]/.test(c) ? c : "#";
if (/[A-Z]/.test(c)) return c;
if (/[0-9]/.test(c)) return "#";
return "@";
}
interface LetterRange {

View File

@@ -30,6 +30,7 @@ const meta: Meta<typeof RTextField> = {
readonly: { control: "boolean" },
loading: { control: "boolean" },
hint: { control: "text" },
subtitle: { control: "text" },
error: { control: "boolean" },
errorMessages: { control: "text" },
},
@@ -135,6 +136,30 @@ export const InlineLabel: Story = {
},
};
export const WithSubtitle: Story = {
name: "Subtitle · path under field",
render: () => ({
components: { RTextField },
setup: () => ({
filename: ref("Super Mario World (USA).sfc"),
}),
template: `
<div style="width:420px">
<RTextField
v-model="filename"
prefix-label="stacked"
label="Filename"
>
<template #subtitle>
<span style="font-size:13px;line-height:1">📁</span>
/romm/library/snes/Super Mario World (USA).sfc
</template>
</RTextField>
</div>
`,
}),
};
// ── States ──────────────────────────────────────────────────────────
export const WithHint: Story = {

View File

@@ -84,6 +84,12 @@ interface Props {
* matters. Affects the input/textarea only — labels keep the regular
* family so the chrome still reads as a normal form field. */
mono?: boolean;
/** Small context line rendered just below the field box (above the
* details/error row). Mono-styled — used for file paths, URLs,
* hashes, or any "this is where the value resolves to" hint that
* pairs with the field's value. The `#subtitle` slot wins over the
* prop when both are provided; use the slot to drop in an icon. */
subtitle?: string;
}
const props = withDefaults(defineProps<Props>(), {
@@ -114,6 +120,7 @@ const props = withDefaults(defineProps<Props>(), {
multiline: false,
rows: 4,
mono: false,
subtitle: undefined,
});
const emit = defineEmits<{
@@ -294,6 +301,8 @@ const hasAppendInner = computed(
const inlineLabelOn = computed(() => props.prefixLabel === "inline");
const stackedLabelOn = computed(() => props.prefixLabel === "stacked");
const hasSubtitle = computed(() => !!props.subtitle || !!slots.subtitle);
// When `label` is set without a `prefixLabel`, we don't render a
// visible label — fall back to the label as placeholder + aria-label
// so the field still reads what it's for. Consumers wanting a visible
@@ -306,14 +315,30 @@ const effectiveAriaLabel = computed(() =>
);
// True when the parent is subscribed to a click on the adornment.
// Vue normalises `@click:append-inner` to the key `onClick:appendInner`
// in `$attrs`. The fallback handles older codepaths that camelCase the
// whole name. When subscribed, the adornment renders as a focusable
// `<button>` with hover + cursor.
// Vue's `toHandlerKey('click:append-inner')` is `onClick:append-inner`
// — the part after the colon is left verbatim, NOT camelised. The
// other variants below cover camelised / capitalised forms in case a
// parent passes the handler programmatically with a different key. When
// subscribed, the adornment renders as a focusable `<button>` with
// hover + cursor.
function hasListener(name: string): boolean {
const camel = `on${name[0].toUpperCase()}${name.slice(1).replace(/:(\w)/g, (_, c) => `:${c.toUpperCase()}`)}`;
const flat = `on${name[0].toUpperCase()}${name.slice(1).replace(/:(\w)/g, (_, c) => c.toUpperCase())}`;
return !!attrs[camel] || !!attrs[flat];
// verbatim → onClick:append-inner (Vue's actual template output)
const verbatim = `on${name[0].toUpperCase()}${name.slice(1)}`;
// kebab→camel inside the arg → onClick:appendInner
const argCamel = `on${name[0].toUpperCase()}${name
.slice(1)
.replace(/-(\w)/g, (_, c) => c.toUpperCase())}`;
// capitalised after the colon → onClick:Append-inner
const colonCap = `on${name[0].toUpperCase()}${name
.slice(1)
.replace(/:(\w)/g, (_, c) => `:${c.toUpperCase()}`)}`;
// no colon, camelCase tail → onClickAppend-inner
const flat = `on${name[0].toUpperCase()}${name
.slice(1)
.replace(/:(\w)/g, (_, c) => c.toUpperCase())}`;
return (
!!attrs[verbatim] || !!attrs[argCamel] || !!attrs[colonCap] || !!attrs[flat]
);
}
const prependInteractive = computed(() => hasListener("click:prepend-inner"));
const appendInteractive = computed(() => hasListener("click:append-inner"));
@@ -498,6 +523,15 @@ function onAppendInnerClick(evt: MouseEvent) {
/>
</div>
<!-- Subtitle — small mono context line just below the field box.
Used for resolved paths, URLs, hashes, or any "this value
points here" hint that pairs with the input. Sits between the
field box and the details/error row so error messages always
stay closest to the field. -->
<div v-if="hasSubtitle" class="r-text-field__subtitle">
<slot name="subtitle">{{ subtitle }}</slot>
</div>
<!-- Details row — error message, then hint as fallback. Always
mounted when shown so the height transition is smooth. -->
<div
@@ -844,6 +878,23 @@ function onAppendInnerClick(evt: MouseEvent) {
color: var(--r-color-danger);
}
/* ── Subtitle row ──────────────────────────────────────────────── */
/* Mono context line — paths, URLs, hashes. Sits flush below the
field box and aligns with the details row's padding so both rows
read as the same "annotation gutter". `word-break: break-all` keeps
long paths inside the field width instead of pushing the dialog. */
.r-text-field__subtitle {
display: inline-flex;
align-items: center;
gap: 6px;
padding-inline: 4px;
font-family: var(--r-font-family-mono);
font-size: 11px;
line-height: 1.3;
color: var(--r-color-fg-muted);
word-break: break-all;
}
/* ── Label — shared base ───────────────────────────────────────── */
.r-text-field__label {
display: inline-flex;
@@ -931,7 +982,8 @@ html[data-input="pad"]
.r-text-field__underline,
.r-text-field__clear,
.r-text-field__label,
.r-text-field__details {
.r-text-field__details,
.r-text-field__subtitle {
transition: none;
}
}

View File

@@ -60,6 +60,7 @@ const {
const { groupBy, layout } = useGalleryMode();
useGalleryViewModeUrl();
const searchTerm = useTileSearchUrl();
const gridSortDir = ref<"asc" | "desc">("asc");
// `?kind=` URL-synced filter — same direction rules as
// `useTileSearchUrl`: route → ref on every change, ref → router.replace
@@ -183,14 +184,21 @@ const filtered = computed<CollectionTileEntry[]>(() => {
return byTerm;
});
// Sort comparator for grid mode — the toolbar asc/desc toggle drives
// direction, name is the only sort axis the grid surface exposes.
function gridCompare(a: CollectionTileEntry, b: CollectionTileEntry): number {
const sign = gridSortDir.value === "asc" ? 1 : -1;
return a.name.localeCompare(b.name) * sign;
}
// Curated = regular + smart (both real, hand-managed). Virtual is the
// dynamic/computed kind. Splitting up front keeps every render branch
// (flat / letter / list) free of inline kind checks.
const curatedTiles = computed<CollectionTileEntry[]>(() =>
filtered.value.filter((c) => c.kind !== "virtual"),
[...filtered.value.filter((c) => c.kind !== "virtual")].sort(gridCompare),
);
const virtualTiles = computed<CollectionTileEntry[]>(() =>
filtered.value.filter((c) => c.kind === "virtual"),
[...filtered.value.filter((c) => c.kind === "virtual")].sort(gridCompare),
);
const totalCount = computed(() => tiles.value.length);
@@ -202,22 +210,38 @@ const noResults = computed(
);
type LetterGroup = { letter: string; items: CollectionTileEntry[] };
// Bucket visual order in asc: `# A…Z @` — `#` (digits) first, `@`
// (other symbols) last; mirrors AlphaStrip's ALPHABET. Desc flips the
// whole sequence (`@ Z…A #`).
const COLLECTION_BUCKET_ORDER = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ@";
function groupByLetter(items: CollectionTileEntry[]): LetterGroup[] {
const sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));
// `items` is pre-sorted by `gridCompare` (see curatedTiles /
// virtualTiles); Array.push + Map iteration preserve insertion order
// so items inside each bucket inherit that direction.
//
// Non-letter first chars split into two distinct buckets so digits
// and other symbols read as separate sections:
// * "#" — digits (0-9)
// * "@" — anything else
const map = new Map<string, CollectionTileEntry[]>();
for (const c of sorted) {
for (const c of items) {
const ch = c.name.charAt(0).toUpperCase();
const key = /[A-Z]/.test(ch) ? ch : "#";
let key: string;
if (/[A-Z]/.test(ch)) key = ch;
else if (/[0-9]/.test(ch)) key = "#";
else key = "@";
const bucket = map.get(key);
if (bucket) bucket.push(c);
else map.set(key, [c]);
}
const dirSign = gridSortDir.value === "asc" ? 1 : -1;
return [...map.entries()]
.sort(([a], [b]) => {
if (a === "#") return 1;
if (b === "#") return -1;
return a.localeCompare(b);
})
.sort(
([a], [b]) =>
(COLLECTION_BUCKET_ORDER.indexOf(a) -
COLLECTION_BUCKET_ORDER.indexOf(b)) *
dirSign,
)
.map(([letter, items]) => ({ letter, items }));
}
const curatedLetterGroups = computed<LetterGroup[]>(() =>
@@ -253,6 +277,7 @@ const showVirtualSection = computed(
<GalleryToolbar
:group-by="groupBy"
:layout="layout"
:sort-dir="gridSortDir"
:search="searchTerm"
show-search
search-placeholder="Search collections"
@@ -262,6 +287,7 @@ const showVirtualSection = computed(
kind-filter-aria-label="Filter collections"
@update:group-by="groupBy = $event"
@update:layout="layout = $event"
@update:sort-dir="gridSortDir = $event"
@update:search="searchTerm = $event"
@update:kind-filter="kindFilter = $event"
/>

View File

@@ -55,55 +55,88 @@ const playableById = computed(() => {
return map;
});
// Sort state — local to this view (the platforms index is small enough
// that a URL round-trip is overkill; debt item if/when we make this
// bookmarkable).
const sortKey = ref<PlatformSortKey>("name");
const sortDir = ref<"asc" | "desc">("asc");
// 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
// groupBy (letter → name, family → family, …, none → name). Keeping
// them separate so flipping one mode doesn't reshuffle the other.
const listSortKey = ref<PlatformSortKey>("name");
const listSortDir = ref<"asc" | "desc">("asc");
const gridSortDir = ref<"asc" | "desc">("asc");
function onSort({ key, dir }: { key: PlatformSortKey; dir: "asc" | "desc" }) {
sortKey.value = key;
sortDir.value = dir;
function onListSort({
key,
dir,
}: {
key: PlatformSortKey;
dir: "asc" | "desc";
}) {
listSortKey.value = key;
listSortDir.value = dir;
}
// Comparator pulled out so the flat list and each bucket can share it.
// `name` is the secondary tiebreaker for every other column so equal
// values still land in a stable alphabetical order.
function compare(a: Platform, b: Platform): number {
const dir = sortDir.value === "asc" ? 1 : -1;
// Sort axis the grid view should use, derived from the active groupBy.
// Grid has no column headers — the bucket axis is the natural sort axis,
// the toolbar asc/desc toggle is the only direction control.
const gridSortKey = computed<PlatformSortKey>(() => {
switch (groupBy.value) {
case "family":
return "family";
case "category":
return "category";
case "generation":
return "generation";
case "playable":
return "playable";
default:
return "name";
}
});
// Pure comparator parameterised by (key, dir). Both sort states feed it
// to produce their respective sorted arrays. `name` is the secondary
// tiebreaker for every other column so equal values still land in a
// stable alphabetical order.
function compareBy(
a: Platform,
b: Platform,
key: PlatformSortKey,
dir: "asc" | "desc",
): number {
const sign = dir === "asc" ? 1 : -1;
const byName = a.display_name.localeCompare(b.display_name);
switch (sortKey.value) {
switch (key) {
case "name":
return byName * dir;
return byName * sign;
case "family": {
const af = a.family_name ?? "";
const bf = b.family_name ?? "";
const cmp = af.localeCompare(bf);
return (cmp || byName) * dir;
return (cmp || byName) * sign;
}
case "category": {
const ac = a.category ?? "";
const bc = b.category ?? "";
const cmp = ac.localeCompare(bc);
return (cmp || byName) * dir;
return (cmp || byName) * sign;
}
case "generation": {
const ag = a.generation ?? -1;
const bg = b.generation ?? -1;
const cmp = ag - bg;
return (cmp || byName) * dir;
return (cmp || byName) * sign;
}
case "playable": {
const ap = playableById.value.get(a.id) ? 1 : 0;
const bp = playableById.value.get(b.id) ? 1 : 0;
const cmp = ap - bp;
return (cmp || byName) * dir;
return (cmp || byName) * sign;
}
case "rom_count": {
const ar = a.rom_count ?? 0;
const br = b.rom_count ?? 0;
const cmp = ar - br;
return (cmp || byName) * dir;
return (cmp || byName) * sign;
}
}
}
@@ -164,11 +197,19 @@ const filtered = computed<Platform[]>(() => {
);
});
// Sorted view of the filtered list. Single source of truth feeding both
// the flat layouts and the bucket builders (which preserve insertion
// order, so items inside each bucket inherit this sort).
const sorted = computed<Platform[]>(() => {
return [...filtered.value].sort(compare);
// 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
// inside each bucket inherit that order).
const sortedForGrid = computed<Platform[]>(() => {
return [...filtered.value].sort((a, b) =>
compareBy(a, b, gridSortKey.value, gridSortDir.value),
);
});
const sortedForList = computed<Platform[]>(() => {
return [...filtered.value].sort((a, b) =>
compareBy(a, b, listSortKey.value, listSortDir.value),
);
});
const totalCount = computed(() => filledPlatforms.value.length);
@@ -202,32 +243,34 @@ function bucketBy(
return [...map.values()].sort(sort);
}
// Letter buckets. Non-alpha first chars roll up under "#" so Greek /
// numeric / symbol-prefixed platform names still land in a stable
// section.
const letterGroups = computed<Bucket[]>(() =>
bucketBy(
sorted.value,
// Letter buckets. Non-letter first chars split into two head buckets so
// the user can tell digits apart from other symbols at a glance:
// * "#" — digits (0-9)
// * "@" — anything else (Greek, punctuation, etc.)
// Order in asc: `# A…Z @` — `#` first, `@` last (matches AlphaStrip's
// ALPHABET). Desc flips the whole sequence (`@ Z…A #`).
const BUCKET_ORDER = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ@";
const letterGroups = computed<Bucket[]>(() => {
const dirSign = gridSortDir.value === "asc" ? 1 : -1;
return bucketBy(
sortedForGrid.value,
(p) => {
const ch = p.display_name.charAt(0).toUpperCase();
const key = /[A-Z]/.test(ch) ? ch : "#";
return { key, label: key };
if (/[A-Z]/.test(ch)) return { key: ch, label: ch };
if (/[0-9]/.test(ch)) return { key: "#", label: "#" };
return { key: "@", label: "@" };
},
(a, b) => {
// "#" sorts after letters so the alphabetical run is unbroken.
if (a.key === "#") return 1;
if (b.key === "#") return -1;
return a.key.localeCompare(b.key);
},
),
);
(a, b) =>
(BUCKET_ORDER.indexOf(a.key) - BUCKET_ORDER.indexOf(b.key)) * dirSign,
);
});
// Family buckets. `family_slug` is the stable id (cheap to use as a
// Map key); `family_name` is what the user reads. Platforms without a
// family land in "Other" and sort last.
const familyGroups = computed<Bucket[]>(() =>
bucketBy(
sorted.value,
sortedForGrid.value,
(p) => {
const slug = p.family_slug;
const name = p.family_name;
@@ -248,7 +291,7 @@ const familyGroups = computed<Bucket[]>(() =>
// label without altering the underlying key.
const categoryGroups = computed<Bucket[]>(() =>
bucketBy(
sorted.value,
sortedForGrid.value,
(p) => {
const c = p.category;
if (c) return { key: c, label: prettifyPlatformCategory(c) };
@@ -267,7 +310,7 @@ const categoryGroups = computed<Bucket[]>(() =>
// list-mode metadata column and the group heading agree word-for-word.
const generationGroups = computed<Bucket[]>(() =>
bucketBy(
sorted.value,
sortedForGrid.value,
(p) => {
const g = p.generation;
if (typeof g === "number" && g > 0) {
@@ -292,7 +335,7 @@ const generationGroups = computed<Bucket[]>(() =>
// top regardless of sort direction.
const playableGroups = computed<Bucket[]>(() =>
bucketBy(
sorted.value,
sortedForGrid.value,
(p) =>
playableById.value.get(p.id)
? { key: "playable", label: "Playable" }
@@ -336,21 +379,23 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
<GalleryToolbar
:group-by="groupBy"
:layout="layout"
:sort-dir="gridSortDir"
:search="searchTerm"
:group-by-items="platformGroupByItems"
show-search
search-placeholder="Search platforms"
@update:group-by="groupBy = $event"
@update:layout="layout = $event"
@update:sort-dir="gridSortDir = $event"
@update:search="searchTerm = $event"
/>
</template>
<template #listHeader>
<PlatformListHeader
:sort-key="sortKey"
:sort-dir="sortDir"
@sort="onSort"
:sort-key="listSortKey"
:sort-dir="listSortDir"
@sort="onListSort"
/>
</template>
@@ -381,7 +426,7 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
would have separated them. -->
<div v-else-if="layout === 'list'" class="r-v2-pidx__list">
<PlatformListRow
v-for="p in sorted"
v-for="p in sortedForList"
:key="p.id"
:id="p.id"
:slug="p.slug"
@@ -419,7 +464,7 @@ const groupedBuckets = computed<Bucket[] | null>(() => {
<!-- Grid mode, flat. -->
<div v-else class="r-v2-pidx__grid">
<PlatformTile
v-for="p in sorted"
v-for="p in sortedForGrid"
:id="p.id"
:key="p.id"
:slug="p.slug"