Proyecto ChatBot Con Gemini
This commit is contained in:
0
chatbot-widget/src/App.css
Normal file
0
chatbot-widget/src/App.css
Normal file
17
chatbot-widget/src/App.tsx
Normal file
17
chatbot-widget/src/App.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import Chatbot from './components/Chatbot';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="App">
|
||||
{/* El contenido de la página web iría aquí */}
|
||||
<h1>Página de ejemplo de El Día</h1>
|
||||
<p>Este es un contenido de demostración para el sitio.</p>
|
||||
|
||||
{/* Aquí integramos nuestro widget de chatbot */}
|
||||
<Chatbot />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
140
chatbot-widget/src/components/Chatbot.css
Normal file
140
chatbot-widget/src/components/Chatbot.css
Normal file
@@ -0,0 +1,140 @@
|
||||
/* Estilos para la burbuja flotante del chat */
|
||||
.chat-bubble {
|
||||
position: fixed;
|
||||
bottom: 25px;
|
||||
right: 25px;
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 28px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
|
||||
transition: transform 0.2s ease-in-out;
|
||||
}
|
||||
|
||||
.chat-bubble:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
/* Estilos para la ventana del chat */
|
||||
.chat-window {
|
||||
position: fixed;
|
||||
bottom: 100px;
|
||||
right: 25px;
|
||||
width: 350px;
|
||||
height: 500px;
|
||||
background-color: white;
|
||||
border-radius: 15px;
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
transition: opacity 0.3s, transform 0.3s;
|
||||
}
|
||||
|
||||
/* Estilos para el encabezado del chat */
|
||||
.chat-header {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
padding: 15px;
|
||||
font-weight: bold;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.chat-header .close-button {
|
||||
background: none;
|
||||
border: none;
|
||||
color: white;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
.chat-header .close-button:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
/* Contenedor de mensajes */
|
||||
.messages-container {
|
||||
flex-grow: 1;
|
||||
padding: 15px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: #f4f4f4;
|
||||
}
|
||||
|
||||
/* Estilos individuales de los mensajes */
|
||||
.message {
|
||||
padding: 10px 15px;
|
||||
border-radius: 20px;
|
||||
margin-bottom: 10px;
|
||||
max-width: 80%;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.message.user {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.message.bot {
|
||||
background-color: #e9e9eb;
|
||||
color: #333;
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
/* Formulario de entrada de texto */
|
||||
.input-form {
|
||||
display: flex;
|
||||
padding: 10px;
|
||||
border-top: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.input-form input {
|
||||
flex-grow: 1;
|
||||
border: 1px solid #ddd;
|
||||
padding: 10px;
|
||||
border-radius: 20px;
|
||||
margin-right: 10px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.input-form button {
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
font-size: 18px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.input-container {
|
||||
position: relative;
|
||||
flex-grow: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.input-container input {
|
||||
padding-right: 8px; /* Espacio para que no se solape con el botón */
|
||||
width: calc(100% - 28px); /* Ajuste del ancho del input */
|
||||
}
|
||||
|
||||
.char-counter {
|
||||
font-size: 0.75rem;
|
||||
color: #888;
|
||||
text-align: right;
|
||||
margin-top: 4px;
|
||||
margin-right: 15px;
|
||||
}
|
||||
203
chatbot-widget/src/components/Chatbot.tsx
Normal file
203
chatbot-widget/src/components/Chatbot.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
// src/components/Chatbot.tsx
|
||||
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import rehypeSanitize from 'rehype-sanitize';
|
||||
import './Chatbot.css';
|
||||
|
||||
interface Message {
|
||||
text: string;
|
||||
sender: 'user' | 'bot';
|
||||
}
|
||||
|
||||
const MAX_CHARS = 200;
|
||||
// Constante para la clave del localStorage
|
||||
const CHAT_HISTORY_KEY = 'chatbot-history';
|
||||
|
||||
const Chatbot: React.FC = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [messages, setMessages] = useState<Message[]>(() => {
|
||||
try {
|
||||
// 1. Intentamos obtener el historial guardado.
|
||||
const savedHistory = localStorage.getItem(CHAT_HISTORY_KEY);
|
||||
if (savedHistory) {
|
||||
// 2. Si existe, lo parseamos y lo devolvemos para usarlo como estado inicial.
|
||||
return JSON.parse(savedHistory);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("No se pudo cargar el historial del chat desde localStorage:", error);
|
||||
}
|
||||
// 3. Si no hay nada guardado o hay un error, devolvemos el estado por defecto.
|
||||
return [{ text: '¡Hola! Soy tu asistente virtual. ¿En qué puedo ayudarte hoy?', sender: 'bot' }];
|
||||
});
|
||||
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const messagesEndRef = useRef<null | HTMLDivElement>(null);
|
||||
|
||||
// Añadimos un useEffect para guardar los mensajes.
|
||||
useEffect(() => {
|
||||
try {
|
||||
// Cada vez que el array de 'messages' cambie, lo guardamos en localStorage.
|
||||
localStorage.setItem(CHAT_HISTORY_KEY, JSON.stringify(messages));
|
||||
} catch (error) {
|
||||
console.error("No se pudo guardar el historial del chat en localStorage:", error);
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
// Solo intentamos hacer scroll si la ventana del chat está abierta.
|
||||
if (isOpen) {
|
||||
// Usamos un pequeño retardo para asegurar que el navegador haya renderizado
|
||||
// completamente la ventana antes de intentar hacer el scroll.
|
||||
// Esto previene problemas si hay animaciones CSS.
|
||||
setTimeout(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, 50);
|
||||
}
|
||||
}, [messages, isOpen]);
|
||||
|
||||
const toggleChat = () => setIsOpen(!isOpen);
|
||||
|
||||
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setInputValue(event.target.value);
|
||||
};
|
||||
|
||||
const handleSendMessage = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
if (inputValue.trim() === '' || isLoading) return;
|
||||
|
||||
const userMessage: Message = { text: inputValue, sender: 'user' };
|
||||
setMessages(prev => [...prev, userMessage]);
|
||||
const messageToSend = inputValue;
|
||||
setInputValue('');
|
||||
setIsLoading(true);
|
||||
|
||||
const botMessagePlaceholder: Message = { text: '', sender: 'bot' };
|
||||
setMessages(prev => [...prev, botMessagePlaceholder]);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/chat/stream-message`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: messageToSend }),
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error('Error en la respuesta del servidor.');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let accumulatedResponse = ''; // Variable para acumular el texto crudo
|
||||
|
||||
const readStream = async () => {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
// El stream ha terminado, no hacemos nada más aquí.
|
||||
break;
|
||||
}
|
||||
|
||||
// Acumulamos la respuesta cruda que viene del backend
|
||||
accumulatedResponse += decoder.decode(value);
|
||||
|
||||
try {
|
||||
// Intentamos limpiar la respuesta acumulada
|
||||
// 1. Parseamos como si fuera un array JSON
|
||||
const parsedArray = JSON.parse(accumulatedResponse
|
||||
// Añadimos un corchete de cierre por si el stream se corta a la mitad
|
||||
.replace(/,$/, '') + ']');
|
||||
|
||||
// 2. Unimos los fragmentos del array en un solo texto
|
||||
const cleanText = Array.isArray(parsedArray) ? parsedArray.join('') : accumulatedResponse;
|
||||
|
||||
// 3. Actualizamos el estado con el texto limpio
|
||||
setMessages(prev => {
|
||||
const lastMessage = prev[prev.length - 1];
|
||||
const updatedLastMessage = { ...lastMessage, text: cleanText };
|
||||
return [...prev.slice(0, -1), updatedLastMessage];
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
// Si hay un error de parseo (porque el JSON aún no está completo),
|
||||
// mostramos el texto sin los caracteres iniciales/finales.
|
||||
const partiallyCleanedText = accumulatedResponse
|
||||
.replace(/^\[?"|"?,"?|"?\]$/g, '')
|
||||
.replace(/","/g, '');
|
||||
|
||||
setMessages(prev => {
|
||||
const lastMessage = prev[prev.length - 1];
|
||||
const updatedLastMessage = { ...lastMessage, text: partiallyCleanedText };
|
||||
return [...prev.slice(0, -1), updatedLastMessage];
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await readStream();
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error al conectar con la API de streaming:", error);
|
||||
const errorText = error instanceof Error ? error.message : 'Lo siento, no pude conectarme.';
|
||||
|
||||
setMessages(prev => {
|
||||
const lastMessage = prev[prev.length - 1];
|
||||
const updatedLastMessage = { ...lastMessage, text: errorText };
|
||||
return [...prev.slice(0, -1), updatedLastMessage];
|
||||
});
|
||||
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="chat-bubble" onClick={toggleChat}>
|
||||
<span>{isOpen ? 'X' : '💬'}</span>
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<div className="chat-window">
|
||||
<div className="chat-header">
|
||||
<span>Asistente Virtual - El Día</span>
|
||||
<button className="close-button" onClick={toggleChat}>×</button>
|
||||
</div>
|
||||
<div className="messages-container">
|
||||
{messages.map((msg, index) => (
|
||||
<div key={index} className={`message ${msg.sender}`}>
|
||||
<ReactMarkdown rehypePlugins={[rehypeSanitize]}>
|
||||
{msg.text.replace(/\\n/g, "\n")}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
<form className="input-form" onSubmit={handleSendMessage}>
|
||||
<div className="input-container">
|
||||
<input
|
||||
type="text"
|
||||
placeholder={isLoading ? "Esperando respuesta..." : "Escribe tu consulta..."}
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
disabled={isLoading}
|
||||
maxLength={MAX_CHARS}
|
||||
/>
|
||||
<div className="char-counter">
|
||||
{inputValue.length} / {MAX_CHARS}
|
||||
</div>
|
||||
</div>
|
||||
<button type="submit" disabled={isLoading}>
|
||||
{isLoading ? '...' : '→'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Chatbot;
|
||||
0
chatbot-widget/src/index.css
Normal file
0
chatbot-widget/src/index.css
Normal file
10
chatbot-widget/src/main.tsx
Normal file
10
chatbot-widget/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
Reference in New Issue
Block a user