Fase 2: Creación del frontend con React, Vite y MUI. Implementada tabla de titulares con funcionalidad de arrastrar y soltar.

This commit is contained in:
2025-10-28 11:45:51 -03:00
parent 2c44081e5d
commit 8e783b73d5
18 changed files with 4899 additions and 3 deletions

View File

@@ -23,7 +23,7 @@ builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp", builder =>
{
builder.WithOrigins("http://localhost:5173")
builder.WithOrigins("http://localhost:5174")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();

View File

@@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5173",
"applicationUrl": "http://localhost:5174",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -14,7 +14,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7000;http://localhost:5173",
"applicationUrl": "https://localhost:7000;http://localhost:5174",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
frontend/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

4447
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
frontend/package.json Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.4",
"@mui/material": "^7.3.4",
"axios": "^1.13.0",
"react": "^19.1.1",
"react-dom": "^19.1.1"
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@types/node": "^24.6.0",
"@types/react": "^19.1.16",
"@types/react-dom": "^19.1.9",
"@vitejs/plugin-react": "^5.0.4",
"eslint": "^9.36.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.22",
"globals": "^16.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.45.0",
"vite": "^7.1.7"
}
}

33
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,33 @@
// frontend/src/App.tsx
import { ThemeProvider, createTheme, CssBaseline, Box } from '@mui/material';
import TablaTitulares from './components/TablaTitulares'; // Lo crearemos ahora
// Definimos un tema oscuro similar al de la imagen de referencia
const darkTheme = createTheme({
palette: {
mode: 'dark',
primary: {
main: '#3f51b5',
},
background: {
default: '#121212',
paper: '#1e1e1e',
},
},
});
function App() {
return (
<ThemeProvider theme={darkTheme}>
<CssBaseline /> {/* Normaliza el CSS para que se vea bien en todos los navegadores */}
<Box sx={{ padding: 3 }}>
<h1>Titulares Dashboard</h1>
{/* Aquí irán los demás componentes como el formulario de configuración */}
<TablaTitulares />
</Box>
</ThemeProvider>
);
}
export default App;

View File

@@ -0,0 +1,119 @@
// frontend/src/components/TablaTitulares.tsx
import { useEffect, useState } from 'react';
import {
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Chip, IconButton
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { DndContext, closestCenter, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { Titular } from '../types';
import * as api from '../services/apiService';
// Componente para una fila de tabla "arrastrable"
const SortableRow = ({ titular }: { titular: Titular }) => {
const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: titular.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
const getChipColor = (tipo: Titular['tipo']) => {
if (tipo === 'Edited') return 'warning';
if (tipo === 'Manual') return 'info';
return 'success';
};
return (
<TableRow ref={setNodeRef} style={style} {...attributes} {...listeners}>
<TableCell>...</TableCell> {/* Handle para arrastrar */}
<TableCell>{titular.texto}</TableCell>
<TableCell>
<Chip label={titular.tipo || 'Scraped'} color={getChipColor(titular.tipo)} size="small" />
</TableCell>
<TableCell>{titular.fuente}</TableCell>
<TableCell>
<IconButton size="small" onClick={() => console.log('Eliminar:', titular.id)}>
<DeleteIcon />
</IconButton>
</TableCell>
</TableRow>
);
};
// Componente principal de la tabla
const TablaTitulares = () => {
const [titulares, setTitulares] = useState<Titular[]>([]);
// Sensores para dnd-kit: reaccionar a clics de puntero
const sensors = useSensors(useSensor(PointerSensor));
const cargarTitulares = async () => {
try {
const data = await api.obtenerTitulares();
setTitulares(data);
} catch (error) {
console.error("Error al cargar titulares:", error);
}
};
useEffect(() => {
cargarTitulares();
}, []);
const handleDragEnd = (event: any) => {
const { active, over } = event;
if (active.id !== over.id) {
setTitulares((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over.id);
const newArray = arrayMove(items, oldIndex, newIndex);
// Creamos el payload para la API
const payload = newArray.map((item, index) => ({
id: item.id,
nuevoOrden: index
}));
// Llamada a la API en segundo plano
api.actualizarOrdenTitulares(payload).catch(err => {
console.error("Error al reordenar:", err);
// Opcional: revertir el estado si la API falla
});
return newArray;
});
}
};
return (
<TableContainer component={Paper}>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={titulares.map(t => t.id)} strategy={verticalListSortingStrategy}>
<Table>
<TableHead>
<TableRow>
<TableCell style={{ width: 50 }}></TableCell> {/* Celda para el drag handle */}
<TableCell>Texto del Titular</TableCell>
<TableCell>Tipo</TableCell>
<TableCell>Fuente</TableCell>
<TableCell>Acciones</TableCell>
</TableRow>
</TableHead>
<TableBody>
{titulares.map((titular) => (
<SortableRow key={titular.id} titular={titular} />
))}
</TableBody>
</Table>
</SortableContext>
</DndContext>
</TableContainer>
);
};
export default TablaTitulares;

0
frontend/src/index.css Normal file
View File

12
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,12 @@
// frontend/src/main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css' // Puedes borrar el contenido de este archivo si quieres
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)

View File

@@ -0,0 +1,33 @@
// frontend/src/services/apiService.ts
import axios from 'axios';
import type { Titular } from '../types';
// La URL base de nuestra API. Ajusta el puerto si es diferente.
const API_URL = 'https://localhost:5174/api';
const apiClient = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
});
export const obtenerTitulares = async (): Promise<Titular[]> => {
const response = await apiClient.get('/titulares');
return response.data;
};
export const eliminarTitular = async (id: number): Promise<void> => {
await apiClient.delete(`/titulares/${id}`);
};
// DTO para el reordenamiento
interface ReordenarPayload {
id: number;
nuevoOrden: number;
}
export const actualizarOrdenTitulares = async (payload: ReordenarPayload[]): Promise<void> => {
await apiClient.put('/titulares/reordenar', payload);
};

13
frontend/src/types.ts Normal file
View File

@@ -0,0 +1,13 @@
// frontend/src/types.ts
export interface Titular {
id: number;
texto: string;
urlFuente: string | null;
modificadoPorUsuario: boolean;
esEntradaManual: boolean;
ordenVisual: number;
fechaCreacion: string;
tipo: 'Scraped' | 'Edited' | 'Manual' | null;
fuente: string | null;
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

7
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})