Files
romm/frontend/src/components/Dialogs/CreateSmartCollectionDialog.vue
2026-10-27 08:21:22 -04:00

428 lines
13 KiB
Vue

<script setup lang="ts">
// CreateSmartCollectionDialog: captures the current galleryFilter state
// as a smart collection. v2 replacement for v1's
// `components/common/Collection/Dialog/CreateSmartCollection.vue`.
//
// Flow:
// • Emitter fires `showCreateSmartCollectionDialog` (typically from
// the FilterDrawer footer CTA).
// • If no filters are active we refuse to open and surface a snackbar
// hint: same guard v1 had, just routed through the v2 channel.
// • The dialog snapshots `galleryFilter` once on open (so further
// toggles in the gallery don't leak into the preview) and lets the
// user name / describe / mark public.
// • Submit → POST /collections/smart → store add → navigate to the
// freshly-created smart collection.
//
// Serialization + summary live in `@/utils/smartCollectionCriteria`
// so the read-only display inside CollectionSettingsDrawer renders from
// the same rules.
import { storeToRefs } from "pinia";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import VisibilitySwitch from "@/components/shared/VisibilitySwitch.vue";
import { useBreakpoint } from "@/composables/useBreakpoint";
import { useEmitterEvent } from "@/composables/useEmitterEvent";
import { useSnackbar } from "@/composables/useSnackbar";
import { RBtn, RChip, RDialog, RForm, RIcon, RTextField, RTag } from "@/lib";
import { ROUTES } from "@/plugins/router";
import collectionApi from "@/services/api/collection";
import storeCollections from "@/stores/collections";
import storeGalleryFilter from "@/stores/galleryFilter";
import storeGalleryRoms from "@/stores/galleryRoms";
import storePlatforms from "@/stores/platforms";
import { toBrowserLocale } from "@/utils";
import {
buildSmartFilterCriteria,
hasAnySmartFilterCriteria,
summarizeSmartFilterCriteria,
type SmartFilterCriteria,
} from "@/utils/smartCollectionCriteria";
import { required } from "@/utils/validation";
defineOptions({ inheritAttrs: false });
const { t, locale } = useI18n();
const { mdAndUp } = useBreakpoint();
const router = useRouter();
const snackbar = useSnackbar();
const galleryFilter = storeGalleryFilter();
const galleryRoms = storeGalleryRoms();
const collectionsStore = storeCollections();
const platformsStore = storePlatforms();
const { allPlatforms } = storeToRefs(platformsStore);
const show = ref(false);
const submitting = ref(false);
const formValid = ref(true);
const name = ref("");
const description = ref("");
const isPublic = ref(false);
// Snapshot the criteria once when the dialog opens. We don't want the
// preview to keep updating as the user toggles filters in the gallery
// behind the dialog: what the user saw at the moment they clicked the
// CTA is what gets saved.
const snapshot = ref<SmartFilterCriteria>({});
const nameRules = [required(t("common.required"))];
const openHandler = () => {
// v1 guarded with a snackbar warning here: keep that behaviour so
// the user gets a hint instead of an empty preview.
const next = buildSmartFilterCriteria(
{
searchTerm: galleryFilter.searchTerm,
filterMatched: galleryFilter.filterMatched,
filterFavorites: galleryFilter.filterFavorites,
filterDuplicates: galleryFilter.filterDuplicates,
filterPlayables: galleryFilter.filterPlayables,
filterRA: galleryFilter.filterRA,
filterSaves: galleryFilter.filterSaves,
filterStates: galleryFilter.filterStates,
filterSoundtrack: galleryFilter.filterSoundtrack,
filterMissing: galleryFilter.filterMissing,
filterPhysical: galleryFilter.filterPhysical,
filterVerified: galleryFilter.filterVerified,
selectedPlatforms: galleryFilter.selectedPlatforms,
selectedGenres: galleryFilter.selectedGenres,
genresLogic: galleryFilter.genresLogic,
selectedFranchises: galleryFilter.selectedFranchises,
franchisesLogic: galleryFilter.franchisesLogic,
selectedCollections: galleryFilter.selectedCollections,
collectionsLogic: galleryFilter.collectionsLogic,
selectedCompanies: galleryFilter.selectedCompanies,
companiesLogic: galleryFilter.companiesLogic,
selectedPublishers: galleryFilter.selectedPublishers,
publishersLogic: galleryFilter.publishersLogic,
selectedDevelopers: galleryFilter.selectedDevelopers,
developersLogic: galleryFilter.developersLogic,
selectedAgeRatings: galleryFilter.selectedAgeRatings,
ageRatingsLogic: galleryFilter.ageRatingsLogic,
selectedRegions: galleryFilter.selectedRegions,
regionsLogic: galleryFilter.regionsLogic,
selectedLanguages: galleryFilter.selectedLanguages,
languagesLogic: galleryFilter.languagesLogic,
selectedPlayerCounts: galleryFilter.selectedPlayerCounts,
playerCountsLogic: galleryFilter.playerCountsLogic,
selectedMetadataProviders: galleryFilter.selectedMetadataProviders,
metadataProvidersLogic: galleryFilter.metadataProvidersLogic,
selectedLengthMinHours: galleryFilter.selectedLengthMinHours,
selectedLengthMaxHours: galleryFilter.selectedLengthMaxHours,
selectedTags: galleryFilter.selectedTags,
tagsLogic: galleryFilter.tagsLogic,
selectedStatuses: galleryFilter.selectedStatuses,
statusesLogic: galleryFilter.statusesLogic,
},
{
currentPlatform: galleryRoms.currentPlatform,
currentCollectionId: galleryRoms.currentCollection?.id ?? null,
currentVirtualCollectionId:
galleryRoms.currentVirtualCollection?.id ?? null,
currentSmartCollectionId: galleryRoms.currentSmartCollection?.id ?? null,
},
);
if (!hasAnySmartFilterCriteria(next)) {
snackbar.warning(t("collection.smart-no-filters"), {
icon: "mdi-information",
});
return;
}
snapshot.value = next;
name.value = "";
description.value = "";
isPublic.value = false;
show.value = true;
};
useEmitterEvent("showCreateSmartCollectionDialog", openHandler);
// Platform / collection lookups so the summary renders human-readable
// names ("SNES", "Castlevania") instead of `#1`. Each returns null when
// the store hasn't hydrated yet.
function platformLookup(id: number): string | null {
return allPlatforms.value.find((p) => p.id === id)?.display_name ?? null;
}
function collectionLookup(id: number): string | null {
return collectionsStore.getCollection(id)?.name ?? null;
}
function virtualCollectionLookup(id: string): string | null {
return collectionsStore.getVirtualCollection(id)?.name ?? null;
}
function smartCollectionLookup(id: number): string | null {
return collectionsStore.getSmartCollection(id)?.name ?? null;
}
const summary = computed(() =>
summarizeSmartFilterCriteria(
snapshot.value,
t,
{
platform: platformLookup,
collection: collectionLookup,
virtualCollection: virtualCollectionLookup,
smartCollection: smartCollectionLookup,
},
toBrowserLocale(locale.value),
),
);
function close() {
show.value = false;
}
async function submit() {
if (submitting.value) return;
if (!name.value.trim()) return;
const trimmed = name.value.trim();
if (collectionsStore.smartCollections.some((c) => c.name === trimmed)) {
snackbar.error(t("collection.name-exists"), { icon: "mdi-close-circle" });
return;
}
submitting.value = true;
try {
const trimmedDescription = description.value.trim();
const data = await collectionApi.createSmartCollection({
smartCollection: {
name: name.value.trim(),
...(trimmedDescription ? { description: trimmedDescription } : {}),
filter_criteria: snapshot.value,
is_public: isPublic.value,
},
});
collectionsStore.addSmartCollection(data);
snackbar.success(t("collection.smart-created"), { icon: "mdi-check-bold" });
show.value = false;
void router.push({
name: ROUTES.SMART_COLLECTION,
params: { collection: data.id },
});
} catch (err) {
const e = err as {
response?: { data?: { msg?: string; detail?: string } };
message?: string;
};
snackbar.error(
`${t("collection.smart-create-failed")}: ${
e?.response?.data?.msg ||
e?.response?.data?.detail ||
e?.message ||
t("common.unknown-error")
}`,
{ icon: "mdi-close-circle" },
);
} finally {
submitting.value = false;
}
}
</script>
<template>
<RDialog
v-model="show"
icon="mdi-playlist-plus"
:width="mdAndUp ? 640 : '95vw'"
cancelable
:cancel-disabled="submitting"
@close="close"
>
<template #header>
<span>{{ t("collection.create-smart-collection") }}</span>
</template>
<template #content>
<RForm v-model="formValid" class="r-csc__form" @submit="submit">
<div class="r-csc__grid">
<!-- Left column: editable fields -->
<div class="r-csc__fields">
<!-- eslint-disable vuejs-accessibility/no-autofocus -- autofocusing the first field on dialog open is intentional modal UX -->
<RTextField
v-model="name"
:placeholder="t('collection.name')"
prefix-label="stacked"
:rules="nameRules"
required
autofocus
>
<template #prefix-label>
{{ t("collection.name") }}
</template>
</RTextField>
<!-- eslint-enable vuejs-accessibility/no-autofocus -->
<RTextField
v-model="description"
:placeholder="t('collection.description')"
prefix-label="stacked"
multiline
:rows="3"
hide-details
>
<template #prefix-label>
{{ t("collection.description") }}
</template>
</RTextField>
<VisibilitySwitch v-model="isPublic" />
</div>
<!-- Right column: criteria preview -->
<aside class="r-csc__preview">
<header class="r-csc__preview-head">
<RIcon icon="mdi-filter-variant" size="14" />
<span>{{ t("collection.current-filters") }}</span>
</header>
<ul class="r-csc__preview-list">
<li
v-for="row in summary"
:key="row.key"
class="r-csc__preview-row"
>
<span class="r-csc__preview-label">
<RIcon :icon="row.icon" size="14" />
<span>{{ row.label }}</span>
<RTag
v-if="row.logic"
tone="brand"
size="x-small"
class="r-csc__preview-logic"
>
{{ row.logic }}
</RTag>
</span>
<div v-if="row.values?.length" class="r-csc__preview-values">
<RChip
v-for="(v, i) in row.values"
:key="`${row.key}-${i}`"
size="x-small"
variant="translucent"
>
{{ v }}
</RChip>
</div>
</li>
</ul>
</aside>
</div>
</RForm>
</template>
<template #footer>
<RBtn
variant="flat"
color="primary"
prepend-icon="mdi-playlist-plus"
:disabled="!name.trim() || submitting"
:loading="submitting"
@click="submit"
>
{{ t("common.create") }}
</RBtn>
</template>
</RDialog>
</template>
<style scoped>
.r-csc__form {
display: block;
}
.r-csc__grid {
display: grid;
grid-template-columns: 1fr;
gap: 18px;
}
html[data-bp~="sm-and-up"] .r-csc__grid {
grid-template-columns: 1.1fr 1fr;
align-items: stretch;
}
.r-csc__fields {
display: flex;
flex-direction: column;
gap: 12px;
}
.r-csc__preview {
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
background: var(--r-color-bg-elevated);
border: 1px solid var(--r-color-border);
border-radius: var(--r-radius-md);
min-height: 200px;
/* Bound the panel so a filter-heavy snapshot can't stretch the dialog
past the viewport: the head stays pinned, the list scrolls. */
max-height: clamp(200px, 48vh, 420px);
}
.r-csc__preview-head {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 8px;
font-size: 11px;
font-weight: var(--r-font-weight-bold);
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--r-color-fg-muted);
}
.r-csc__preview-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 10px;
/* Scroll the criteria list inside the panel instead of overflowing
the dialog when there are many active filters. */
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--r-color-border-strong) transparent;
/* Keep chips off the scrollbar gutter. */
padding-right: 4px;
}
.r-csc__preview-list::-webkit-scrollbar {
width: 8px;
}
.r-csc__preview-list::-webkit-scrollbar-thumb {
background: var(--r-color-border-strong);
border-radius: 4px;
}
.r-csc__preview-row {
display: flex;
flex-direction: column;
gap: 6px;
}
.r-csc__preview-label {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--r-color-fg-secondary);
font-size: var(--r-font-size-sm);
font-weight: var(--r-font-weight-semibold);
}
.r-csc__preview-logic {
margin-left: 4px;
text-transform: uppercase;
}
.r-csc__preview-values {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding-left: 20px;
}
</style>