more work on frontend

This commit is contained in:
Georges-Antoine Assi committed 2025-07-22 18:47:38 -04:00
1 parent f7b030ba10
commit 526685b479
20 files changed
+367 -308

No files matched your search

+5
View File
@@ -181,6 +181,10 @@ def get_roms(
str | None,
Query(description="Virtual collection internal id."),
] = None,
smart_collection_id: Annotated[
int | None,
Query(description="Smart collection internal id.", ge=1),
] = None,
matched: Annotated[
bool | None,
Query(description="Whether the rom matched a metadata source."),
@@ -274,6 +278,7 @@ def get_roms(
platform_id=platform_id,
collection_id=collection_id,
virtual_collection_id=virtual_collection_id,
smart_collection_id=smart_collection_id,
search_term=search_term,
matched=matched,
favourite=favourite,
+18
View File
@@ -178,6 +178,18 @@ class DBRomsHandler(DBBaseHandler):
return query.filter(Rom.id.in_(v_collection.rom_ids))
return query
def filter_by_smart_collection_id(
self, query: Query, session: Session, smart_collection_id: int
):
smart_collection = (
session.query(Collection)
.filter(Collection.id == smart_collection_id)
.one_or_none()
)
if smart_collection:
return query.filter(Rom.id.in_(smart_collection.rom_ids))
return query
def filter_by_search_term(self, query: Query, search_term: str):
return query.filter(
or_(
@@ -390,6 +402,7 @@ class DBRomsHandler(DBBaseHandler):
platform_id: int | None = None,
collection_id: int | None = None,
virtual_collection_id: str | None = None,
smart_collection_id: int | None = None,
search_term: str | None = None,
matched: bool | None = None,
favourite: bool | None = None,
@@ -421,6 +434,11 @@ class DBRomsHandler(DBBaseHandler):
query, session, virtual_collection_id
)
if smart_collection_id:
query = self.filter_by_smart_collection_id(
query, session, smart_collection_id
)
if search_term:
query = self.filter_by_search_term(query, search_term)
+1 -1
View File
@@ -24,7 +24,7 @@
"build": "npm run typecheck && vite build",
"preview": "vite preview",
"typecheck": "vue-tsc --noEmit",
"generate": "openapi --input http://127.0.0.1:5000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false"
"generate": "openapi --input http://127.0.0.1:3000/openapi.json --output ./src/__generated__ --client axios --useOptions --useUnionTypes --exportServices false --exportSchemas false --exportCore false"
},
"dependencies": {
"@mdi/font": "7.4.47",
+1
View File
@@ -60,6 +60,7 @@ export type { SearchCoverSchema } from './models/SearchCoverSchema';
export type { SearchRomSchema } from './models/SearchRomSchema';
export type { SiblingRomSchema } from './models/SiblingRomSchema';
export type { SimpleRomSchema } from './models/SimpleRomSchema';
export type { SmartCollectionSchema } from './models/SmartCollectionSchema';
export type { StateSchema } from './models/StateSchema';
export type { StatsReturn } from './models/StatsReturn';
export type { SystemDict } from './models/SystemDict';
+2 -2
View File
@@ -11,6 +11,8 @@ export type CollectionSchema = {
path_cover_large: (string | null);
path_covers_small: Array<string>;
path_covers_large: Array<string>;
created_at: string;
updated_at: string;
id: number;
url_cover: (string | null);
user_id: number;
@@ -18,7 +20,5 @@ export type CollectionSchema = {
is_public: boolean;
is_favorite: boolean;
is_virtual?: boolean;
created_at: string;
updated_at: string;
};
@@ -0,0 +1,24 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type SmartCollectionSchema = {
name: string;
description?: string;
rom_ids?: Array<number>;
rom_count: number;
path_cover_small: (string | null);
path_cover_large: (string | null);
path_covers_small: Array<string>;
path_covers_large: Array<string>;
created_at: string;
updated_at: string;
id: number;
filter_criteria: Record<string, any>;
filter_summary: string;
user_id: number;
user__username: string;
is_public: boolean;
is_smart?: boolean;
};
@@ -11,12 +11,12 @@ export type VirtualCollectionSchema = {
path_cover_large: (string | null);
path_covers_small: Array<string>;
path_covers_large: Array<string>;
created_at: string;
updated_at: string;
id: string;
type: string;
is_public?: boolean;
is_favorite?: boolean;
is_virtual?: boolean;
created_at: string;
updated_at: string;
};
@@ -6,23 +6,34 @@ import storeNavigation from "@/stores/navigation";
import storeRoms from "@/stores/roms";
import { storeToRefs } from "pinia";
import { useDisplay } from "vuetify";
import { computed } from "vue";
// Props
const { xs } = useDisplay();
const navigationStore = storeNavigation();
const romsStore = storeRoms();
const { currentCollection } = storeToRefs(romsStore);
const { currentCollection, currentVirtualCollection, currentSmartCollection } =
storeToRefs(romsStore);
// Get the currently active collection (any type)
const activeCollection = computed(() => {
return (
currentCollection.value ||
currentVirtualCollection.value ||
currentSmartCollection.value
);
});
</script>
<template>
<base-gallery-app-bar show-platforms-filter :show-search-bar="!xs">
<template #prepend>
<r-avatar
v-if="currentCollection"
v-if="activeCollection"
@click="navigationStore.switchActiveCollectionInfoDrawer"
class="collection-icon cursor-pointer"
:size="45"
:collection="currentCollection"
:collection="activeCollection"
/>
</template>
</base-gallery-app-bar>
@@ -24,8 +24,28 @@ const emitter = inject<Emitter<Events>>("emitter");
const auth = storeAuth();
const romsStore = storeRoms();
const collectionsStore = storeCollection();
const { currentCollection } = storeToRefs(romsStore);
const { currentCollection, currentVirtualCollection, currentSmartCollection } =
storeToRefs(romsStore);
const navigationStore = storeNavigation();
// Get the currently active collection (any type)
const activeCollection = computed(() => {
return (
currentCollection.value ||
currentVirtualCollection.value ||
currentSmartCollection.value
);
});
// Check if the active collection is editable (only regular collections are editable for now)
const isCollectionEditable = computed(() => {
return (
currentCollection.value &&
currentCollection.value.user__username === auth.user?.username &&
auth.scopes.includes("collections.write")
);
});
const imagePreviewUrl = ref<string | undefined>("");
const removeCover = ref(false);
const heartbeat = storeHeartbeat();
@@ -130,7 +150,7 @@ async function updateCollection() {
<template>
<v-navigation-drawer
v-if="currentCollection"
v-if="activeCollection"
mobile
floating
width="500"
@@ -145,12 +165,7 @@ async function updateCollection() {
<v-col style="max-width: 240px" cols="12">
<div class="text-center justify-center align-center">
<div class="position-absolute append-top-right mr-5">
<template
v-if="
currentCollection.user__username === auth.user?.username &&
auth.scopes.includes('collections.write')
"
>
<template v-if="isCollectionEditable">
<v-btn
v-if="!isEditable"
:loading="updating"
@@ -182,10 +197,10 @@ async function updateCollection() {
</template>
</div>
<collection-card
:key="currentCollection.updated_at"
:key="activeCollection.updated_at"
:show-title="false"
:with-link="false"
:collection="currentCollection"
:collection="activeCollection"
:src="imagePreviewUrl"
>
<template v-if="isEditable" #append-inner>
@@ -199,7 +214,7 @@ async function updateCollection() {
class="translucent-dark"
@click="
emitter?.emit('showSearchCoverDialog', {
term: currentCollection.name as string,
term: activeCollection.name as string,
aspectRatio: null,
})
"
@@ -240,23 +255,23 @@ async function updateCollection() {
<div v-if="!isEditable">
<div>
<span class="text-h5 font-weight-bold pl-0">{{
currentCollection.name
activeCollection.name
}}</span>
</div>
<div>
<span class="text-subtitle-2">{{
currentCollection.description
activeCollection.description
}}</span>
</div>
<v-chip
class="mt-4"
size="small"
:color="currentCollection.is_public ? 'primary' : ''"
:color="activeCollection.is_public ? 'primary' : ''"
><v-icon class="mr-1">{{
currentCollection.is_public ? "mdi-lock-open" : "mdi-lock"
activeCollection.is_public ? "mdi-lock-open" : "mdi-lock"
}}</v-icon
>{{
currentCollection.is_public
activeCollection.is_public
? t("collection.public")
: t("collection.private")
}}</v-chip
@@ -311,11 +326,11 @@ async function updateCollection() {
<v-chip size="small" class="mr-2 px-0" label>
<v-chip label>{{ field.label }}</v-chip
><span class="px-2">{{
currentCollection[
field.key as keyof typeof currentCollection
activeCollection[
field.key as keyof typeof activeCollection
]?.toString()
? currentCollection[
field.key as keyof typeof currentCollection
? activeCollection[
field.key as keyof typeof activeCollection
]
: "N/A"
}}</span>
@@ -329,7 +344,7 @@ async function updateCollection() {
<r-section
v-if="
auth.scopes.includes('collections.write') &&
currentCollection.user__username === auth.user?.username
activeCollection.user__username === auth.user?.username
"
icon="mdi-alert"
icon-color="red"
@@ -345,7 +360,7 @@ async function updateCollection() {
class="text-romm-red bg-toplayer ma-2"
variant="flat"
@click="
emitter?.emit('showDeleteCollectionDialog', currentCollection)
emitter?.emit('showDeleteCollectionDialog', activeCollection)
"
>
<v-icon class="text-romm-red mr-2">mdi-delete</v-icon>
@@ -17,8 +17,12 @@ const router = useRouter();
const emitter = inject<Emitter<Events>>("emitter");
const galleryFilterStore = storeGalleryFilter();
const romsStore = storeRoms();
const { currentPlatform, currentCollection, currentVirtualCollection } =
storeToRefs(romsStore);
const {
currentPlatform,
currentCollection,
currentVirtualCollection,
currentSmartCollection,
} = storeToRefs(romsStore);
const {
searchTerm,
@@ -42,7 +46,7 @@ const {
async function goToRandomGame() {
try {
const apiParams = {
let apiParams = {
limit: 1,
offset: 0,
platformId: currentPlatform.value?.id || null,
@@ -70,6 +74,17 @@ async function goToRandomGame() {
selectedLanguage: selectedLanguage.value,
};
// If we're in a smart collection, apply its filter criteria instead of collection ID
if (currentSmartCollection.value) {
const criteria = currentSmartCollection.value.filter_criteria;
apiParams = {
...apiParams,
...criteria,
// Smart collections don't use collectionId
collectionId: null,
};
}
// Get the total count first
const { data: romsResponse } = await romApi.getRoms(apiParams);
+6 -2
View File
@@ -14,7 +14,8 @@ import { storeToRefs } from "pinia";
// Props
const { t } = useI18n();
const collections = storeCollections();
const { allCollectionsUnified } = storeToRefs(collections);
const { filteredCollections, filteredSmartCollections } =
storeToRefs(collections);
const storedCollections = localStorage.getItem("settings.gridCollections");
const gridCollections = ref(
isNull(storedCollections) ? false : storedCollections === "true",
@@ -60,7 +61,10 @@ function onHover(emitData: { isHovering: boolean; id: number }) {
no-gutters
>
<v-col
v-for="collection in allCollectionsUnified"
v-for="collection in [
...filteredCollections,
...filteredSmartCollections,
]"
:key="`${'filter_criteria' in collection ? 'smart' : 'regular'}-${collection.id}`"
class="pa-1"
:cols="views[0]['size-cols']"
@@ -119,6 +119,25 @@ const emit = defineEmits(["hover"]);
const tiltCard = ref<TiltHTMLElement | null>(null);
// Determine the correct route for this collection type
const collectionRoute = computed(() => {
if (!props.withLink || !props.collection) return {};
// Check if it's a smart collection (has filter_criteria property)
if ("filter_criteria" in props.collection) {
return {
name: ROUTES.SMART_COLLECTION,
params: { collection: props.collection.id },
};
}
// Default to regular collection route for both regular and virtual collections
return {
name: ROUTES.COLLECTION,
params: { collection: props.collection.id },
};
});
onMounted(() => {
if (tiltCard.value && !smAndDown.value && props.enable3DTilt) {
VanillaTilt.init(tiltCard.value, {
@@ -144,14 +163,7 @@ onBeforeUnmount(() => {
<v-card
v-bind="{
...hoverProps,
...(withLink && collection
? {
to: {
name: ROUTES.COLLECTION,
params: { collection: collection.id },
},
}
: {}),
...collectionRoute,
}"
:class="{
'on-hover': isHovering,
@@ -8,7 +8,7 @@ import RAvatar from "@/components/common/Collection/RAvatar.vue";
import { ROUTES } from "@/plugins/router";
// Props
withDefaults(
const props = withDefaults(
defineProps<{
collection: Collection | VirtualCollection | SmartCollection;
withTitle?: boolean;
@@ -23,20 +23,30 @@ withDefaults(
withLink: false,
},
);
// Determine the correct route for this collection type
const getCollectionRoute = () => {
if (!props.withLink || !props.collection) return {};
// Check if it's a smart collection (has filter_criteria property)
if ("filter_criteria" in props.collection) {
return {
name: ROUTES.SMART_COLLECTION,
params: { collection: props.collection.id },
};
}
// Default to regular collection route for both regular and virtual collections
return {
name: ROUTES.COLLECTION,
params: { collection: props.collection.id },
};
};
</script>
<template>
<v-list-item
v-bind="{
...(withLink && collection
? {
to: {
name: ROUTES.COLLECTION,
params: { collection: collection.id },
},
}
: {}),
}"
v-bind="getCollectionRoute()"
:value="collection.id"
rounded
density="compact"
@@ -32,14 +32,22 @@ const { activeCollectionsDrawer } = storeToRefs(navigationStore);
@click="navigationStore.switchActiveCollectionsDrawer"
>
<div class="d-flex flex-column align-center">
<v-icon :color="$route.name == 'collection' ? 'primary' : ''"
<v-icon
:color="
$route.name == 'collection' || $route.name == 'smart-collection'
? 'primary'
: ''
"
>mdi-bookmark-box-multiple</v-icon
>
<v-expand-transition>
<span
v-if="withTag"
class="text-caption text-center"
:class="{ 'text-primary': $route.name == 'collection' }"
:class="{
'text-primary':
$route.name == 'collection' || $route.name == 'smart-collection',
}"
>Collections</span
>
</v-expand-transition>
+12
View File
@@ -22,6 +22,8 @@ export const ROUTES = {
SEARCH: "search",
PLATFORM: "platform",
COLLECTION: "collection",
VIRTUAL_COLLECTION: "virtual-collection",
SMART_COLLECTION: "smart-collection",
ROM: "rom",
EMULATORJS: "emulatorjs",
RUFFLE: "ruffle",
@@ -125,6 +127,16 @@ const routes = [
name: ROUTES.COLLECTION,
component: () => import("@/views/Gallery/Collection.vue"),
},
{
path: "collection/virtual/:collection",
name: ROUTES.VIRTUAL_COLLECTION,
component: () => import("@/views/Gallery/Collection.vue"),
},
{
path: "collection/smart/:collection",
name: ROUTES.SMART_COLLECTION,
component: () => import("@/views/Gallery/Collection.vue"),
},
{
path: "rom/:rom",
name: ROUTES.ROM,
+72 -113
View File
@@ -1,50 +1,16 @@
import type { MessageResponse } from "@/__generated__";
import api from "@/services/api/index";
import type { Collection, VirtualCollection } from "@/stores/collections";
import type {
Collection,
VirtualCollection,
SmartCollection,
} from "@/stores/collections";
export type UpdatedCollection = Collection & {
artwork?: File;
url_cover?: string | null;
};
// Smart Collection types
export interface SmartCollectionSchema {
id: number;
name: string;
description: string | null;
filter_criteria: Record<string, any>;
filter_summary: string;
rom_count: number;
path_cover_small: string | null;
path_cover_large: string | null;
url_cover: string | null;
user_id: number;
user__username: string;
is_public: boolean;
is_smart: boolean;
created_at: string;
updated_at: string;
}
export interface CreateSmartCollectionParams {
name: string;
description?: string;
filter_criteria: Record<string, any>;
url_cover?: string;
is_public?: boolean;
artwork?: File;
}
export interface UpdateSmartCollectionParams {
name?: string;
description?: string;
filter_criteria?: Record<string, any>;
url_cover?: string;
is_public?: boolean;
remove_cover?: boolean;
artwork?: File;
}
export const collectionApi = api;
async function createCollection({
@@ -53,12 +19,40 @@ async function createCollection({
collection: UpdatedCollection;
}): Promise<{ data: Collection }> {
const formData = new FormData();
formData.append("name", collection.name || "");
formData.append("description", collection.description || "");
formData.append("url_cover", collection.url_cover || "");
formData.append("rom_ids", JSON.stringify(collection.rom_ids));
if (collection.artwork) formData.append("artwork", collection.artwork);
return api.post(`/collections`, formData);
return api.post(`/collections`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
}
async function createSmartCollection({
smartCollection,
}: {
smartCollection: SmartCollection;
}): Promise<{ data: SmartCollection }> {
const formData = new FormData();
formData.append("name", smartCollection.name);
formData.append("description", smartCollection.description || "");
formData.append(
"filter_criteria",
JSON.stringify(smartCollection.filter_criteria),
);
formData.append("is_public", String(smartCollection.is_public || false));
return api.post("/collections/smart", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
}
async function getCollections(): Promise<{ data: Collection[] }> {
@@ -74,6 +68,10 @@ async function getVirtualCollections({
return api.get("/collections/virtual", { params: { type } });
}
async function getSmartCollections(): Promise<{ data: SmartCollection[] }> {
return api.get("/collections/smart");
}
async function getCollection(id: number): Promise<{ data: Collection }> {
return api.get(`/collections/${id}`);
}
@@ -84,6 +82,12 @@ async function getVirtualCollection(
return api.get(`/collections/virtual/${id}`);
}
async function getSmartCollection(
id: number,
): Promise<{ data: SmartCollection }> {
return api.get(`/collections/smart/${id}`);
}
async function updateCollection({
collection,
removeCover = false,
@@ -98,10 +102,37 @@ async function updateCollection({
formData.append("rom_ids", JSON.stringify(collection.rom_ids));
if (collection.artwork) formData.append("artwork", collection.artwork);
return api.put(`/collections/${collection.id}`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
params: { is_public: collection.is_public, remove_cover: removeCover },
});
}
async function updateSmartCollection({
smartCollection,
}: {
smartCollection: SmartCollection;
}): Promise<{ data: SmartCollection }> {
const formData = new FormData();
formData.append("name", smartCollection.name || "");
formData.append("description", smartCollection.description || "");
formData.append(
"filter_criteria",
JSON.stringify(smartCollection.filter_criteria),
);
return api.put(`/collections/smart/${smartCollection.id}`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
params: {
is_public: smartCollection.is_public,
},
});
}
async function deleteCollection({
collection,
}: {
@@ -110,76 +141,6 @@ async function deleteCollection({
return api.delete(`/collections/${collection.id}`);
}
// Smart Collection functions
async function getSmartCollections(): Promise<{
data: SmartCollectionSchema[];
}> {
return api.get("/collections/smart");
}
async function getSmartCollection(
id: number,
): Promise<{ data: SmartCollectionSchema }> {
return api.get(`/collections/smart/${id}`);
}
async function getSmartCollectionRoms(
id: number,
): Promise<{ data: { items: any[]; total: number } }> {
return api.get(`/collections/smart/${id}/roms`);
}
async function createSmartCollection(
params: CreateSmartCollectionParams,
): Promise<{ data: SmartCollectionSchema }> {
const formData = new FormData();
formData.append("name", params.name);
if (params.description) formData.append("description", params.description);
formData.append("filter_criteria", JSON.stringify(params.filter_criteria));
if (params.url_cover) formData.append("url_cover", params.url_cover);
formData.append("is_public", String(params.is_public || false));
if (params.artwork) formData.append("artwork", params.artwork);
return api.post("/collections/smart", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
}
async function updateSmartCollection(
id: number,
params: UpdateSmartCollectionParams,
): Promise<{ data: SmartCollectionSchema }> {
const formData = new FormData();
if (params.name) formData.append("name", params.name);
if (params.description !== undefined)
formData.append("description", params.description);
if (params.filter_criteria)
formData.append("filter_criteria", JSON.stringify(params.filter_criteria));
if (params.url_cover !== undefined)
formData.append("url_cover", params.url_cover);
if (params.is_public !== undefined)
formData.append("is_public", String(params.is_public));
if (params.remove_cover)
formData.append("remove_cover", String(params.remove_cover));
if (params.artwork) formData.append("artwork", params.artwork);
return api.put(`/collections/smart/${id}`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
params: {
...(params.remove_cover !== undefined && {
remove_cover: params.remove_cover,
}),
...(params.is_public !== undefined && { is_public: params.is_public }),
},
});
}
async function deleteSmartCollection(
id: number,
): Promise<{ data: { msg: string } }> {
@@ -188,17 +149,15 @@ async function deleteSmartCollection(
export default {
createCollection,
createSmartCollection,
getCollections,
getVirtualCollections,
getCollection,
getVirtualCollection,
updateCollection,
deleteCollection,
// Smart Collection functions
getSmartCollections,
getSmartCollection,
getSmartCollectionRoms,
createSmartCollection,
updateSmartCollection,
deleteSmartCollection,
};
+3
View File
@@ -62,6 +62,7 @@ export interface GetRomsParams {
platformId?: number | null;
collectionId?: number | null;
virtualCollectionId?: string | null;
smartCollectionId?: number | null;
searchTerm?: string | null;
limit?: number;
offset?: number;
@@ -90,6 +91,7 @@ async function getRoms({
platformId = null,
collectionId = null,
virtualCollectionId = null,
smartCollectionId = null,
searchTerm = null,
limit = 72,
offset = 0,
@@ -118,6 +120,7 @@ async function getRoms({
platform_id: platformId,
collection_id: collectionId,
virtual_collection_id: virtualCollectionId,
smart_collection_id: smartCollectionId,
search_term: searchTerm,
limit: limit,
offset: offset,
+4 -129
View File
@@ -1,9 +1,8 @@
import type {
CollectionSchema,
VirtualCollectionSchema,
SmartCollectionSchema,
} from "@/__generated__";
import type { SmartCollectionSchema } from "@/services/api/collection";
import collectionApi from "@/services/api/collection";
import { uniqBy } from "lodash";
import { defineStore } from "pinia";
import type { SimpleRom } from "./roms";
@@ -34,17 +33,6 @@ export default defineStore("collections", {
smartCollections.filter((p) =>
p.name.toLowerCase().includes(filterText.toLowerCase()),
),
// Combine all collection types for unified display
allCollectionsUnified: ({ allCollections, smartCollections }) => [
...allCollections,
...smartCollections,
],
filteredCollectionsUnified: (state) => {
const unified = [...state.allCollections, ...state.smartCollections];
return unified.filter((p: Collection | SmartCollection) =>
p.name.toLowerCase().includes(state.filterText.toLowerCase()),
);
},
},
actions: {
_reorder() {
@@ -61,6 +49,9 @@ export default defineStore("collections", {
setVirtual(collections: VirtualCollection[]) {
this.virtualCollections = collections;
},
setSmart(collections: SmartCollection[]) {
this.smartCollections = collections;
},
add(collection: Collection) {
this.allCollections.push(collection);
this._reorder();
@@ -87,122 +78,6 @@ export default defineStore("collections", {
isFav(rom: SimpleRom) {
return this.favCollection?.rom_ids?.includes(rom.id);
},
// Smart collections actions
setSmartCollections(smartCollections: SmartCollection[]) {
this.smartCollections = smartCollections;
},
setCurrentSmartCollection(smartCollection: SmartCollection | null) {
this.currentSmartCollection = smartCollection;
},
addSmartCollection(smartCollection: SmartCollection) {
this.smartCollections.push(smartCollection);
this.smartCollections.sort((a, b) => a.name.localeCompare(b.name));
},
updateSmartCollection(updatedSmartCollection: SmartCollection) {
const index = this.smartCollections.findIndex(
(sc) => sc.id === updatedSmartCollection.id,
);
if (index !== -1) {
this.smartCollections[index] = updatedSmartCollection;
this.smartCollections.sort((a, b) => a.name.localeCompare(b.name));
}
},
removeSmartCollection(smartCollectionId: number) {
const index = this.smartCollections.findIndex(
(sc) => sc.id === smartCollectionId,
);
if (index !== -1) {
this.smartCollections.splice(index, 1);
}
},
getSmartCollection(collectionId: number) {
return this.smartCollections.find((p) => p.id === collectionId);
},
// API actions for smart collections
async fetchSmartCollections() {
return collectionApi
.getSmartCollections()
.then(({ data }) => {
this.setSmartCollections(data);
return data;
})
.catch((error) => {
console.error("Failed to fetch smart collections:", error);
throw error;
});
},
async fetchSmartCollectionById(id: number) {
return collectionApi
.getSmartCollection(id)
.then(({ data }) => {
this.setCurrentSmartCollection(data);
return data;
})
.catch((error) => {
console.error(`Failed to fetch smart collection ${id}:`, error);
throw error;
});
},
async createSmartCollection(params: {
name: string;
description?: string;
filter_criteria: Record<string, any>;
url_cover?: string;
is_public?: boolean;
artwork?: File;
}) {
return collectionApi
.createSmartCollection(params)
.then(({ data }) => {
this.addSmartCollection(data);
return data;
})
.catch((error) => {
console.error("Failed to create smart collection:", error);
throw error;
});
},
async updateSmartCollectionById(
id: number,
params: {
name?: string;
description?: string;
filter_criteria?: Record<string, any>;
url_cover?: string;
is_public?: boolean;
remove_cover?: boolean;
artwork?: File;
},
) {
return collectionApi
.updateSmartCollection(id, params)
.then(({ data }) => {
this.updateSmartCollection(data);
if (this.currentSmartCollection?.id === id) {
this.setCurrentSmartCollection(data);
}
return data;
})
.catch((error) => {
console.error(`Failed to update smart collection ${id}:`, error);
throw error;
});
},
async deleteSmartCollectionById(id: number) {
return collectionApi
.deleteSmartCollection(id)
.then(({ data }) => {
this.removeSmartCollection(id);
if (this.currentSmartCollection?.id === id) {
this.setCurrentSmartCollection(null);
}
return data;
})
.catch((error) => {
console.error(`Failed to delete smart collection ${id}:`, error);
throw error;
});
},
reset() {
this.allCollections = [];
this.virtualCollections = [];
+41 -7
View File
@@ -1,7 +1,11 @@
import type { SearchRomSchema } from "@/__generated__";
import type { DetailedRomSchema, SimpleRomSchema } from "@/__generated__/";
import romApi from "@/services/api/rom";
import { type Collection, type VirtualCollection } from "@/stores/collections";
import {
type Collection,
type VirtualCollection,
type SmartCollection,
} from "@/stores/collections";
import storeGalleryFilter from "@/stores/galleryFilter";
import { type Platform } from "@/stores/platforms";
import type { ExtractPiniaStoreType } from "@/types";
@@ -17,6 +21,7 @@ const defaultRomsState = {
currentPlatform: null as Platform | null,
currentCollection: null as Collection | null,
currentVirtualCollection: null as VirtualCollection | null,
currentSmartCollection: null as SmartCollection | null,
currentRom: null as DetailedRom | null,
allRoms: [] as SimpleRom[],
selectedIDs: new Set<number>(),
@@ -40,6 +45,7 @@ const _romsCacheByID = new Map<number, SimpleRom>();
const _romsCacheByPlatform = new Map<number, number[]>();
const _romsCacheByCollection = new Map<number, number[]>();
const _romsCacheByVirtualCollection = new Map<string, number[]>();
const _romsCacheBySmartCollection = new Map<number, number[]>();
export default defineStore("roms", {
state: () => ({ ...defaultRomsState }),
@@ -98,6 +104,17 @@ export default defineStore("roms", {
}
}
},
setCurrentSmartCollection(collection: SmartCollection | null) {
this.currentSmartCollection = collection;
if (collection) {
const romIDs = _romsCacheBySmartCollection.get(collection.id);
if (romIDs) {
this.allRoms = romIDs
.filter((id) => _romsCacheByID.has(id))
.map((id) => _romsCacheByID.get(id)!) as SimpleRom[];
}
}
},
fetchRoms(galleryFilter: GalleryFilterStore, concat = true) {
if (this.fetchingRoms) return Promise.resolve();
this.fetchingRoms = true;
@@ -112,6 +129,7 @@ export default defineStore("roms", {
null,
collectionId: this.currentCollection?.id ?? null,
virtualCollectionId: this.currentVirtualCollection?.id ?? null,
smartCollectionId: this.currentSmartCollection?.id ?? null,
limit: this.fetchLimit,
offset: this.fetchOffset,
orderBy: this.orderBy,
@@ -122,7 +140,7 @@ export default defineStore("roms", {
if (!concat || this.fetchOffset === 0) {
this.allRoms = items;
// Cache the first batch of roms for each platform
// Cache the first batch of roms for each context
if (this.currentPlatform) {
_romsCacheByPlatform.set(
this.currentPlatform.id,
@@ -141,6 +159,12 @@ export default defineStore("roms", {
items.map((rom) => rom.id),
);
items.forEach((rom) => _romsCacheByID.set(rom.id, rom));
} else if (this.currentSmartCollection) {
_romsCacheBySmartCollection.set(
this.currentSmartCollection.id,
items.map((rom) => rom.id),
);
items.forEach((rom) => _romsCacheByID.set(rom.id, rom));
}
} else {
this.allRoms = this.allRoms.concat(items);
@@ -196,11 +220,21 @@ export default defineStore("roms", {
});
},
reset() {
Object.assign(this, {
...defaultRomsState,
recentRoms: this.recentRoms,
continuePlayingRoms: this.continuePlayingRoms,
});
this.currentPlatform = null;
this.currentCollection = null;
this.currentVirtualCollection = null;
this.currentSmartCollection = null;
this.currentRom = null;
this.allRoms = [];
this.selectedIDs = new Set<number>();
this.lastSelectedIndex = -1;
this.selectingRoms = false;
this.fetchingRoms = false;
this.initialSearch = false;
this.fetchOffset = 0;
this.fetchTotalRoms = 0;
this.characterIndex = {};
this.selectedCharacter = null;
},
resetPagination() {
this.fetchLimit = 72;
+56 -3
View File
@@ -26,7 +26,8 @@ const galleryViewStore = storeGalleryView();
const galleryFilterStore = storeGalleryFilter();
const { scrolledToTop, currentView } = storeToRefs(galleryViewStore);
const collectionsStore = storeCollections();
const { allCollections, virtualCollections } = storeToRefs(collectionsStore);
const { allCollections, virtualCollections, smartCollections } =
storeToRefs(collectionsStore);
const romsStore = storeRoms();
const {
allRoms,
@@ -35,6 +36,7 @@ const {
currentPlatform,
currentCollection,
currentVirtualCollection,
currentSmartCollection,
fetchingRoms,
fetchTotalRoms,
} = storeToRefs(romsStore);
@@ -190,9 +192,9 @@ onMounted(async () => {
(collection) => collection.id === Number(routeCollectionId),
);
// Check if the current platform is different or no ROMs have been loaded
// Check if the current collection is different or no ROMs have been loaded
if (
(currentVirtualCollection.value?.id !== routeCollectionId ||
(currentCollection.value?.id !== Number(routeCollectionId) ||
allRoms.value.length === 0) &&
collection
) {
@@ -236,6 +238,34 @@ onMounted(async () => {
},
{ immediate: true }, // Ensure watcher is triggered immediately
);
watch(
() => smartCollections.value,
async (collections) => {
if (
collections.length > 0 &&
collections.some(
(collection) => collection.id === Number(routeCollectionId),
)
) {
const collection = collections.find(
(collection) => collection.id === Number(routeCollectionId),
);
if (
(currentSmartCollection.value?.id !== Number(routeCollectionId) ||
allRoms.value.length === 0) &&
collection
) {
if (currentSmartCollection.value) resetGallery();
romsStore.setCurrentSmartCollection(collection);
document.title = `${collection.name}`;
await fetchRoms();
}
}
},
{ immediate: true }, // Ensure watcher is triggered immediately
);
});
onBeforeRouteUpdate(async (to, from) => {
@@ -292,6 +322,29 @@ onBeforeRouteUpdate(async (to, from) => {
},
{ immediate: true }, // Ensure watcher is triggered immediately
);
watch(
() => smartCollections.value,
async (collections) => {
if (collections.length > 0) {
const collection = collections.find(
(collection) => collection.id === Number(routeCollectionId),
);
if (
(currentSmartCollection.value?.id !== Number(routeCollectionId) ||
allRoms.value.length === 0) &&
collection
) {
if (currentSmartCollection.value) resetGallery();
romsStore.setCurrentSmartCollection(collection);
document.title = `${collection.name}`;
await fetchRoms();
}
}
},
{ immediate: true }, // Ensure watcher is triggered immediately
);
});
onBeforeUnmount(() => {