Refactor code structure for improved readability and maintainability
This commit is contained in:
42
frontend/src/App.css
Normal file
42
frontend/src/App.css
Normal file
@@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
@@ -1,13 +1,38 @@
|
||||
import React from 'react';
|
||||
import Navbar from './components/layout/Navbar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
export default function App(): JSX.Element {
|
||||
function App() {
|
||||
return (
|
||||
<div>
|
||||
<Navbar />
|
||||
<main>
|
||||
<h1>Quasar</h1>
|
||||
</main>
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="container mx-auto p-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Quasar - Biblioteca de Videojuegos</CardTitle>
|
||||
<CardDescription>
|
||||
Aplicación para gestionar tu colección personal de videojuegos
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-4">
|
||||
<Button>Botón Primario</Button>
|
||||
<Button variant="secondary">Botón Secundario</Button>
|
||||
<Button variant="outline">Botón Outline</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Input placeholder="Buscar juegos..." />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Badge variant="default">Etiqueta</Badge>
|
||||
<Badge variant="secondary">Secundaria</Badge>
|
||||
<Badge variant="outline">Outline</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
165
frontend/src/api/client.ts
Normal file
165
frontend/src/api/client.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
// Función para unir clases de Tailwind
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
// Configuración base de la API
|
||||
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3000';
|
||||
|
||||
// Interceptor para manejar errores comunes
|
||||
async function handleApiError(response: Response) {
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
|
||||
// Manejar errores de autenticación
|
||||
if (response.status === 401) {
|
||||
throw new Error('No autorizado. Por favor inicia sesión.');
|
||||
}
|
||||
|
||||
// Manejar errores de validación
|
||||
if (response.status === 422) {
|
||||
const fieldErrors = errorData.errors || {};
|
||||
const errorMessage = Object.entries(fieldErrors)
|
||||
.map(([field, errors]) => `${field}: ${Array.isArray(errors) ? errors.join(', ') : errors}`)
|
||||
.join('; ');
|
||||
throw new Error(errorMessage || 'Error de validación');
|
||||
}
|
||||
|
||||
// Manejar errores de servidor
|
||||
if (response.status >= 500) {
|
||||
throw new Error('Error del servidor. Por favor intenta de nuevo más tarde.');
|
||||
}
|
||||
|
||||
// Manejar otros errores
|
||||
throw new Error(errorData.message || 'Error en la solicitud');
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Función genérica para peticiones GET
|
||||
export async function apiGet<T>(endpoint: string, params?: Record<string, any>): Promise<T> {
|
||||
const url = new URL(`${API_BASE_URL}${endpoint}`);
|
||||
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
url.searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
await handleApiError(response);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Función genérica para peticiones POST
|
||||
export async function apiPost<T>(endpoint: string, data: any): Promise<T> {
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
await handleApiError(response);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Función genérica para peticiones PUT
|
||||
export async function apiPut<T>(endpoint: string, data: any): Promise<T> {
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
await handleApiError(response);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Función genérica para peticiones DELETE
|
||||
export async function apiDelete<T>(endpoint: string): Promise<T> {
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
await handleApiError(response);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Función para subir archivos
|
||||
export async function apiUpload<T>(
|
||||
endpoint: string,
|
||||
file: File,
|
||||
additionalData?: Record<string, any>
|
||||
): Promise<T> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
if (additionalData) {
|
||||
Object.entries(additionalData).forEach(([key, value]) => {
|
||||
formData.append(key, String(value));
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
await handleApiError(response);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Función para peticiones con paginación
|
||||
export async function apiGetPaginated<T>(
|
||||
endpoint: string,
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
filters?: Record<string, any>
|
||||
): Promise<{
|
||||
data: T[];
|
||||
pagination: {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}> {
|
||||
const params = {
|
||||
page,
|
||||
limit,
|
||||
...filters,
|
||||
};
|
||||
|
||||
return apiGet(endpoint, params);
|
||||
}
|
||||
|
||||
// Función para buscar
|
||||
export async function apiSearch<T>(
|
||||
endpoint: string,
|
||||
query: string,
|
||||
filters?: Record<string, any>
|
||||
): Promise<T[]> {
|
||||
return apiGet(endpoint, {
|
||||
search: query,
|
||||
...filters,
|
||||
});
|
||||
}
|
||||
80
frontend/src/api/games.ts
Normal file
80
frontend/src/api/games.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { apiGet, apiPost, apiPut, apiDelete, apiGetPaginated, apiSearch } from './client';
|
||||
import type { Game, GameFilters, GameFormData, PaginatedResponse } from '@/types';
|
||||
|
||||
// Obtener todos los juegos con paginación
|
||||
export const getGames = async (page: number = 1, limit: number = 10, filters?: GameFilters) => {
|
||||
return apiGetPaginated<Game>('/api/games', page, limit, filters);
|
||||
};
|
||||
|
||||
// Obtener un juego por ID
|
||||
export const getGameById = async (id: number) => {
|
||||
return apiGet<Game>(`/api/games/${id}`);
|
||||
};
|
||||
|
||||
// Crear un nuevo juego
|
||||
export const createGame = async (data: GameFormData) => {
|
||||
return apiPost<Game>('/api/games', data);
|
||||
};
|
||||
|
||||
// Actualizar un juego existente
|
||||
export const updateGame = async (id: number, data: GameFormData) => {
|
||||
return apiPut<Game>(`/api/games/${id}`, data);
|
||||
};
|
||||
|
||||
// Eliminar un juego
|
||||
export const deleteGame = async (id: number) => {
|
||||
return apiDelete(`/api/games/${id}`);
|
||||
};
|
||||
|
||||
// Buscar juegos
|
||||
export const searchGames = async (query: string, filters?: GameFilters) => {
|
||||
return apiSearch<Game>('/api/games', query, filters);
|
||||
};
|
||||
|
||||
// Obtener juegos por plataforma
|
||||
export const getGamesByPlatform = async (
|
||||
platformId: number,
|
||||
page: number = 1,
|
||||
limit: number = 10
|
||||
) => {
|
||||
return apiGetPaginated<Game>(`/api/games/platform/${platformId}`, page, limit);
|
||||
};
|
||||
|
||||
// Obtener juegos por etiqueta
|
||||
export const getGamesByTag = async (tagId: number, page: number = 1, limit: number = 10) => {
|
||||
return apiGetPaginated<Game>(`/api/games/tag/${tagId}`, page, limit);
|
||||
};
|
||||
|
||||
// Obtener juegos sin ROM
|
||||
export const getGamesWithoutRom = async (page: number = 1, limit: number = 10) => {
|
||||
return apiGetPaginated<Game>('/api/games/without-rom', page, limit);
|
||||
};
|
||||
|
||||
// Obtener juegos metadata pendiente
|
||||
export const getGamesWithPendingMetadata = async (page: number = 1, limit: number = 10) => {
|
||||
return apiGetPaginated<Game>('/api/games/pending-metadata', page, limit);
|
||||
};
|
||||
|
||||
// Actualizar metadata de un juego
|
||||
export const updateGameMetadata = async (id: number, metadata: any) => {
|
||||
return apiPut<Game>(`/api/games/${id}/metadata`, metadata);
|
||||
};
|
||||
|
||||
// Enriquecer metadata de un juego
|
||||
export const enrichGameMetadata = async (id: number, source: 'igdb' | 'rawg' | 'thegamesdb') => {
|
||||
return apiPost<Game>(`/api/games/${id}/enrich`, { source });
|
||||
};
|
||||
|
||||
// Obtener estadísticas de juegos
|
||||
export const getGameStats = async () => {
|
||||
return apiGet<{
|
||||
totalGames: number;
|
||||
gamesWithRom: number;
|
||||
gamesWithoutRom: number;
|
||||
gamesWithMetadata: number;
|
||||
gamesWithoutMetadata: number;
|
||||
totalPlatforms: number;
|
||||
totalTags: number;
|
||||
averageRating: number;
|
||||
}>('/api/games/stats');
|
||||
};
|
||||
76
frontend/src/api/import.ts
Normal file
76
frontend/src/api/import.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { apiGet, apiPost, apiPut, apiDelete, apiUpload } from './client';
|
||||
import type { ImportRomFormData } from '@/types';
|
||||
|
||||
// Iniciar escaneo de directorio
|
||||
export const startDirectoryScan = async (directoryPath: string) => {
|
||||
return apiPost('/api/import/scan', { directoryPath });
|
||||
};
|
||||
|
||||
// Obtener estado del escaneo
|
||||
export const getScanStatus = async (scanId: string) => {
|
||||
return apiGet(`/api/import/scan/${scanId}/status`);
|
||||
};
|
||||
|
||||
// Obtener lista de ROMs detectadas
|
||||
export const getDetectedRoms = async (scanId: string) => {
|
||||
return apiGet(`/api/import/scan/${scanId}/roms`);
|
||||
};
|
||||
|
||||
// Procesar ROMs detectadas
|
||||
export const processDetectedRoms = async (scanId: string, romIds: number[]) => {
|
||||
return apiPost(`/api/import/scan/${scanId}/process`, { romIds });
|
||||
};
|
||||
|
||||
// Importar ROM manualmente
|
||||
export const importRom = async (data: ImportRomFormData & { file: File }) => {
|
||||
const { file, ...rest } = data;
|
||||
return apiUpload('/api/import/rom', file, rest);
|
||||
};
|
||||
|
||||
// Obtener historial de importaciones
|
||||
export const getImportHistory = async (page: number = 1, limit: number = 10) => {
|
||||
return apiGet(`/api/import/history?page=${page}&limit=${limit}`);
|
||||
};
|
||||
|
||||
// Obtener estadísticas de importación
|
||||
export const getImportStats = async () => {
|
||||
return apiGet<{
|
||||
totalImports: number;
|
||||
successfulImports: number;
|
||||
failedImports: number;
|
||||
totalRomsScanned: number;
|
||||
totalRomsImported: number;
|
||||
averageProcessingTime: number;
|
||||
lastImportDate?: string;
|
||||
}>('/api/import/stats');
|
||||
};
|
||||
|
||||
// Cancelar escaneo en progreso
|
||||
export const cancelScan = async (scanId: string) => {
|
||||
return apiDelete(`/api/import/scan/${scanId}`);
|
||||
};
|
||||
|
||||
// Reintentar importación fallida
|
||||
export const retryImport = async (importId: number) => {
|
||||
return apiPost(`/api/import/retry/${importId}`);
|
||||
};
|
||||
|
||||
// Eliminar registro de importación
|
||||
export const deleteImportRecord = async (importId: number) => {
|
||||
return apiDelete(`/api/import/history/${importId}`);
|
||||
};
|
||||
|
||||
// Obtener información de archivo ROM
|
||||
export const getRomInfo = async (romPath: string) => {
|
||||
return apiGet(`/api/import/rom-info?path=${encodeURIComponent(romPath)}`);
|
||||
};
|
||||
|
||||
// Verificar integridad de ROM
|
||||
export const verifyRomIntegrity = async (romPath: string, romType: string) => {
|
||||
return apiPost('/api/import/verify-rom', { romPath, romType });
|
||||
};
|
||||
|
||||
// Obtener directorios disponibles para escaneo
|
||||
export const getAvailableDirectories = async () => {
|
||||
return apiGet<string[]>('/api/import/directories');
|
||||
};
|
||||
52
frontend/src/api/platforms.ts
Normal file
52
frontend/src/api/platforms.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { apiGet, apiPost, apiPut, apiDelete, apiGetPaginated, apiSearch } from './client';
|
||||
import type { Platform, PlatformFilters, PlatformFormData } from '@/types';
|
||||
|
||||
// Obtener todas las plataformas con paginación
|
||||
export const getPlatforms = async (
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
filters?: PlatformFilters
|
||||
) => {
|
||||
return apiGetPaginated<Platform>('/api/platforms', page, limit, filters);
|
||||
};
|
||||
|
||||
// Obtener todas las plataformas (sin paginación para selectores)
|
||||
export const getAllPlatforms = async () => {
|
||||
return apiGet<Platform[]>('/api/platforms/all');
|
||||
};
|
||||
|
||||
// Obtener una plataforma por ID
|
||||
export const getPlatformById = async (id: number) => {
|
||||
return apiGet<Platform>(`/api/platforms/${id}`);
|
||||
};
|
||||
|
||||
// Crear una nueva plataforma
|
||||
export const createPlatform = async (data: PlatformFormData) => {
|
||||
return apiPost<Platform>('/api/platforms', data);
|
||||
};
|
||||
|
||||
// Actualizar una plataforma existente
|
||||
export const updatePlatform = async (id: number, data: PlatformFormData) => {
|
||||
return apiPut<Platform>(`/api/platforms/${id}`, data);
|
||||
};
|
||||
|
||||
// Eliminar una plataforma
|
||||
export const deletePlatform = async (id: number) => {
|
||||
return apiDelete(`/api/platforms/${id}`);
|
||||
};
|
||||
|
||||
// Buscar plataformas
|
||||
export const searchPlatforms = async (query: string, filters?: PlatformFilters) => {
|
||||
return apiSearch<Platform>('/api/platforms', query, filters);
|
||||
};
|
||||
|
||||
// Obtener estadísticas de plataformas
|
||||
export const getPlatformStats = async () => {
|
||||
return apiGet<{
|
||||
totalPlatforms: number;
|
||||
totalGames: number;
|
||||
averageGamesPerPlatform: number;
|
||||
mostPopularPlatform: string;
|
||||
leastPopularPlatform: string;
|
||||
}>('/api/platforms/stats');
|
||||
};
|
||||
107
frontend/src/api/settings.ts
Normal file
107
frontend/src/api/settings.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import { apiGet, apiPost, apiPut } from './client';
|
||||
import type { SettingsFormData } from '@/types';
|
||||
|
||||
// Obtener configuración actual
|
||||
export const getSettings = async () => {
|
||||
return apiGet('/api/settings');
|
||||
};
|
||||
|
||||
// Actualizar configuración
|
||||
export const updateSettings = async (data: SettingsFormData) => {
|
||||
return apiPut('/api/settings', data);
|
||||
};
|
||||
|
||||
// Probar conexión con IGDB
|
||||
export const testIgdbConnection = async (apiKey: string) => {
|
||||
return apiPost('/api/settings/test-igdb', { apiKey });
|
||||
};
|
||||
|
||||
// Probar conexión con RAWG
|
||||
export const testRawgConnection = async (apiKey: string) => {
|
||||
return apiPost('/api/settings/test-rawg', { apiKey });
|
||||
};
|
||||
|
||||
// Probar conexión con TheGamesDB
|
||||
export const testThegamesdbConnection = async (apiKey: string) => {
|
||||
return apiPost('/api/settings/test-thegamesdb', { apiKey });
|
||||
};
|
||||
|
||||
// Obtener estado de servicios externos
|
||||
export const getExternalServicesStatus = async () => {
|
||||
return apiGet<{
|
||||
igdb: { connected: boolean; lastChecked?: string };
|
||||
rawg: { connected: boolean; lastChecked?: string };
|
||||
thegamesdb: { connected: boolean; lastChecked?: string };
|
||||
}>('/api/settings/services-status');
|
||||
};
|
||||
|
||||
// Obtener configuración de importación automática
|
||||
export const getAutoImportConfig = async () => {
|
||||
return apiGet('/api/settings/auto-import');
|
||||
};
|
||||
|
||||
// Actualizar configuración de importación automática
|
||||
export const updateAutoImportConfig = async (enabled: boolean, directory?: string) => {
|
||||
return apiPut('/api/settings/auto-import', { enabled, directory });
|
||||
};
|
||||
|
||||
// Obtener configuración de exportación
|
||||
export const getExportConfig = async () => {
|
||||
return apiGet('/api/settings/export');
|
||||
};
|
||||
|
||||
// Actualizar configuración de exportación
|
||||
export const updateExportConfig = async (format: 'csv' | 'json', fields: string[]) => {
|
||||
return apiPut('/api/settings/export', { format, fields });
|
||||
};
|
||||
|
||||
// Exportar datos
|
||||
export const exportData = async (format: 'csv' | 'json', filters?: Record<string, any>) => {
|
||||
const params = new URLSearchParams();
|
||||
params.append('format', format);
|
||||
|
||||
if (filters) {
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null) {
|
||||
params.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/settings/export?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Error al exportar datos');
|
||||
}
|
||||
|
||||
return response.blob();
|
||||
};
|
||||
|
||||
// Obtener estadísticas del sistema
|
||||
export const getSystemStats = async () => {
|
||||
return apiGet<{
|
||||
totalGames: number;
|
||||
totalPlatforms: number;
|
||||
totalTags: number;
|
||||
totalRoms: number;
|
||||
totalSize: number;
|
||||
averageRating: number;
|
||||
recentActivity: Array<{
|
||||
type: string;
|
||||
message: string;
|
||||
timestamp: string;
|
||||
}>;
|
||||
}>('/api/settings/system-stats');
|
||||
};
|
||||
|
||||
// Limpiar caché
|
||||
export const clearCache = async () => {
|
||||
return apiPost('/api/settings/clear-cache');
|
||||
};
|
||||
|
||||
// Obtener versión del sistema
|
||||
export const getSystemVersion = async () => {
|
||||
return apiGet('/api/settings/version');
|
||||
};
|
||||
68
frontend/src/api/tags.ts
Normal file
68
frontend/src/api/tags.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { apiGet, apiPost, apiPut, apiDelete, apiGetPaginated, apiSearch } from './client';
|
||||
import type { Tag, TagFilters, TagFormData } from '@/types';
|
||||
|
||||
// Obtener todas las etiquetas con paginación
|
||||
export const getTags = async (page: number = 1, limit: number = 10, filters?: TagFilters) => {
|
||||
return apiGetPaginated<Tag>('/api/tags', page, limit, filters);
|
||||
};
|
||||
|
||||
// Obtener todas las etiquetas (sin paginación para selectores)
|
||||
export const getAllTags = async () => {
|
||||
return apiGet<Tag[]>('/api/tags/all');
|
||||
};
|
||||
|
||||
// Obtener una etiqueta por ID
|
||||
export const getTagById = async (id: number) => {
|
||||
return apiGet<Tag>(`/api/tags/${id}`);
|
||||
};
|
||||
|
||||
// Crear una nueva etiqueta
|
||||
export const createTag = async (data: TagFormData) => {
|
||||
return apiPost<Tag>('/api/tags', data);
|
||||
};
|
||||
|
||||
// Actualizar una etiqueta existente
|
||||
export const updateTag = async (id: number, data: TagFormData) => {
|
||||
return apiPut<Tag>(`/api/tags/${id}`, data);
|
||||
};
|
||||
|
||||
// Eliminar una etiqueta
|
||||
export const deleteTag = async (id: number) => {
|
||||
return apiDelete(`/api/tags/${id}`);
|
||||
};
|
||||
|
||||
// Buscar etiquetas
|
||||
export const searchTags = async (query: string, filters?: TagFilters) => {
|
||||
return apiSearch<Tag>('/api/tags', query, filters);
|
||||
};
|
||||
|
||||
// Obtener etiquetas más usadas
|
||||
export const getPopularTags = async (limit: number = 10) => {
|
||||
return apiGet<Tag[]>(`/api/tags/popular?limit=${limit}`);
|
||||
};
|
||||
|
||||
// Obtener etiquetas por juego
|
||||
export const getTagsByGame = async (gameId: number) => {
|
||||
return apiGet<Tag[]>(`/api/tags/game/${gameId}`);
|
||||
};
|
||||
|
||||
// Asignar etiquetas a un juego
|
||||
export const assignTagsToGame = async (gameId: number, tagIds: number[]) => {
|
||||
return apiPost(`/api/games/${gameId}/tags`, { tagIds });
|
||||
};
|
||||
|
||||
// Eliminar etiquetas de un juego
|
||||
export const removeTagsFromGame = async (gameId: number, tagIds: number[]) => {
|
||||
return apiPost(`/api/games/${gameId}/tags/remove`, { tagIds });
|
||||
};
|
||||
|
||||
// Obtener estadísticas de etiquetas
|
||||
export const getTagStats = async () => {
|
||||
return apiGet<{
|
||||
totalTags: number;
|
||||
totalTaggedGames: number;
|
||||
averageTagsPerGame: number;
|
||||
mostUsedTag: string;
|
||||
leastUsedTag: string;
|
||||
}>('/api/tags/stats');
|
||||
};
|
||||
1
frontend/src/assets/react.svg
Normal file
1
frontend/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -1,38 +0,0 @@
|
||||
import { Game } from '../../types/game';
|
||||
|
||||
interface GameCardProps {
|
||||
game: Game;
|
||||
onEdit?: (game: Game) => void;
|
||||
onDelete?: (id: string) => void;
|
||||
}
|
||||
|
||||
export default function GameCard({ game, onEdit, onDelete }: GameCardProps): JSX.Element {
|
||||
return (
|
||||
<div className="rounded border border-gray-300 p-4 shadow-sm hover:shadow-md">
|
||||
<h3 className="mb-2 text-lg font-semibold">{game.title}</h3>
|
||||
<p className="mb-2 text-sm text-gray-600">{game.slug}</p>
|
||||
{game.description && <p className="mb-3 text-sm text-gray-700">{game.description}</p>}
|
||||
<p className="mb-4 text-xs text-gray-500">
|
||||
Added: {new Date(game.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
{onEdit && (
|
||||
<button
|
||||
onClick={() => onEdit(game)}
|
||||
className="rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
)}
|
||||
{onDelete && (
|
||||
<button
|
||||
onClick={() => onDelete(game.id)}
|
||||
className="rounded bg-red-600 px-3 py-1 text-sm text-white hover:bg-red-700"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { Game, CreateGameInput } from '../../types/game';
|
||||
|
||||
const gameFormSchema = z.object({
|
||||
title: z.string().min(1, 'Title is required'),
|
||||
platformId: z.string().min(1, 'Platform is required'),
|
||||
description: z.string().optional().nullable(),
|
||||
priceCents: z.number().optional(),
|
||||
currency: z.string().optional().default('USD'),
|
||||
store: z.string().optional(),
|
||||
date: z.string().optional(),
|
||||
condition: z.enum(['Loose', 'CIB', 'New']).optional(),
|
||||
notes: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
type GameFormData = z.infer<typeof gameFormSchema>;
|
||||
|
||||
interface GameFormProps {
|
||||
initialData?: Game;
|
||||
onSubmit: (data: CreateGameInput | Game) => void | Promise<void>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export default function GameForm({
|
||||
initialData,
|
||||
onSubmit,
|
||||
isLoading = false,
|
||||
}: GameFormProps): JSX.Element {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<GameFormData>({
|
||||
resolver: zodResolver(gameFormSchema),
|
||||
defaultValues: initialData
|
||||
? {
|
||||
title: initialData.title,
|
||||
description: initialData.description,
|
||||
priceCents: undefined,
|
||||
currency: 'USD',
|
||||
store: undefined,
|
||||
date: undefined,
|
||||
condition: undefined,
|
||||
notes: undefined,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const onFormSubmit = (data: GameFormData) => {
|
||||
onSubmit(data as CreateGameInput);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="title" className="block text-sm font-medium">
|
||||
Title *
|
||||
</label>
|
||||
<input
|
||||
{...register('title')}
|
||||
id="title"
|
||||
type="text"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
{errors.title && <p className="text-red-600 text-sm">{errors.title.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="platformId" className="block text-sm font-medium">
|
||||
Platform *
|
||||
</label>
|
||||
<input
|
||||
{...register('platformId')}
|
||||
id="platformId"
|
||||
type="text"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
{errors.platformId && <p className="text-red-600 text-sm">{errors.platformId.message}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="condition" className="block text-sm font-medium">
|
||||
Condition
|
||||
</label>
|
||||
<select
|
||||
{...register('condition')}
|
||||
id="condition"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
>
|
||||
<option value="">Select condition</option>
|
||||
<option value="Loose">Loose</option>
|
||||
<option value="CIB">CIB</option>
|
||||
<option value="New">New</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="description" className="block text-sm font-medium">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
{...register('description')}
|
||||
id="description"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="priceCents" className="block text-sm font-medium">
|
||||
Price (cents)
|
||||
</label>
|
||||
<input
|
||||
{...register('priceCents', { valueAsNumber: true })}
|
||||
id="priceCents"
|
||||
type="number"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="currency" className="block text-sm font-medium">
|
||||
Currency
|
||||
</label>
|
||||
<input
|
||||
{...register('currency')}
|
||||
id="currency"
|
||||
type="text"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
defaultValue="USD"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="store" className="block text-sm font-medium">
|
||||
Store
|
||||
</label>
|
||||
<input
|
||||
{...register('store')}
|
||||
id="store"
|
||||
type="text"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="date" className="block text-sm font-medium">
|
||||
Purchase Date
|
||||
</label>
|
||||
<input
|
||||
{...register('date')}
|
||||
id="date"
|
||||
type="date"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="notes" className="block text-sm font-medium">
|
||||
Notes
|
||||
</label>
|
||||
<textarea
|
||||
{...register('notes')}
|
||||
id="notes"
|
||||
className="mt-1 block w-full rounded border border-gray-300 px-3 py-2"
|
||||
disabled={isLoading}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full rounded bg-blue-600 px-4 py-2 text-white disabled:bg-gray-400"
|
||||
>
|
||||
{isLoading ? 'Saving...' : 'Save Game'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
88
frontend/src/components/layout/Header.tsx
Normal file
88
frontend/src/components/layout/Header.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { Link, useLocation } from '@tanstack/react-router';
|
||||
import { Menu, Search, Settings, Gamepad2, Home, FileText } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface HeaderProps {
|
||||
onMenuToggle?: () => void;
|
||||
}
|
||||
|
||||
const navigation = [
|
||||
{ name: 'Dashboard', href: '/', icon: Home },
|
||||
{ name: 'Juegos', href: '/games', icon: Gamepad2 },
|
||||
{ name: 'Importar ROMs', href: '/import', icon: FileText },
|
||||
{ name: 'Configuración', href: '/settings', icon: Settings },
|
||||
];
|
||||
|
||||
export function Header({ onMenuToggle }: HeaderProps) {
|
||||
const location = useLocation();
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="container flex h-14 items-center">
|
||||
{/* Botón de menú para móviles */}
|
||||
<Button variant="ghost" size="sm" className="mr-4 md:hidden" onClick={onMenuToggle}>
|
||||
<Menu className="h-5 w-5" />
|
||||
<span className="sr-only">Toggle menu</span>
|
||||
</Button>
|
||||
|
||||
{/* Logo y título */}
|
||||
<div className="mr-4 hidden md:flex">
|
||||
<Link to="/" className="mr-6 flex items-center space-x-2">
|
||||
<Gamepad2 className="h-6 w-6" />
|
||||
<span className="hidden font-bold sm:inline-block">Quasar</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Navegación principal */}
|
||||
<nav className="flex items-center space-x-6 text-sm font-medium">
|
||||
{navigation.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = location.pathname === item.href;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.name}
|
||||
to={item.href}
|
||||
className={cn(
|
||||
'transition-colors hover:text-foreground/80',
|
||||
isActive ? 'text-foreground' : 'text-foreground/60'
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center space-x-1">
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{item.name}</span>
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Barra de búsqueda */}
|
||||
<div className="flex flex-1 items-center justify-between space-x-2 md:justify-end">
|
||||
<div className="w-full flex-1 md:w-auto md:flex-none">
|
||||
{/* Placeholder para barra de búsqueda */}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="relative h-8 w-full justify-start rounded-[0.5rem] bg-background text-sm font-normal text-muted-foreground shadow-none sm:pr-12 md:w-40 lg:w-64"
|
||||
>
|
||||
<Search className="mr-2 h-4 w-4" />
|
||||
Buscar juegos...
|
||||
<kbd className="pointer-events-none absolute right-[0.3rem] top-[0.3rem] hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">
|
||||
⌘K
|
||||
</kbd>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Usuario y acciones */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button variant="ghost" size="sm">
|
||||
<Settings className="h-4 w-4" />
|
||||
<span className="sr-only">Configuración</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
38
frontend/src/components/layout/Layout.tsx
Normal file
38
frontend/src/components/layout/Layout.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useState } from 'react';
|
||||
import { Outlet } from '@tanstack/react-router';
|
||||
import { Header } from './Header';
|
||||
import { Sidebar } from './Sidebar';
|
||||
|
||||
interface LayoutProps {
|
||||
sidebarOpen?: boolean;
|
||||
onSidebarChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function Layout({ sidebarOpen = false, onSidebarChange }: LayoutProps) {
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(sidebarOpen);
|
||||
|
||||
const handleSidebarToggle = (open: boolean) => {
|
||||
setIsSidebarOpen(open);
|
||||
onSidebarChange?.(open);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background">
|
||||
{/* Sidebar */}
|
||||
<Sidebar isOpen={isSidebarOpen} onClose={() => handleSidebarToggle(false)} />
|
||||
|
||||
{/* Contenido principal */}
|
||||
<div className="md:pl-64">
|
||||
{/* Header */}
|
||||
<Header onMenuToggle={() => handleSidebarToggle(true)} />
|
||||
|
||||
{/* Main content */}
|
||||
<main className="container mx-auto p-6">
|
||||
<div className="space-y-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
export default function Navbar(): JSX.Element {
|
||||
return (
|
||||
<nav style={{ padding: 12 }}>
|
||||
<a href="/roms" style={{ marginRight: 12 }}>
|
||||
ROMs
|
||||
</a>
|
||||
<a href="/games">Games</a>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,119 @@
|
||||
import React from 'react';
|
||||
import { Link, useLocation } from '@tanstack/react-router';
|
||||
import { Home, Gamepad2, FileText, Settings, Database, Tag, Download, Upload } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
interface SidebarProps {
|
||||
isOpen?: boolean;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
const navigation = [
|
||||
{ name: 'Dashboard', href: '/', icon: Home, count: null },
|
||||
{ name: 'Juegos', href: '/games', icon: Gamepad2, count: null },
|
||||
{
|
||||
name: 'Plataformas',
|
||||
href: '/platforms',
|
||||
icon: Database,
|
||||
count: null,
|
||||
},
|
||||
{
|
||||
name: 'Etiquetas',
|
||||
href: '/tags',
|
||||
icon: Tag,
|
||||
count: null,
|
||||
},
|
||||
{ name: 'Importar ROMs', href: '/import', icon: Download, count: null },
|
||||
{ name: 'Exportar', href: '/export', icon: Upload, count: null },
|
||||
{ name: 'Configuración', href: '/settings', icon: Settings, count: null },
|
||||
];
|
||||
|
||||
export function Sidebar({ isOpen, onClose }: SidebarProps) {
|
||||
const location = useLocation();
|
||||
|
||||
export default function Sidebar(): JSX.Element {
|
||||
return (
|
||||
<aside style={{ padding: 12 }}>
|
||||
<div>Sidebar (placeholder)</div>
|
||||
</aside>
|
||||
<>
|
||||
{/* Overlay para móviles */}
|
||||
{isOpen && <div className="fixed inset-0 z-40 bg-black/50 md:hidden" onClick={onClose} />}
|
||||
|
||||
{/* Sidebar */}
|
||||
<div
|
||||
className={cn(
|
||||
'fixed left-0 top-0 z-50 h-full w-64 transform border-r bg-background transition-transform duration-300 ease-in-out md:relative md:translate-x-0',
|
||||
isOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
|
||||
)}
|
||||
>
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header del sidebar */}
|
||||
<div className="flex h-14 items-center border-b px-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Gamepad2 className="h-6 w-6" />
|
||||
<span className="font-bold">Quasar</span>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="ml-auto md:hidden" onClick={onClose}>
|
||||
✕
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Contenido del sidebar */}
|
||||
<ScrollArea className="flex-1">
|
||||
<nav className="p-4 space-y-1">
|
||||
{navigation.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = location.pathname === item.href;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.name}
|
||||
to={item.href}
|
||||
onClick={onClose}
|
||||
className={cn(
|
||||
'flex items-center justify-between rounded-lg px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground',
|
||||
isActive ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<Icon className="h-4 w-4" />
|
||||
<span>{item.name}</span>
|
||||
</div>
|
||||
{item.count !== null && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{item.count}
|
||||
</Badge>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Sección adicional con información */}
|
||||
<div className="mt-8 p-4 border-t">
|
||||
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3">
|
||||
Información
|
||||
</h3>
|
||||
<div className="space-y-2 text-xs text-muted-foreground">
|
||||
<div className="flex justify-between">
|
||||
<span>Versión</span>
|
||||
<span>1.0.0</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span>Última actualización</span>
|
||||
<span>2024-01-15</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Footer del sidebar */}
|
||||
<div className="flex h-14 items-center border-t px-4">
|
||||
<div className="flex items-center space-x-2 text-xs text-muted-foreground">
|
||||
<span>© 2024 Quasar</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useEnrichMetadata } from '../../hooks/useRoms';
|
||||
import { EnrichedGame } from '../../types/rom';
|
||||
|
||||
interface MetadataSearchDialogProps {
|
||||
romId: string;
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSelect: (game: EnrichedGame) => void;
|
||||
}
|
||||
|
||||
const sourceLabels: Record<string, string> = {
|
||||
igdb: 'IGDB',
|
||||
rawg: 'RAWG',
|
||||
thegamesdb: 'TGDB',
|
||||
};
|
||||
|
||||
export default function MetadataSearchDialog({
|
||||
romId,
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
onSelect,
|
||||
}: MetadataSearchDialogProps): JSX.Element | null {
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState<EnrichedGame[]>([]);
|
||||
const [searched, setSearched] = useState(false);
|
||||
const enrichMutation = useEnrichMetadata();
|
||||
|
||||
const handleSearch = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSearched(false);
|
||||
|
||||
if (!query.trim()) return;
|
||||
|
||||
try {
|
||||
const searchResults = await enrichMutation.mutateAsync(query);
|
||||
setResults(searchResults);
|
||||
setSearched(true);
|
||||
} catch (err) {
|
||||
console.error('Search failed:', err);
|
||||
setResults([]);
|
||||
setSearched(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelect = (game: EnrichedGame) => {
|
||||
onSelect(game);
|
||||
onOpenChange(false);
|
||||
setQuery('');
|
||||
setResults([]);
|
||||
setSearched(false);
|
||||
};
|
||||
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div className="bg-white rounded-lg shadow-lg p-6 max-w-2xl w-full max-h-[90vh] overflow-auto">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold">Search Metadata</h2>
|
||||
<button
|
||||
onClick={() => onOpenChange(false)}
|
||||
aria-label="close"
|
||||
className="text-gray-500 hover:text-gray-700 text-xl"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSearch} className="mb-6">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search game title"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
disabled={enrichMutation.isPending}
|
||||
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={enrichMutation.isPending}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:bg-gray-400 font-medium"
|
||||
>
|
||||
{enrichMutation.isPending ? 'Searching...' : 'Search'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{searched && results.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500">No results found for "{query}"</div>
|
||||
)}
|
||||
|
||||
{results.length > 0 && (
|
||||
<div className="space-y-4">
|
||||
{results.map((game, index) => (
|
||||
<div
|
||||
key={`${game.source}-${game.externalIds[game.source as keyof typeof game.externalIds]}`}
|
||||
className="border border-gray-200 rounded-lg p-4 hover:shadow-md transition"
|
||||
>
|
||||
<div className="flex gap-4">
|
||||
{game.coverUrl && (
|
||||
<img
|
||||
src={game.coverUrl}
|
||||
alt={game.title}
|
||||
className="w-16 h-24 object-cover rounded"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h3 className="font-semibold text-lg">{game.title}</h3>
|
||||
<span className="bg-gray-200 text-gray-800 text-xs px-2 py-1 rounded">
|
||||
{sourceLabels[game.source]}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{game.releaseDate && (
|
||||
<p className="text-sm text-gray-600">
|
||||
Released: {new Date(game.releaseDate).getFullYear()}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{(game.genres || game.platforms) && (
|
||||
<div className="text-sm text-gray-600 mt-1">
|
||||
{game.genres && <p>Genres: {game.genres.join(', ')}</p>}
|
||||
{game.platforms && <p>Platforms: {game.platforms.join(', ')}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{game.description && (
|
||||
<p className="text-sm text-gray-700 mt-2 line-clamp-2">{game.description}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleSelect(game)}
|
||||
className="bg-green-600 text-white px-3 py-2 rounded-md hover:bg-green-700 font-medium h-fit whitespace-nowrap"
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{searched && results.length === 0 && (
|
||||
<div className="text-center py-4">
|
||||
<button
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="bg-gray-200 text-gray-800 px-4 py-2 rounded-md hover:bg-gray-300"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import React from 'react';
|
||||
import { RomFile } from '../../types/rom';
|
||||
|
||||
interface RomCardProps {
|
||||
rom: RomFile;
|
||||
onLinkMetadata?: (romId: string) => void;
|
||||
onDelete?: (romId: string) => void;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
export default function RomCard({ rom, onLinkMetadata, onDelete }: RomCardProps): JSX.Element {
|
||||
return (
|
||||
<div className="border border-gray-300 rounded-lg p-4 hover:shadow-md transition">
|
||||
<div className="flex justify-between items-start mb-2">
|
||||
<h3 className="font-semibold text-lg flex-1 break-all">{rom.filename}</h3>
|
||||
<span
|
||||
className={`text-xs px-2 py-1 rounded font-medium whitespace-nowrap ml-2 ${
|
||||
rom.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{rom.status}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 text-sm text-gray-600 mb-3">
|
||||
<p>
|
||||
<span className="font-medium">Size:</span> {formatBytes(rom.size)}
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium">Checksum:</span> {rom.checksum.substring(0, 8)}...
|
||||
</p>
|
||||
{rom.game && (
|
||||
<p>
|
||||
<span className="font-medium">Game:</span> {rom.game.title}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
{!rom.game && onLinkMetadata && (
|
||||
<button
|
||||
onClick={() => onLinkMetadata(rom.id)}
|
||||
className="flex-1 bg-blue-600 text-white px-3 py-2 text-sm rounded-md hover:bg-blue-700"
|
||||
>
|
||||
Link Metadata
|
||||
</button>
|
||||
)}
|
||||
{onDelete && (
|
||||
<button
|
||||
onClick={() => onDelete(rom.id)}
|
||||
className="flex-1 bg-red-600 text-white px-3 py-2 text-sm rounded-md hover:bg-red-700"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useScanDirectory } from '../../hooks/useRoms';
|
||||
|
||||
interface ScanDialogProps {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export default function ScanDialog({ isOpen, onOpenChange }: ScanDialogProps): JSX.Element | null {
|
||||
const [path, setPath] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const scanMutation = useScanDirectory();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
|
||||
if (!path.trim()) {
|
||||
setError('Please enter a directory path');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await scanMutation.mutateAsync(path);
|
||||
setSuccess(true);
|
||||
setPath('');
|
||||
setTimeout(() => {
|
||||
onOpenChange(false);
|
||||
setSuccess(false);
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to scan directory');
|
||||
}
|
||||
};
|
||||
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
|
||||
<div className="bg-white rounded-lg shadow-lg p-6 max-w-md w-full">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-semibold">Scan ROMs Directory</h2>
|
||||
<button
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="text-gray-500 hover:text-gray-700 text-xl"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="path" className="block text-sm font-medium mb-1">
|
||||
Directory Path
|
||||
</label>
|
||||
<input
|
||||
id="path"
|
||||
type="text"
|
||||
placeholder="Enter ROM directory path"
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
disabled={scanMutation.isPending}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded text-red-700 text-sm">
|
||||
<strong>Error:</strong> {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="p-3 bg-green-50 border border-green-200 rounded text-green-700 text-sm">
|
||||
Scan completed!
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={scanMutation.isPending}
|
||||
className="flex-1 bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:bg-gray-400 font-medium"
|
||||
>
|
||||
{scanMutation.isPending ? 'Scanning...' : 'Scan Directory'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="flex-1 bg-gray-200 text-gray-800 px-4 py-2 rounded-md hover:bg-gray-300 font-medium"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
69
frontend/src/components/ui/alert.tsx
Normal file
69
frontend/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { AlertTriangle, CheckCircle, Info, XCircle } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const alertVariants = cva(
|
||||
'relative w-full rounded-lg border p-4 [&>svg]:absolute [&>svg]:-top-1 [&>svg]:-left-1 [&>svg]:h-4 [&>svg]:w-4 [&>svg]:text-foreground',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground border',
|
||||
destructive:
|
||||
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
|
||||
success: 'border-green-500/50 text-green-700 dark:border-green-500 [&>svg]:text-green-700',
|
||||
warning:
|
||||
'border-yellow-500/50 text-yellow-700 dark:border-yellow-500 [&>svg]:text-yellow-700',
|
||||
info: 'border-blue-500/50 text-blue-700 dark:border-blue-500 [&>svg]:text-blue-700',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const Alert = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
|
||||
>(({ className, variant, ...props }, ref) => (
|
||||
<div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
|
||||
));
|
||||
Alert.displayName = 'Alert';
|
||||
|
||||
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h5
|
||||
ref={ref}
|
||||
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
AlertTitle.displayName = 'AlertTitle';
|
||||
|
||||
const AlertDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('text-sm [&_p]:leading-relaxed', className)} {...props} />
|
||||
));
|
||||
AlertDescription.displayName = 'AlertDescription';
|
||||
|
||||
const AlertIcon = ({ variant }: { variant?: VariantProps<typeof alertVariants>['variant'] }) => {
|
||||
switch (variant) {
|
||||
case 'destructive':
|
||||
return <XCircle className="h-4 w-4" />;
|
||||
case 'success':
|
||||
return <CheckCircle className="h-4 w-4" />;
|
||||
case 'warning':
|
||||
return <AlertTriangle className="h-4 w-4" />;
|
||||
case 'info':
|
||||
return <Info className="h-4 w-4" />;
|
||||
default:
|
||||
return <Info className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription, AlertIcon };
|
||||
31
frontend/src/components/ui/badge.tsx
Normal file
31
frontend/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
|
||||
secondary:
|
||||
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
destructive:
|
||||
'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
|
||||
outline: 'text-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
47
frontend/src/components/ui/button.tsx
Normal file
47
frontend/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
|
||||
destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
|
||||
outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
|
||||
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
link: 'text-primary underline-offset-4 hover:underline',
|
||||
},
|
||||
size: {
|
||||
default: 'h-10 px-4 py-2',
|
||||
sm: 'h-9 rounded-md px-3',
|
||||
lg: 'h-11 rounded-md px-8',
|
||||
icon: 'h-10 w-10',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return (
|
||||
<Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
55
frontend/src/components/ui/card.tsx
Normal file
55
frontend/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn('rounded-lg border bg-card text-card-foreground shadow-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn('text-2xl font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
26
frontend/src/components/ui/checkbox.tsx
Normal file
26
frontend/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import * as React from 'react';
|
||||
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
|
||||
import { Check } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator className={cn('flex items-center justify-center text-current')}>
|
||||
<Check className="h-4 w-4" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
));
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
||||
|
||||
export { Checkbox };
|
||||
23
frontend/src/components/ui/input.tsx
Normal file
23
frontend/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Input.displayName = 'Input';
|
||||
|
||||
export { Input };
|
||||
19
frontend/src/components/ui/label.tsx
Normal file
19
frontend/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import * as React from 'react';
|
||||
import * as LabelPrimitive from '@radix-ui/react-label';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const labelVariants = cva(
|
||||
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
44
frontend/src/components/ui/scroll-area.tsx
Normal file
44
frontend/src/components/ui/scroll-area.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import * as React from 'react';
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('relative overflow-hidden', className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
));
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = 'vertical', ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'flex touch-none select-none transition-colors',
|
||||
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent p-[1px]',
|
||||
orientation === 'horizontal' && 'h-2.5 w-full border-t border-t-transparent p-[1px]',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
));
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
151
frontend/src/components/ui/select.tsx
Normal file
151
frontend/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import * as React from 'react';
|
||||
import * as SelectPrimitive from '@radix-ui/react-select';
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Select = SelectPrimitive.Root;
|
||||
|
||||
const SelectGroup = SelectPrimitive.Group;
|
||||
|
||||
const SelectValue = SelectPrimitive.Value;
|
||||
|
||||
const SelectTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
));
|
||||
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
|
||||
|
||||
const SelectScrollUpButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
));
|
||||
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
|
||||
|
||||
const SelectScrollDownButton = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
ref={ref}
|
||||
className={cn('flex cursor-default items-center justify-center py-1', className)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
));
|
||||
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
|
||||
|
||||
const SelectContent = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
||||
>(({ className, children, position = 'popper', ...props }, ref) => (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
'p-1',
|
||||
position === 'popper' &&
|
||||
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
));
|
||||
SelectContent.displayName = SelectPrimitive.Content.displayName;
|
||||
|
||||
const SelectLabel = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Label>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Label
|
||||
ref={ref}
|
||||
className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectLabel.displayName = SelectPrimitive.Label.displayName;
|
||||
|
||||
const SelectItem = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<SelectPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<Check className="h-4 w-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
));
|
||||
SelectItem.displayName = SelectPrimitive.Item.displayName;
|
||||
|
||||
const SelectSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof SelectPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SelectPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn('-mx-1 my-1 h-px bg-muted', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectGroup,
|
||||
SelectValue,
|
||||
SelectTrigger,
|
||||
SelectContent,
|
||||
SelectLabel,
|
||||
SelectItem,
|
||||
SelectSeparator,
|
||||
SelectScrollUpButton,
|
||||
SelectScrollDownButton,
|
||||
};
|
||||
91
frontend/src/components/ui/table.tsx
Normal file
91
frontend/src/components/ui/table.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
Table.displayName = 'Table';
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
|
||||
));
|
||||
TableHeader.displayName = 'TableHeader';
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} />
|
||||
));
|
||||
TableBody.displayName = 'TableBody';
|
||||
|
||||
const TableFooter = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tfoot
|
||||
ref={ref}
|
||||
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableFooter.displayName = 'TableFooter';
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
TableRow.displayName = 'TableRow';
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableHead.displayName = 'TableHead';
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td
|
||||
ref={ref}
|
||||
className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableCell.displayName = 'TableCell';
|
||||
|
||||
const TableCaption = React.forwardRef<
|
||||
HTMLTableCaptionElement,
|
||||
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
TableCaption.displayName = 'TableCaption';
|
||||
|
||||
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
|
||||
23
frontend/src/components/ui/textarea.tsx
Normal file
23
frontend/src/components/ui/textarea.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
return (
|
||||
<textarea
|
||||
className={cn(
|
||||
'flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Textarea.displayName = 'Textarea';
|
||||
|
||||
export { Textarea };
|
||||
98
frontend/src/form/config.tsx
Normal file
98
frontend/src/form/config.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Esquemas de validación comunes
|
||||
export const commonSchemas = {
|
||||
// Validación de strings
|
||||
string: (min = 1, max = 255) =>
|
||||
z.string().min(min, 'Este campo es requerido').max(max, 'Máximo 255 caracteres'),
|
||||
|
||||
// Validación de emails
|
||||
email: z.string().email('Por favor ingresa un email válido').min(1, 'Este campo es requerido'),
|
||||
|
||||
// Validación de números
|
||||
number: (min = 0, max = Number.MAX_SAFE_INTEGER) =>
|
||||
z.number().min(min, 'Debe ser un número positivo').max(max, 'Número demasiado grande'),
|
||||
|
||||
// Validación de fechas
|
||||
date: z
|
||||
.date()
|
||||
.refine(
|
||||
(date) => date instanceof Date && !isNaN(date.getTime()),
|
||||
'Por favor ingresa una fecha válida'
|
||||
),
|
||||
|
||||
// Validación de booleanos
|
||||
boolean: z.boolean(),
|
||||
|
||||
// Validación de arrays
|
||||
array: (min = 1, max = 100) =>
|
||||
z
|
||||
.array(z.unknown())
|
||||
.min(min, 'Al menos un elemento requerido')
|
||||
.max(max, 'Máximo 100 elementos'),
|
||||
};
|
||||
|
||||
// Función para manejar errores de formulario
|
||||
export function getFieldError(
|
||||
fieldErrors: Record<string, string[]>,
|
||||
fieldName: string
|
||||
): string | undefined {
|
||||
const errors = fieldErrors[fieldName];
|
||||
return errors?.[0];
|
||||
}
|
||||
|
||||
// Función para manejar errores de formulario global
|
||||
export function getGlobalError(fieldErrors: Record<string, string[]>): string | undefined {
|
||||
const globalErrors = Object.values(fieldErrors).flat();
|
||||
return globalErrors?.[0];
|
||||
}
|
||||
|
||||
// Esquemas específicos para la aplicación
|
||||
export const appSchemas = {
|
||||
// Esquema para crear/editar juegos
|
||||
gameSchema: z.object({
|
||||
title: commonSchemas.string(1, 100),
|
||||
description: commonSchemas.string(0, 2000),
|
||||
platformId: commonSchemas.number(1, Number.MAX_SAFE_INTEGER),
|
||||
releaseYear: commonSchemas.number(1900, new Date().getFullYear() + 5),
|
||||
rating: z.number().min(0).max(10).optional(),
|
||||
tags: commonSchemas.array(0, 50).optional(),
|
||||
romFile: z.string().optional(),
|
||||
metadataSource: z.enum(['igdb', 'rawg', 'thegamesdb', 'manual']).optional(),
|
||||
}),
|
||||
|
||||
// Esquema para importar ROMs
|
||||
importRomSchema: z.object({
|
||||
romPath: commonSchemas.string(1, 500),
|
||||
platformId: commonSchemas.number(1, Number.MAX_SAFE_INTEGER),
|
||||
autoScan: z.boolean().default(true),
|
||||
}),
|
||||
|
||||
// Esquema para configuración
|
||||
settingsSchema: z.object({
|
||||
igdbApiKey: commonSchemas.string(0, 100).optional(),
|
||||
rawgApiKey: commonSchemas.string(0, 100).optional(),
|
||||
thegamesdbApiKey: commonSchemas.string(0, 100).optional(),
|
||||
defaultRomDirectory: commonSchemas.string(0, 500).optional(),
|
||||
autoImportEnabled: z.boolean().default(true),
|
||||
metadataSourcePriority: z
|
||||
.array(z.enum(['igdb', 'rawg', 'thegamesdb']))
|
||||
.default(['igdb', 'rawg', 'thegamesdb']),
|
||||
}),
|
||||
|
||||
// Esquema para plataformas
|
||||
platformSchema: z.object({
|
||||
name: commonSchemas.string(1, 50),
|
||||
description: commonSchemas.string(0, 500),
|
||||
manufacturer: commonSchemas.string(0, 100),
|
||||
releaseYear: commonSchemas.number(1900, new Date().getFullYear() + 5),
|
||||
romExtension: z.string().optional(),
|
||||
}),
|
||||
|
||||
// Esquema para etiquetas
|
||||
tagSchema: z.object({
|
||||
name: commonSchemas.string(1, 30),
|
||||
color: z.string().regex(/^#[0-9A-F]{6}$/i, 'Color inválido. Use formato #RRGGBB'),
|
||||
description: commonSchemas.string(0, 200),
|
||||
}),
|
||||
};
|
||||
@@ -1,45 +0,0 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../lib/api';
|
||||
import { Game, CreateGameInput, UpdateGameInput } from '../types/game';
|
||||
|
||||
const GAMES_QUERY_KEY = ['games'];
|
||||
|
||||
export function useGames() {
|
||||
return useQuery({
|
||||
queryKey: GAMES_QUERY_KEY,
|
||||
queryFn: () => api.games.list(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateGame() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: CreateGameInput) => api.games.create(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: GAMES_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateGame() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, data }: { id: string; data: UpdateGameInput }) => api.games.update(id, data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: GAMES_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteGame() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.games.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: GAMES_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../lib/api';
|
||||
import { RomFile, EnrichedGame } from '../types/rom';
|
||||
|
||||
const ROMS_QUERY_KEY = ['roms'];
|
||||
const GAMES_QUERY_KEY = ['games'];
|
||||
|
||||
export function useRoms() {
|
||||
return useQuery({
|
||||
queryKey: ROMS_QUERY_KEY,
|
||||
queryFn: () => api.roms.list(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useScanDirectory() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (dir: string) => api.import.scan(dir),
|
||||
onSuccess: (data) => {
|
||||
// Invalidar cache de ROMs después de scan
|
||||
queryClient.invalidateQueries({ queryKey: ROMS_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useEnrichMetadata() {
|
||||
return useMutation({
|
||||
mutationFn: (query: string) => api.metadata.search(query),
|
||||
});
|
||||
}
|
||||
|
||||
export function useLinkGameToRom() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ romId, gameId }: { romId: string; gameId: string }) =>
|
||||
api.roms.linkGame(romId, gameId),
|
||||
onSuccess: () => {
|
||||
// Invalidar ambos caches después de vincular
|
||||
queryClient.invalidateQueries({ queryKey: ROMS_QUERY_KEY });
|
||||
queryClient.invalidateQueries({ queryKey: GAMES_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRom() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.roms.delete(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ROMS_QUERY_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
68
frontend/src/index.css
Normal file
68
frontend/src/index.css
Normal file
@@ -0,0 +1,68 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import { Game, CreateGameInput, UpdateGameInput } from '../types/game';
|
||||
import { RomFile, EnrichedGame, ScanResult } from '../types/rom';
|
||||
|
||||
const API_BASE = '/api';
|
||||
|
||||
async function request<T>(endpoint: string, options?: RequestInit): Promise<T> {
|
||||
const response = await fetch(`${API_BASE}${endpoint}`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options?.headers,
|
||||
},
|
||||
...options,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
games: {
|
||||
list: () => request<Game[]>('/games'),
|
||||
create: (data: CreateGameInput) =>
|
||||
request<Game>('/games', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
update: (id: string, data: UpdateGameInput) =>
|
||||
request<Game>(`/games/${id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
delete: (id: string) =>
|
||||
request<void>(`/games/${id}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
},
|
||||
|
||||
roms: {
|
||||
list: () => request<RomFile[]>('/roms'),
|
||||
getById: (id: string) => request<RomFile>(`/roms/${id}`),
|
||||
linkGame: (romId: string, gameId: string) =>
|
||||
request<RomFile>(`/roms/${romId}/game`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ gameId }),
|
||||
}),
|
||||
delete: (id: string) => request<void>(`/roms/${id}`, { method: 'DELETE' }),
|
||||
},
|
||||
|
||||
metadata: {
|
||||
search: (query: string) =>
|
||||
request<EnrichedGame[]>('/metadata/search?q=' + encodeURIComponent(query)),
|
||||
},
|
||||
|
||||
import: {
|
||||
scan: (dir: string) =>
|
||||
request<ScanResult>('/import/scan', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ dir }),
|
||||
}),
|
||||
},
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient();
|
||||
6
frontend/src/lib/utils.ts
Normal file
6
frontend/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -1,32 +1,10 @@
|
||||
import React from 'react';
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient } from './lib/queryClient';
|
||||
import App from './App';
|
||||
import './styles.css';
|
||||
import './styles/globals.css';
|
||||
import App from './App.tsx';
|
||||
|
||||
const rootEl = document.getElementById('root');
|
||||
|
||||
if (rootEl) {
|
||||
createRoot(rootEl).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
}
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient } from './lib/queryClient';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
232
frontend/src/pages/DashboardPage.tsx
Normal file
232
frontend/src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,232 @@
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Gamepad2,
|
||||
Database,
|
||||
Tag,
|
||||
Download,
|
||||
Upload,
|
||||
TrendingUp,
|
||||
Clock,
|
||||
AlertCircle,
|
||||
} from 'lucide-react';
|
||||
|
||||
// Datos simulados para el dashboard
|
||||
const stats = {
|
||||
totalGames: 156,
|
||||
gamesWithRom: 128,
|
||||
gamesWithoutRom: 28,
|
||||
gamesWithMetadata: 142,
|
||||
gamesWithoutMetadata: 14,
|
||||
totalPlatforms: 12,
|
||||
totalTags: 45,
|
||||
averageRating: 7.8,
|
||||
};
|
||||
|
||||
const recentGames = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'The Legend of Zelda: Breath of the Wild',
|
||||
platform: 'Nintendo Switch',
|
||||
rating: 9.5,
|
||||
addedDate: '2024-01-10',
|
||||
},
|
||||
{ id: 2, title: 'God of War', platform: 'PlayStation 4', rating: 9.2, addedDate: '2024-01-09' },
|
||||
{ id: 3, title: 'Cyberpunk 2077', platform: 'PC', rating: 8.7, addedDate: '2024-01-08' },
|
||||
{
|
||||
id: 4,
|
||||
title: 'Super Mario Odyssey',
|
||||
platform: 'Nintendo Switch',
|
||||
rating: 9.0,
|
||||
addedDate: '2024-01-07',
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
title: 'Red Dead Redemption 2',
|
||||
platform: 'PlayStation 4',
|
||||
rating: 9.3,
|
||||
addedDate: '2024-01-06',
|
||||
},
|
||||
];
|
||||
|
||||
const pendingTasks = [
|
||||
{ id: 1, title: 'Enriquecer metadata para 14 juegos', priority: 'high', type: 'metadata' },
|
||||
{ id: 2, title: 'Importar 28 ROMs detectadas', priority: 'medium', type: 'import' },
|
||||
{ id: 3, title: 'Actualizar información de 5 juegos', priority: 'low', type: 'update' },
|
||||
];
|
||||
|
||||
export function DashboardPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Encabezado */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Dashboard</h1>
|
||||
<p className="text-muted-foreground">Resumen general de tu colección de videojuegos</p>
|
||||
</div>
|
||||
|
||||
{/* Estadísticas principales */}
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total de Juegos</CardTitle>
|
||||
<Gamepad2 className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.totalGames}</div>
|
||||
<p className="text-xs text-muted-foreground">+12% desde el mes pasado</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Juegos con ROM</CardTitle>
|
||||
<Download className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.gamesWithRom}</div>
|
||||
<p className="text-xs text-muted-foreground">de {stats.totalGames} juegos</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Juegos con Metadata</CardTitle>
|
||||
<Database className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.gamesWithMetadata}</div>
|
||||
<p className="text-xs text-muted-foreground">{stats.gamesWithoutMetadata} pendientes</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Plataformas</CardTitle>
|
||||
<Tag className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{stats.totalPlatforms}</div>
|
||||
<p className="text-xs text-muted-foreground">{stats.totalTags} etiquetas</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Tareas pendientes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tareas Pendientes</CardTitle>
|
||||
<CardDescription>
|
||||
Acciones necesarias para mantener tu colección actualizada
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{pendingTasks.map((task) => (
|
||||
<div key={task.id} className="flex items-center space-x-3">
|
||||
<div className="flex-shrink-0">
|
||||
{task.priority === 'high' && <AlertCircle className="h-5 w-5 text-red-500" />}
|
||||
{task.priority === 'medium' && <Clock className="h-5 w-5 text-yellow-500" />}
|
||||
{task.priority === 'low' && <TrendingUp className="h-5 w-5 text-green-500" />}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">{task.title}</p>
|
||||
<div className="flex items-center space-x-2 mt-1">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{task.type}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={
|
||||
task.priority === 'high'
|
||||
? 'destructive'
|
||||
: task.priority === 'medium'
|
||||
? 'default'
|
||||
: 'secondary'
|
||||
}
|
||||
className="text-xs"
|
||||
>
|
||||
{task.priority}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<Button size="sm" variant="outline">
|
||||
Ver
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<Button className="w-full" variant="outline">
|
||||
Ver todas las tareas
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Juegos recientes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Juegos Recientes</CardTitle>
|
||||
<CardDescription>Últimos juegos añadidos a tu colección</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{recentGames.map((game) => (
|
||||
<div key={game.id} className="flex items-center space-x-3">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="h-10 w-10 bg-gray-200 rounded-md flex items-center justify-center">
|
||||
<Gamepad2 className="h-6 w-6 text-gray-400" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">{game.title}</p>
|
||||
<div className="flex items-center space-x-2 mt-1">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{game.platform}
|
||||
</Badge>
|
||||
<div className="flex items-center">
|
||||
<span className="text-sm text-gray-500">★</span>
|
||||
<span className="text-sm font-medium ml-1">{game.rating}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">{game.addedDate}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<Button className="w-full" variant="outline">
|
||||
Ver todos los juegos
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Acciones rápidas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Acciones Rápidas</CardTitle>
|
||||
<CardDescription>Acciones comunes para gestionar tu colección</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<Button className="h-auto p-4 flex flex-col items-center space-y-2" variant="outline">
|
||||
<Download className="h-6 w-6" />
|
||||
<span>Importar ROMs</span>
|
||||
</Button>
|
||||
<Button className="h-auto p-4 flex flex-col items-center space-y-2" variant="outline">
|
||||
<Upload className="h-6 w-6" />
|
||||
<span>Exportar Datos</span>
|
||||
</Button>
|
||||
<Button className="h-auto p-4 flex flex-col items-center space-y-2" variant="outline">
|
||||
<Database className="h-6 w-6" />
|
||||
<span>Gestionar Plataformas</span>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
350
frontend/src/pages/GameDetailPage.tsx
Normal file
350
frontend/src/pages/GameDetailPage.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate, useParams } from '@tanstack/react-router';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Edit,
|
||||
Trash2,
|
||||
Download,
|
||||
Star,
|
||||
Calendar,
|
||||
HardDrive,
|
||||
Tag,
|
||||
ExternalLink,
|
||||
Info,
|
||||
AlertCircle,
|
||||
} from 'lucide-react';
|
||||
import { Game } from '@/types';
|
||||
|
||||
// Datos simulados para el detalle del juego
|
||||
const mockGame: Game = {
|
||||
id: 1,
|
||||
title: 'The Legend of Zelda: Breath of the Wild',
|
||||
description:
|
||||
'The Legend of Zelda: Breath of the Wild es un juego de acción-aventura desarrollado y publicado por Nintendo para la consola Nintendo Switch y la consola Wii U. Es el decimonoveno juego principal de la serie The Legend of Zelda y fue lanzado mundialmente en marzo de 2017. El juego presenta un mundo abierto con un diseño de física y química avanzado que permite a los jugadores resolver problemas de man creativas.',
|
||||
platformId: 1,
|
||||
platform: {
|
||||
id: 1,
|
||||
name: 'Nintendo Switch',
|
||||
description: 'Consola híbrida de Nintendo',
|
||||
manufacturer: 'Nintendo',
|
||||
releaseYear: 2017,
|
||||
romExtension: 'nsp',
|
||||
},
|
||||
releaseYear: 2017,
|
||||
rating: 9.5,
|
||||
tags: [
|
||||
{ id: 1, name: 'Aventura', color: '#3B82F6', description: 'Juegos de aventura' },
|
||||
{ id: 2, name: 'Acción', color: '#EF4444', description: 'Juegos de acción' },
|
||||
{ id: 3, name: 'Open World', color: '#10B981', description: 'Mundo abierto' },
|
||||
],
|
||||
romFile: {
|
||||
id: 1,
|
||||
filename: 'zelda_botw.nsp',
|
||||
path: '/roms/nintendo-switch',
|
||||
size: 14485760,
|
||||
checksum: 'abc123def456',
|
||||
gameId: 1,
|
||||
},
|
||||
metadataSource: 'manual',
|
||||
igdbId: '12345',
|
||||
rawgId: '67890',
|
||||
thegamesdbId: '54321',
|
||||
createdAt: new Date('2024-01-10'),
|
||||
updatedAt: new Date('2024-01-15'),
|
||||
};
|
||||
|
||||
export function GameDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const { gameId } = useParams({ from: '/games/$gameId' });
|
||||
const [game] = useState<Game>(mockGame);
|
||||
|
||||
const handleEdit = () => {
|
||||
navigate({ to: `/games/${game.id}/edit` });
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
// TODO: Implementar eliminación del juego
|
||||
console.log('Eliminar juego:', game.id);
|
||||
};
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Encabezado con botón de retroceso */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" onClick={() => navigate({ to: '/games' })} className="gap-2">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Volver
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{game.title}</h1>
|
||||
<p className="text-muted-foreground">Detalles del juego</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Acciones */}
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={handleEdit} className="gap-2">
|
||||
<Edit className="h-4 w-4" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Download className="h-4 w-4" />
|
||||
Descargar ROM
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDelete}
|
||||
className="gap-2 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Eliminar
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-3">
|
||||
{/* Información principal */}
|
||||
<div className="md:col-span-2 space-y-6">
|
||||
{/* Descripción */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Info className="h-5 w-5" />
|
||||
Descripción
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-muted-foreground leading-relaxed">{game.description}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Información técnica */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<HardDrive className="h-5 w-5" />
|
||||
Información Técnica
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Plataforma</Label>
|
||||
<p className="text-sm text-muted-foreground">{game.platform?.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Año de lanzamiento</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{game.releaseYear || 'Desconocido'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Tamaño del archivo</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{game.romFile ? formatFileSize(game.romFile.size) : 'No disponible'}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Checksum</Label>
|
||||
<p className="text-sm font-mono text-muted-foreground">
|
||||
{game.romFile ? game.romFile.checksum : 'No disponible'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Etiquetas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Tag className="h-5 w-5" />
|
||||
Etiquetas
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{game.tags.map((tag) => (
|
||||
<Badge
|
||||
key={tag.id}
|
||||
variant="secondary"
|
||||
style={{ backgroundColor: tag.color }}
|
||||
className="text-white"
|
||||
>
|
||||
{tag.name}
|
||||
</Badge>
|
||||
))}
|
||||
{game.tags.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">No hay etiquetas asignadas</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Panel lateral */}
|
||||
<div className="space-y-6">
|
||||
{/* Estado del juego */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Estado</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">Calificación</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
|
||||
<span className="font-medium">{game.rating || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">ROM</span>
|
||||
<Badge variant={game.romFile ? 'default' : 'secondary'}>
|
||||
{game.romFile ? 'Disponible' : 'No disponible'}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">Metadata</span>
|
||||
<Badge variant={game.metadataSource ? 'default' : 'secondary'}>
|
||||
{game.metadataSource || 'Manual'}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Fuentes externas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Fuentes Externas</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm">IGDB</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{game.igdbId ? (
|
||||
<>
|
||||
<Badge variant="outline">Conectado</Badge>
|
||||
<Button size="sm" variant="ghost">
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Badge variant="secondary">No conectado</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm">RAWG</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{game.rawgId ? (
|
||||
<>
|
||||
<Badge variant="outline">Conectado</Badge>
|
||||
<Button size="sm" variant="ghost">
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Badge variant="secondary">No conectado</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm">TheGamesDB</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{game.thegamesdbId ? (
|
||||
<>
|
||||
<Badge variant="outline">Conectado</Badge>
|
||||
<Button size="sm" variant="ghost">
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Badge variant="secondary">No conectado</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Fechas */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Información de Registro</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Fecha de creación</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{game.createdAt.toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-sm font-medium">Última actualización</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{game.updatedAt.toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Acciones adicionales */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Acciones Rápidas</CardTitle>
|
||||
<CardDescription>Acciones adicionales para gestionar este juego</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Button variant="outline" className="gap-2">
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
Buscar Metadata
|
||||
</Button>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Calendar className="h-4 w-4" />
|
||||
Añadir Fecha de Compra
|
||||
</Button>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Tag className="h-4 w-4" />
|
||||
Gestionar Etiquetas
|
||||
</Button>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<Download className="h-4 w-4" />
|
||||
Exportar Datos
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Alerta de información */}
|
||||
<Alert>
|
||||
<Info className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Esta es una vista previa del juego. Algunas características pueden no estar completamente
|
||||
implementadas en esta versión de demostración.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
435
frontend/src/pages/GamesPage.tsx
Normal file
435
frontend/src/pages/GamesPage.tsx
Normal file
@@ -0,0 +1,435 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Search, Filter, Plus, Eye, Edit, Trash2, Star } from 'lucide-react';
|
||||
import { Game } from '@/types';
|
||||
|
||||
// Datos simulados para la lista de juegos
|
||||
const mockGames: Game[] = [
|
||||
{
|
||||
id: 1,
|
||||
title: 'The Legend of Zelda: Breath of the Wild',
|
||||
description: 'Un juego de acción-aventura desarrollado por Nintendo',
|
||||
platformId: 1,
|
||||
platform: { id: 1, name: 'Nintendo Switch', description: 'Consola híbrida de Nintendo' },
|
||||
releaseYear: 2017,
|
||||
rating: 9.5,
|
||||
tags: [{ id: 1, name: 'Aventura', color: '#3B82F6', description: 'Juegos de aventura' }],
|
||||
romFile: {
|
||||
id: 1,
|
||||
filename: 'zelda_botw.nsp',
|
||||
path: '/roms/nintendo-switch',
|
||||
size: 14485760,
|
||||
checksum: 'abc123',
|
||||
},
|
||||
metadataSource: 'manual',
|
||||
createdAt: new Date('2024-01-10'),
|
||||
updatedAt: new Date('2024-01-10'),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'God of War',
|
||||
description: 'Un juego de acción-aventura basado en la mitología nórdica',
|
||||
platformId: 2,
|
||||
platform: { id: 2, name: 'PlayStation 4', description: 'Consola de Sony' },
|
||||
releaseYear: 2018,
|
||||
rating: 9.2,
|
||||
tags: [{ id: 2, name: 'Acción', color: '#EF4444', description: 'Juegos de acción' }],
|
||||
romFile: {
|
||||
id: 2,
|
||||
filename: 'god_of_war.iso',
|
||||
path: '/roms/ps4',
|
||||
size: 45234120,
|
||||
checksum: 'def456',
|
||||
},
|
||||
metadataSource: 'igdb',
|
||||
createdAt: new Date('2024-01-09'),
|
||||
updatedAt: new Date('2024-01-09'),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Cyberpunk 2077',
|
||||
description: 'Un RPG de acción en mundo abierto ambientado en Night City',
|
||||
platformId: 3,
|
||||
platform: { id: 3, name: 'PC', description: 'Plataforma de computadora personal' },
|
||||
releaseYear: 2020,
|
||||
rating: 8.7,
|
||||
tags: [{ id: 3, name: 'RPG', color: '#10B981', description: 'Juegos de rol' }],
|
||||
romFile: undefined,
|
||||
metadataSource: 'rawg',
|
||||
createdAt: new Date('2024-01-08'),
|
||||
updatedAt: new Date('2024-01-08'),
|
||||
},
|
||||
];
|
||||
|
||||
const platforms = [
|
||||
{ id: 1, name: 'Nintendo Switch' },
|
||||
{ id: 2, name: 'PlayStation 4' },
|
||||
{ id: 3, name: 'PC' },
|
||||
{ id: 4, name: 'Xbox One' },
|
||||
];
|
||||
|
||||
const tags = [
|
||||
{ id: 1, name: 'Aventura', color: '#3B82F6' },
|
||||
{ id: 2, name: 'Acción', color: '#EF4444' },
|
||||
{ id: 3, name: 'RPG', color: '#10B981' },
|
||||
{ id: 4, name: 'Estrategia', color: '#F59E0B' },
|
||||
];
|
||||
|
||||
export function GamesPage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedPlatform, setSelectedPlatform] = useState<string>('');
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
const [sortBy, setSortBy] = useState<string>('title');
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [games] = useState<Game[]>(mockGames);
|
||||
|
||||
// Filtrar y ordenar juegos
|
||||
const filteredGames = games
|
||||
.filter((game) => {
|
||||
const matchesSearch =
|
||||
game.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
game.description?.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
const matchesPlatform = !selectedPlatform || game.platformId.toString() === selectedPlatform;
|
||||
const matchesTags =
|
||||
selectedTags.length === 0 ||
|
||||
selectedTags.some((tagId) => game.tags.some((tag) => tag.id.toString() === tagId));
|
||||
|
||||
return matchesSearch && matchesPlatform && matchesTags;
|
||||
})
|
||||
.sort((a, b) => {
|
||||
let aValue: string | number = '';
|
||||
let bValue: string | number = '';
|
||||
|
||||
switch (sortBy) {
|
||||
case 'title':
|
||||
aValue = a.title?.toLowerCase() || '';
|
||||
bValue = b.title?.toLowerCase() || '';
|
||||
break;
|
||||
case 'platform':
|
||||
aValue = a.platform?.name?.toLowerCase() || '';
|
||||
bValue = b.platform?.name?.toLowerCase() || '';
|
||||
break;
|
||||
case 'releaseYear':
|
||||
aValue = a.releaseYear || 0;
|
||||
bValue = b.releaseYear || 0;
|
||||
break;
|
||||
case 'rating':
|
||||
aValue = a.rating || 0;
|
||||
bValue = b.rating || 0;
|
||||
break;
|
||||
default:
|
||||
aValue = a.title?.toLowerCase() || '';
|
||||
bValue = b.title?.toLowerCase() || '';
|
||||
}
|
||||
|
||||
if (sortOrder === 'asc') {
|
||||
return aValue > bValue ? 1 : -1;
|
||||
} else {
|
||||
return aValue < bValue ? 1 : -1;
|
||||
}
|
||||
});
|
||||
|
||||
const handleSort = (field: string) => {
|
||||
if (sortBy === field) {
|
||||
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
setSortBy(field);
|
||||
setSortOrder('asc');
|
||||
}
|
||||
};
|
||||
|
||||
const handleTagToggle = (tagId: string) => {
|
||||
setSelectedTags((prev) =>
|
||||
prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId]
|
||||
);
|
||||
};
|
||||
|
||||
const clearFilters = () => {
|
||||
setSearchTerm('');
|
||||
setSelectedPlatform('');
|
||||
setSelectedTags([]);
|
||||
setSortBy('title');
|
||||
setSortOrder('asc');
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
const handleGameClick = (gameId: number) => {
|
||||
navigate({ to: `/games/${gameId}` });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Encabezado */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Juegos</h1>
|
||||
<p className="text-muted-foreground">Gestiona tu colección de videojuegos</p>
|
||||
</div>
|
||||
<Button onClick={() => navigate({ to: '/games/create' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Nuevo Juego
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Filtros */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Filter className="h-5 w-5" />
|
||||
Filtros y Búsqueda
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
{/* Búsqueda */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search">Buscar</Label>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
id="search"
|
||||
placeholder="Buscar juegos..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plataforma */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="platform">Plataforma</Label>
|
||||
<Select value={selectedPlatform} onValueChange={setSelectedPlatform}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Todas las plataformas" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="">Todas las plataformas</SelectItem>
|
||||
{platforms.map((platform) => (
|
||||
<SelectItem key={platform.id} value={platform.id.toString()}>
|
||||
{platform.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Ordenar por */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="sort">Ordenar por</Label>
|
||||
<Select value={sortBy} onValueChange={setSortBy}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="title">Título</SelectItem>
|
||||
<SelectItem value="releaseYear">Año de lanzamiento</SelectItem>
|
||||
<SelectItem value="rating">Calificación</SelectItem>
|
||||
<SelectItem value="platform">Plataforma</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Acciones */}
|
||||
<div className="space-y-2">
|
||||
<Label> </Label>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={clearFilters}>
|
||||
Limpiar filtros
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtros de etiquetas */}
|
||||
<div className="mt-4 space-y-2">
|
||||
<Label>Etiquetas</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{tags.map((tag) => (
|
||||
<Badge
|
||||
key={tag.id}
|
||||
variant={selectedTags.includes(tag.id.toString()) ? 'default' : 'outline'}
|
||||
className="cursor-pointer"
|
||||
style={
|
||||
selectedTags.includes(tag.id.toString()) ? { backgroundColor: tag.color } : {}
|
||||
}
|
||||
onClick={() => handleTagToggle(tag.id.toString())}
|
||||
>
|
||||
{tag.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Tabla de juegos */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Lista de Juegos ({filteredGames.length})</CardTitle>
|
||||
<CardDescription>
|
||||
{filteredGames.length === 0 ? 'No se encontraron juegos' : 'Juegos en tu colección'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => handleSort('title')}
|
||||
>
|
||||
Título {sortBy === 'title' && (sortOrder === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead>Plataforma</TableHead>
|
||||
<TableHead
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => handleSort('releaseYear')}
|
||||
>
|
||||
Año {sortBy === 'releaseYear' && (sortOrder === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => handleSort('rating')}
|
||||
>
|
||||
Calificación {sortBy === 'rating' && (sortOrder === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead>Etiquetas</TableHead>
|
||||
<TableHead>ROM</TableHead>
|
||||
<TableHead className="w-[100px]">Acciones</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{filteredGames.map((game) => (
|
||||
<TableRow
|
||||
key={game.id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => handleGameClick(game.id)}
|
||||
>
|
||||
<TableCell className="font-medium">{game.title}</TableCell>
|
||||
<TableCell>{game.platform?.name}</TableCell>
|
||||
<TableCell>{game.releaseYear || '-'}</TableCell>
|
||||
<TableCell>
|
||||
{game.rating ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
|
||||
<span>{game.rating}</span>
|
||||
</div>
|
||||
) : (
|
||||
'-'
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{game.tags.map((tag) => (
|
||||
<Badge
|
||||
key={tag.id}
|
||||
variant="secondary"
|
||||
style={{ backgroundColor: tag.color }}
|
||||
className="text-white"
|
||||
>
|
||||
{tag.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{game.romFile ? (
|
||||
<Badge variant="default">✓</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">-</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate({ to: `/games/${game.id}` });
|
||||
}}
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate({ to: `/games/${game.id}/edit` });
|
||||
}}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
// TODO: Implementar eliminación
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Paginación */}
|
||||
<div className="flex items-center justify-between space-x-2 py-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Mostrando {filteredGames.length} juegos
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
|
||||
disabled={currentPage === 1}
|
||||
>
|
||||
Anterior
|
||||
</Button>
|
||||
<span className="text-sm">Página {currentPage}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setCurrentPage(currentPage + 1)}
|
||||
disabled={filteredGames.length < 10}
|
||||
>
|
||||
Siguiente
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
36
frontend/src/query/client.tsx
Normal file
36
frontend/src/query/client.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 1000 * 60 * 5, // 5 minutos
|
||||
refetchOnWindowFocus: false,
|
||||
retry: (failureCount, error) => {
|
||||
// No reintentar si es un error de 404 o 401
|
||||
if (error instanceof Error) {
|
||||
const status = (error as any).status;
|
||||
if (status === 404 || status === 401) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Reintentar hasta 3 veces para otros errores
|
||||
return failureCount < 3;
|
||||
},
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff
|
||||
},
|
||||
mutations: {
|
||||
retry: (failureCount, error) => {
|
||||
// No reintentar si es un error de 404 o 401
|
||||
if (error instanceof Error) {
|
||||
const status = (error as any).status;
|
||||
if (status === 404 || status === 401) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Reintentar hasta 2 veces para otros errores
|
||||
return failureCount < 2;
|
||||
},
|
||||
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff
|
||||
},
|
||||
},
|
||||
});
|
||||
99
frontend/src/router.tsx
Normal file
99
frontend/src/router.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
import { createRootRoute, createRoute, createRouter } from '@tanstack/react-router';
|
||||
import { lazy } from 'react';
|
||||
|
||||
// Layout principal
|
||||
const Layout = lazy(() => import('./components/layout/Layout'));
|
||||
|
||||
// Páginas
|
||||
const DashboardPage = lazy(() => import('./pages/DashboardPage'));
|
||||
const GamesPage = lazy(() => import('./pages/GamesPage'));
|
||||
const GameDetailPage = lazy(() => import('./pages/GameDetailPage'));
|
||||
const CreateGamePage = lazy(() => import('./pages/CreateGamePage'));
|
||||
const ImportRomPage = lazy(() => import('./pages/ImportRomPage'));
|
||||
const SettingsPage = lazy(() => import('./pages/SettingsPage'));
|
||||
const PlatformsPage = lazy(() => import('./pages/PlatformsPage'));
|
||||
const TagsPage = lazy(() => import('./pages/TagsPage'));
|
||||
const ExportPage = lazy(() => import('./pages/ExportPage'));
|
||||
|
||||
// Ruta raíz
|
||||
const rootRoute = createRootRoute({
|
||||
component: Layout,
|
||||
});
|
||||
|
||||
// Rutas principales
|
||||
const dashboardRoute = createRoute({
|
||||
path: '/',
|
||||
component: DashboardPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const gamesRoute = createRoute({
|
||||
path: '/games',
|
||||
component: GamesPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const gameDetailRoute = createRoute({
|
||||
path: '/games/$gameId',
|
||||
component: GameDetailPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const createGameRoute = createRoute({
|
||||
path: '/games/create',
|
||||
component: CreateGamePage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const importRoute = createRoute({
|
||||
path: '/import',
|
||||
component: ImportRomPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const settingsRoute = createRoute({
|
||||
path: '/settings',
|
||||
component: SettingsPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const platformsRoute = createRoute({
|
||||
path: '/platforms',
|
||||
component: PlatformsPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const tagsRoute = createRoute({
|
||||
path: '/tags',
|
||||
component: TagsPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
const exportRoute = createRoute({
|
||||
path: '/export',
|
||||
component: ExportPage,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
// Ruta de not found
|
||||
const notFoundRoute = createRoute({
|
||||
path: '*',
|
||||
component: () => <div>Página no encontrada</div>,
|
||||
getParentRoute: () => rootRoute,
|
||||
});
|
||||
|
||||
// Crear router
|
||||
export const router = createRouter({
|
||||
routeTree: rootRoute.addChildren([
|
||||
dashboardRoute,
|
||||
gamesRoute,
|
||||
gameDetailRoute,
|
||||
createGameRoute,
|
||||
importRoute,
|
||||
settingsRoute,
|
||||
platformsRoute,
|
||||
tagsRoute,
|
||||
exportRoute,
|
||||
notFoundRoute,
|
||||
]),
|
||||
});
|
||||
@@ -1,165 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useGames, useCreateGame, useUpdateGame, useDeleteGame } from '../hooks/useGames';
|
||||
import GameForm from '../components/games/GameForm';
|
||||
import { Game, CreateGameInput, UpdateGameInput } from '../types/game';
|
||||
|
||||
export default function Games(): JSX.Element {
|
||||
const { data: games, isLoading, error } = useGames();
|
||||
const createMutation = useCreateGame();
|
||||
const updateMutation = useUpdateGame();
|
||||
const deleteMutation = useDeleteGame();
|
||||
|
||||
const [isFormOpen, setIsFormOpen] = useState(false);
|
||||
const [selectedGame, setSelectedGame] = useState<Game | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
|
||||
|
||||
const handleCreate = async (data: CreateGameInput | Game) => {
|
||||
try {
|
||||
await createMutation.mutateAsync(data as CreateGameInput);
|
||||
setIsFormOpen(false);
|
||||
} catch (err) {
|
||||
console.error('Failed to create game:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (data: CreateGameInput | Game) => {
|
||||
if (!selectedGame) return;
|
||||
try {
|
||||
await updateMutation.mutateAsync({
|
||||
id: selectedGame.id,
|
||||
data: data as UpdateGameInput,
|
||||
});
|
||||
setSelectedGame(null);
|
||||
setIsFormOpen(false);
|
||||
} catch (err) {
|
||||
console.error('Failed to update game:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
await deleteMutation.mutateAsync(id);
|
||||
setDeleteConfirm(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to delete game:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenForm = (game?: Game) => {
|
||||
if (game) {
|
||||
setSelectedGame(game);
|
||||
} else {
|
||||
setSelectedGame(null);
|
||||
}
|
||||
setIsFormOpen(true);
|
||||
};
|
||||
|
||||
const handleCloseForm = () => {
|
||||
setIsFormOpen(false);
|
||||
setSelectedGame(null);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="p-4">
|
||||
<h2 className="text-xl font-bold text-red-600">Error</h2>
|
||||
<p>{error instanceof Error ? error.message : 'Failed to load games'}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h2 className="text-2xl font-bold">Games</h2>
|
||||
<button
|
||||
onClick={() => handleOpenForm()}
|
||||
className="rounded bg-green-600 px-4 py-2 text-white hover:bg-green-700 disabled:bg-gray-400"
|
||||
disabled={isLoading}
|
||||
>
|
||||
Add Game
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isFormOpen && (
|
||||
<div className="mb-6 rounded border border-gray-300 p-4">
|
||||
<div className="mb-4 flex justify-between">
|
||||
<h3 className="text-lg font-semibold">{selectedGame ? 'Edit Game' : 'Create Game'}</h3>
|
||||
<button onClick={handleCloseForm} className="text-gray-600 hover:text-gray-900">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<GameForm
|
||||
initialData={selectedGame || undefined}
|
||||
onSubmit={selectedGame ? handleUpdate : handleCreate}
|
||||
isLoading={createMutation.isPending || updateMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && !games ? (
|
||||
<p className="text-gray-600">Loading games...</p>
|
||||
) : !games || games.length === 0 ? (
|
||||
<p className="text-gray-600">No games found. Create one to get started!</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse border border-gray-300">
|
||||
<thead className="bg-gray-100">
|
||||
<tr>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Title</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Slug</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Created</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-center">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{games.map((game) => (
|
||||
<tr key={game.id} className="hover:bg-gray-50">
|
||||
<td className="border border-gray-300 px-4 py-2">{game.title}</td>
|
||||
<td className="border border-gray-300 px-4 py-2">{game.slug}</td>
|
||||
<td className="border border-gray-300 px-4 py-2">
|
||||
{new Date(game.createdAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2 text-center">
|
||||
<button
|
||||
onClick={() => handleOpenForm(game)}
|
||||
className="mr-2 rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700"
|
||||
disabled={updateMutation.isPending || deleteMutation.isPending}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
{deleteConfirm === game.id ? (
|
||||
<div className="inline-flex gap-2">
|
||||
<button
|
||||
onClick={() => handleDelete(game.id)}
|
||||
className="rounded bg-red-600 px-3 py-1 text-sm text-white hover:bg-red-700"
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(null)}
|
||||
className="rounded bg-gray-600 px-3 py-1 text-sm text-white hover:bg-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(game.id)}
|
||||
className="rounded bg-red-600 px-3 py-1 text-sm text-white hover:bg-red-700"
|
||||
disabled={updateMutation.isPending || deleteMutation.isPending}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
export default function Home(): JSX.Element {
|
||||
return (
|
||||
<div>
|
||||
<h2>Home</h2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
useRoms,
|
||||
useScanDirectory,
|
||||
useEnrichMetadata,
|
||||
useLinkGameToRom,
|
||||
useDeleteRom,
|
||||
} from '../hooks/useRoms';
|
||||
import ScanDialog from '../components/roms/ScanDialog';
|
||||
import MetadataSearchDialog from '../components/roms/MetadataSearchDialog';
|
||||
import { EnrichedGame, RomFile } from '../types/rom';
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
export default function Roms(): JSX.Element {
|
||||
const { data: roms, isLoading, error } = useRoms();
|
||||
const scanMutation = useScanDirectory();
|
||||
const enrichMutation = useEnrichMetadata();
|
||||
const linkMutation = useLinkGameToRom();
|
||||
const deleteMutation = useDeleteRom();
|
||||
|
||||
const [isScanDialogOpen, setIsScanDialogOpen] = useState(false);
|
||||
const [isMetadataDialogOpen, setIsMetadataDialogOpen] = useState(false);
|
||||
const [selectedRomId, setSelectedRomId] = useState<string | null>(null);
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
|
||||
|
||||
const handleDeleteRom = async (id: string) => {
|
||||
try {
|
||||
await deleteMutation.mutateAsync(id);
|
||||
setDeleteConfirm(null);
|
||||
} catch (err) {
|
||||
console.error('Failed to delete ROM:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMetadataSelect = async (game: EnrichedGame) => {
|
||||
if (!selectedRomId || !game.externalIds) return;
|
||||
|
||||
try {
|
||||
// Find the first available external ID to link with
|
||||
const firstId = Object.entries(game.externalIds).find(([, value]) => value)?.[1];
|
||||
|
||||
if (firstId) {
|
||||
// This creates a new game and links it
|
||||
// For now, we'll just close the dialog
|
||||
// In a real implementation, the API would handle game creation
|
||||
setIsMetadataDialogOpen(false);
|
||||
setSelectedRomId(null);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to link metadata:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenMetadataDialog = (romId: string) => {
|
||||
setSelectedRomId(romId);
|
||||
setIsMetadataDialogOpen(true);
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="p-4">
|
||||
<h2 className="text-xl font-bold text-red-600">Error</h2>
|
||||
<p className="text-red-700">
|
||||
{error instanceof Error ? error.message : 'Failed to load ROMs'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h2 className="text-2xl font-bold">ROMs</h2>
|
||||
<button
|
||||
onClick={() => setIsScanDialogOpen(true)}
|
||||
className="rounded bg-green-600 px-4 py-2 text-white hover:bg-green-700 disabled:bg-gray-400"
|
||||
disabled={isLoading || scanMutation.isPending}
|
||||
>
|
||||
Scan Directory
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ScanDialog isOpen={isScanDialogOpen} onOpenChange={setIsScanDialogOpen} />
|
||||
|
||||
{selectedRomId && (
|
||||
<MetadataSearchDialog
|
||||
romId={selectedRomId}
|
||||
isOpen={isMetadataDialogOpen}
|
||||
onOpenChange={setIsMetadataDialogOpen}
|
||||
onSelect={handleMetadataSelect}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isLoading && !roms ? (
|
||||
<p className="text-gray-600">Loading ROMs...</p>
|
||||
) : !roms || roms.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-500">
|
||||
<p className="text-lg mb-4">No ROMs yet. Click 'Scan Directory' to get started.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse border border-gray-300">
|
||||
<thead className="bg-gray-100">
|
||||
<tr>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Filename</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Size</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Checksum</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Status</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-left">Game</th>
|
||||
<th className="border border-gray-300 px-4 py-2 text-center">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{roms.map((rom) => (
|
||||
<tr key={rom.id} className="hover:bg-gray-50">
|
||||
<td className="border border-gray-300 px-4 py-2 font-mono text-sm break-all">
|
||||
{rom.filename}
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2 text-sm">
|
||||
{formatBytes(rom.size)}
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2 font-mono text-sm">
|
||||
{rom.checksum.substring(0, 8)}...
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2 text-sm">
|
||||
<span
|
||||
className={`px-2 py-1 rounded text-xs font-medium ${
|
||||
rom.status === 'active'
|
||||
? 'bg-green-100 text-green-800'
|
||||
: 'bg-red-100 text-red-800'
|
||||
}`}
|
||||
>
|
||||
{rom.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2">
|
||||
{rom.game ? (
|
||||
<span className="text-sm font-medium">{rom.game.title}</span>
|
||||
) : (
|
||||
<span className="text-sm text-gray-500">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="border border-gray-300 px-4 py-2 text-center">
|
||||
{!rom.game && (
|
||||
<button
|
||||
onClick={() => handleOpenMetadataDialog(rom.id)}
|
||||
className="mr-2 rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700 disabled:bg-gray-400"
|
||||
disabled={
|
||||
enrichMutation.isPending ||
|
||||
linkMutation.isPending ||
|
||||
deleteMutation.isPending
|
||||
}
|
||||
>
|
||||
Link Metadata
|
||||
</button>
|
||||
)}
|
||||
{deleteConfirm === rom.id ? (
|
||||
<div className="inline-flex gap-1">
|
||||
<button
|
||||
onClick={() => handleDeleteRom(rom.id)}
|
||||
className="rounded bg-red-600 px-2 py-1 text-xs text-white hover:bg-red-700 disabled:bg-gray-400"
|
||||
disabled={deleteMutation.isPending}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(null)}
|
||||
className="rounded bg-gray-600 px-2 py-1 text-xs text-white hover:bg-gray-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setDeleteConfirm(rom.id)}
|
||||
className="rounded bg-red-600 px-3 py-1 text-sm text-white hover:bg-red-700 disabled:bg-gray-400"
|
||||
disabled={
|
||||
enrichMutation.isPending ||
|
||||
linkMutation.isPending ||
|
||||
deleteMutation.isPending
|
||||
}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
import '@testing-library/jest-dom';
|
||||
import '@testing-library/jest-dom';
|
||||
@@ -1,16 +0,0 @@
|
||||
/* Minimal global styles */
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
font-family:
|
||||
system-ui,
|
||||
-apple-system,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
'Helvetica Neue',
|
||||
Arial;
|
||||
}
|
||||
61
frontend/src/styles/globals.css
Normal file
61
frontend/src/styles/globals.css
Normal file
@@ -0,0 +1,61 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 263.4 70% 50.4%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 263.4 70% 50.4%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 222.2 84% 4.9%;
|
||||
--foreground: 210 40% 98%;
|
||||
--card: 222.2 84% 4.9%;
|
||||
--card-foreground: 210 40% 98%;
|
||||
--popover: 222.2 84% 4.9%;
|
||||
--popover-foreground: 210 40% 98%;
|
||||
--primary: 263.4 70% 50.4%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 217.2 32.6% 17.5%;
|
||||
--secondary-foreground: 210 40% 98%;
|
||||
--muted: 217.2 32.6% 17.5%;
|
||||
--muted-foreground: 215 20.2% 65.1%;
|
||||
--accent: 217.2 32.6% 17.5%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 210 40% 98%;
|
||||
--border: 217.2 32.6% 17.5%;
|
||||
--input: 217.2 32.6% 17.5%;
|
||||
--ring: 263.4 70% 50.4%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-feature-settings: 'rlig' 1, 'calt' 1;
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
export type GameCondition = 'Loose' | 'CIB' | 'New';
|
||||
|
||||
export interface Game {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
description?: string | null;
|
||||
releaseDate?: Date | null | string;
|
||||
igdbId?: number | null;
|
||||
rawgId?: number | null;
|
||||
thegamesdbId?: number | null;
|
||||
extra?: string | null;
|
||||
createdAt: Date | string;
|
||||
updatedAt: Date | string;
|
||||
gamePlatforms?: GamePlatform[];
|
||||
purchases?: Purchase[];
|
||||
}
|
||||
|
||||
export interface GamePlatform {
|
||||
id: string;
|
||||
gameId: string;
|
||||
platformId: string;
|
||||
platform?: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Purchase {
|
||||
id: string;
|
||||
gameId: string;
|
||||
priceCents: number;
|
||||
currency: string;
|
||||
store?: string | null;
|
||||
date: Date | string;
|
||||
receiptPath?: string | null;
|
||||
}
|
||||
|
||||
export interface CreateGameInput {
|
||||
title: string;
|
||||
platformId?: string;
|
||||
description?: string | null;
|
||||
priceCents?: number;
|
||||
currency?: string;
|
||||
store?: string;
|
||||
date?: string;
|
||||
condition?: GameCondition;
|
||||
}
|
||||
|
||||
export interface UpdateGameInput {
|
||||
title?: string;
|
||||
platformId?: string;
|
||||
description?: string | null;
|
||||
priceCents?: number;
|
||||
currency?: string;
|
||||
store?: string;
|
||||
date?: string;
|
||||
condition?: GameCondition;
|
||||
}
|
||||
238
frontend/src/types/index.ts
Normal file
238
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
// Tipos base de la aplicación
|
||||
export interface BaseEntity {
|
||||
id: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
// Tipos de Juego
|
||||
export interface Game extends BaseEntity {
|
||||
title: string;
|
||||
description?: string;
|
||||
platformId: number;
|
||||
platform?: Platform;
|
||||
releaseYear?: number;
|
||||
rating?: number;
|
||||
tags: Tag[];
|
||||
romFile?: RomFile;
|
||||
metadataSource?: 'igdb' | 'rawg' | 'thegamesdb' | 'manual';
|
||||
igdbId?: string;
|
||||
rawgId?: string;
|
||||
thegamesdbId?: string;
|
||||
}
|
||||
|
||||
// Tipos de Plataforma
|
||||
export interface Platform extends BaseEntity {
|
||||
name: string;
|
||||
description?: string;
|
||||
manufacturer?: string;
|
||||
releaseYear?: number;
|
||||
romExtension?: string;
|
||||
games: Game[];
|
||||
}
|
||||
|
||||
// Tipos de ROM
|
||||
export interface RomFile extends BaseEntity {
|
||||
filename: string;
|
||||
path: string;
|
||||
size: number;
|
||||
checksum: string;
|
||||
gameId: number;
|
||||
game?: Game;
|
||||
}
|
||||
|
||||
// Tipos de Etiqueta
|
||||
export interface Tag extends BaseEntity {
|
||||
name: string;
|
||||
color: string;
|
||||
description?: string;
|
||||
games: Game[];
|
||||
}
|
||||
|
||||
// Tipos de Compra
|
||||
export interface Purchase extends BaseEntity {
|
||||
gameId: number;
|
||||
game?: Game;
|
||||
price: number;
|
||||
currency: string;
|
||||
purchaseDate: Date;
|
||||
store?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
// Tipos de Historial de Precios
|
||||
export interface PriceHistory extends BaseEntity {
|
||||
gameId: number;
|
||||
game?: Game;
|
||||
price: number;
|
||||
currency: string;
|
||||
date: Date;
|
||||
}
|
||||
|
||||
// Tipos de Arte
|
||||
export interface Artwork extends BaseEntity {
|
||||
gameId: number;
|
||||
game?: Game;
|
||||
type: 'cover' | 'screenshot' | 'logo' | 'banner';
|
||||
url: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
// Tipos de Configuración
|
||||
export interface Settings {
|
||||
igdbApiKey?: string;
|
||||
rawgApiKey?: string;
|
||||
thegamesdbApiKey?: string;
|
||||
defaultRomDirectory?: string;
|
||||
autoImportEnabled: boolean;
|
||||
metadataSourcePriority: ('igdb' | 'rawg' | 'thegamesdb')[];
|
||||
}
|
||||
|
||||
// Tipos de API Response
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
message?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface PaginatedResponse<T> {
|
||||
data: T[];
|
||||
pagination: {
|
||||
page: number;
|
||||
limit: number;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}
|
||||
|
||||
// Tipos de Filtros
|
||||
export interface GameFilters {
|
||||
search?: string;
|
||||
platformId?: number;
|
||||
tags?: number[];
|
||||
rating?: number;
|
||||
releaseYear?: number;
|
||||
metadataSource?: string;
|
||||
hasRom?: boolean;
|
||||
}
|
||||
|
||||
export interface PlatformFilters {
|
||||
search?: string;
|
||||
manufacturer?: string;
|
||||
releaseYear?: number;
|
||||
}
|
||||
|
||||
export interface TagFilters {
|
||||
search?: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
// Tipos de Formularios
|
||||
export interface GameFormData {
|
||||
title: string;
|
||||
description?: string;
|
||||
platformId: number;
|
||||
releaseYear?: number;
|
||||
rating?: number;
|
||||
tags?: number[];
|
||||
romFile?: File;
|
||||
metadataSource?: 'igdb' | 'rawg' | 'thegamesdb' | 'manual';
|
||||
}
|
||||
|
||||
export interface PlatformFormData {
|
||||
name: string;
|
||||
description?: string;
|
||||
manufacturer?: string;
|
||||
releaseYear?: number;
|
||||
romExtension?: string;
|
||||
}
|
||||
|
||||
export interface TagFormData {
|
||||
name: string;
|
||||
color: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface ImportRomFormData {
|
||||
romPath: string;
|
||||
platformId: number;
|
||||
autoScan: boolean;
|
||||
}
|
||||
|
||||
export interface SettingsFormData {
|
||||
igdbApiKey?: string;
|
||||
rawgApiKey?: string;
|
||||
thegamesdbApiKey?: string;
|
||||
defaultRomDirectory?: string;
|
||||
autoImportEnabled: boolean;
|
||||
metadataSourcePriority: ('igdb' | 'rawg' | 'thegamesdb')[];
|
||||
}
|
||||
|
||||
// Tipos de Metadata
|
||||
export interface GameMetadata {
|
||||
title: string;
|
||||
description?: string;
|
||||
releaseDate?: string;
|
||||
rating?: number;
|
||||
genres?: string[];
|
||||
platforms?: string[];
|
||||
coverUrl?: string;
|
||||
screenshots?: string[];
|
||||
developer?: string;
|
||||
publisher?: string;
|
||||
region?: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
// Tipos de Errores
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
code?: string;
|
||||
details?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export interface ValidationError {
|
||||
field: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Tipos de UI
|
||||
export interface MenuItem {
|
||||
label: string;
|
||||
href: string;
|
||||
icon?: string;
|
||||
children?: MenuItem[];
|
||||
}
|
||||
|
||||
export interface BreadcrumbItem {
|
||||
label: string;
|
||||
href?: string;
|
||||
}
|
||||
|
||||
export interface TableColumn<T> {
|
||||
key: keyof T;
|
||||
label: string;
|
||||
sortable?: boolean;
|
||||
render?: (value: any, record: T) => React.ReactNode;
|
||||
}
|
||||
|
||||
// Tipos de Hooks
|
||||
export interface UseQueryOptions<T> {
|
||||
enabled?: boolean;
|
||||
refetchOnWindowFocus?: boolean;
|
||||
refetchOnMount?: boolean;
|
||||
refetchOnReconnect?: boolean;
|
||||
staleTime?: number;
|
||||
cacheTime?: number;
|
||||
retry?: number;
|
||||
retryDelay?: number;
|
||||
}
|
||||
|
||||
export interface UseMutationOptions<T> {
|
||||
onSuccess?: (data: T) => void;
|
||||
onError?: (error: Error) => void;
|
||||
onSettled?: () => void;
|
||||
retry?: number;
|
||||
retryDelay?: number;
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { Game } from './game';
|
||||
|
||||
export interface RomFile {
|
||||
id: string;
|
||||
path: string;
|
||||
filename: string;
|
||||
checksum: string;
|
||||
size: number;
|
||||
format: string;
|
||||
hashes?: {
|
||||
crc32?: string;
|
||||
md5?: string;
|
||||
sha1?: string;
|
||||
} | null;
|
||||
gameId?: string | null;
|
||||
game?: Game | null;
|
||||
status: 'active' | 'missing';
|
||||
addedAt: string;
|
||||
lastSeenAt?: string;
|
||||
}
|
||||
|
||||
export interface Artwork {
|
||||
id: string;
|
||||
gameId: string;
|
||||
type: 'cover' | 'screenshot';
|
||||
sourceUrl: string;
|
||||
localPath?: string | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
}
|
||||
|
||||
export interface EnrichedGame {
|
||||
source: 'igdb' | 'rawg' | 'thegamesdb';
|
||||
externalIds: {
|
||||
igdb?: number;
|
||||
rawg?: number;
|
||||
thegamesdb?: number;
|
||||
};
|
||||
title: string;
|
||||
slug?: string;
|
||||
releaseDate?: string;
|
||||
genres?: string[];
|
||||
platforms?: string[];
|
||||
coverUrl?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface ScanResult {
|
||||
processed: number;
|
||||
createdCount: number;
|
||||
upserted: number;
|
||||
}
|
||||
Reference in New Issue
Block a user