Feat: Ajustes y Preparación Docker
This commit is contained in:
25
chatbot-widget/Dockerfile.widget
Normal file
25
chatbot-widget/Dockerfile.widget
Normal file
@@ -0,0 +1,25 @@
|
||||
# Dockerfile.widget
|
||||
|
||||
# ---- Etapa de Compilación (Build) ----
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
|
||||
COPY . .
|
||||
# IMPORTANTE: Aquí definimos la URL de la API para producción
|
||||
# El docker-compose se encargará de exponer la API en el puerto 8080 del host
|
||||
RUN VITE_API_BASE_URL=http://192.168.5.129:8080 npm run build
|
||||
|
||||
# ---- Etapa Final (Runtime) ----
|
||||
FROM nginx:alpine AS final
|
||||
|
||||
# Copiamos los archivos estáticos construidos en la etapa anterior
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
# Copiamos nuestra configuración personalizada de Nginx
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
15
chatbot-widget/nginx.conf
Normal file
15
chatbot-widget/nginx.conf
Normal file
@@ -0,0 +1,15 @@
|
||||
# nginx.conf
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location / {
|
||||
# Si un archivo o directorio no existe, redirige al index.html
|
||||
# Esto es esencial para que el enrutamiento del lado del cliente de React funcione.
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -150,4 +150,40 @@ opacity: 0.8;
|
||||
|
||||
.context-indicator span {
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- INICIO DE LA ANIMACIÓN DE "ESCRIBIENDO" --- */
|
||||
|
||||
.typing-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 2px 0; /* Espacio vertical para que no se pegue a los bordes */
|
||||
}
|
||||
|
||||
.typing-indicator span {
|
||||
height: 8px;
|
||||
width: 8px;
|
||||
background-color: #999;
|
||||
border-radius: 50%;
|
||||
display: inline-block;
|
||||
margin: 0 2px;
|
||||
animation: typing-bounce 1.4s infinite;
|
||||
}
|
||||
|
||||
/* Aplicamos un pequeño retardo a cada punto para crear el efecto de onda */
|
||||
.typing-indicator span:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.typing-indicator span:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes typing-bounce {
|
||||
0%, 80%, 100% {
|
||||
transform: scale(0);
|
||||
}
|
||||
40% {
|
||||
transform: scale(0.75);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@ interface Message {
|
||||
}
|
||||
|
||||
const MAX_CHARS = 200;
|
||||
// Constante para la clave del localStorage
|
||||
// Constantes para la clave del localStorage
|
||||
const CHAT_HISTORY_KEY = 'chatbot-history';
|
||||
const CHAT_CONTEXT_KEY = 'chatbot-active-article';
|
||||
|
||||
const Chatbot: React.FC = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
@@ -33,8 +34,22 @@ const Chatbot: React.FC = () => {
|
||||
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isStreaming, setIsStreaming] = useState(false);
|
||||
const messagesEndRef = useRef<null | HTMLDivElement>(null);
|
||||
const [activeArticleUrl, setActiveArticleUrl] = useState<string | null>(null);
|
||||
const [activeArticle, setActiveArticle] = useState<{ url: string; title: string; } | null>(() => {
|
||||
try {
|
||||
// 1. Intentamos obtener el contexto del artículo guardado.
|
||||
const savedContext = localStorage.getItem(CHAT_CONTEXT_KEY);
|
||||
if (savedContext) {
|
||||
// 2. Si existe, lo parseamos y lo usamos como estado inicial.
|
||||
return JSON.parse(savedContext);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("No se pudo cargar el contexto del artículo desde localStorage:", error);
|
||||
}
|
||||
// 3. Si no hay nada guardado o hay un error, el estado inicial es null.
|
||||
return null;
|
||||
});
|
||||
|
||||
// Añadimos un useEffect para guardar los mensajes.
|
||||
useEffect(() => {
|
||||
@@ -46,6 +61,19 @@ const Chatbot: React.FC = () => {
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (activeArticle) {
|
||||
// Si hay un artículo activo, lo guardamos en localStorage.
|
||||
localStorage.setItem(CHAT_CONTEXT_KEY, JSON.stringify(activeArticle));
|
||||
} else {
|
||||
// Si el artículo activo es null, lo eliminamos de localStorage para mantenerlo limpio.
|
||||
localStorage.removeItem(CHAT_CONTEXT_KEY);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("No se pudo guardar el contexto del artículo en localStorage:", error);
|
||||
}
|
||||
}, [activeArticle]); // Wste efecto se ejecuta cada vez que 'activeArticle' cambia.
|
||||
|
||||
useEffect(() => {
|
||||
// Solo intentamos hacer scroll si la ventana del chat está abierta.
|
||||
@@ -73,15 +101,15 @@ const Chatbot: React.FC = () => {
|
||||
setMessages(prev => [...prev, userMessage]);
|
||||
const messageToSend = inputValue;
|
||||
setInputValue('');
|
||||
setIsLoading(true);
|
||||
|
||||
const botMessagePlaceholder: Message = { text: '', sender: 'bot' };
|
||||
setMessages(prev => [...prev, botMessagePlaceholder]);
|
||||
// Inicia el estado de carga, pero aún no el de streaming
|
||||
setIsLoading(true);
|
||||
setIsStreaming(false);
|
||||
|
||||
try {
|
||||
const requestBody = {
|
||||
message: messageToSend,
|
||||
contextUrl: activeArticleUrl
|
||||
contextUrl: activeArticle ? activeArticle.url : null
|
||||
};
|
||||
|
||||
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/chat/stream-message`, {
|
||||
@@ -98,52 +126,67 @@ const Chatbot: React.FC = () => {
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
const readStream = async () => {
|
||||
let fullReply = '';
|
||||
let fullReplyRaw = '';
|
||||
let isFirstChunk = true;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
let finalCleanText = '';
|
||||
// ... (La lógica de `if (done)` no cambia)
|
||||
try {
|
||||
const parsedArray = JSON.parse(fullReply.replace(/,$/, '') + ']');
|
||||
finalCleanText = Array.isArray(parsedArray) ? parsedArray.join('') : fullReply;
|
||||
const responseArray = JSON.parse(fullReplyRaw);
|
||||
let intent = 'Homepage';
|
||||
let messageChunks = [];
|
||||
if (Array.isArray(responseArray) && responseArray.length > 0) {
|
||||
if (typeof responseArray[0] === 'string' && responseArray[0].startsWith('INTENT::')) {
|
||||
intent = responseArray[0].split('::')[1];
|
||||
messageChunks = responseArray.slice(1);
|
||||
} else {
|
||||
messageChunks = responseArray;
|
||||
}
|
||||
}
|
||||
const finalCleanText = messageChunks.join('');
|
||||
const linkRegex = /\[(.*?)\]\((https?:\/\/[^\s]+)\)/;
|
||||
const match = finalCleanText.match(linkRegex);
|
||||
if (match && match[1] && match[2]) {
|
||||
setActiveArticle({ title: match[1], url: match[2] });
|
||||
} else if (intent === 'Database' || intent === 'Homepage') {
|
||||
setActiveArticle(null);
|
||||
}
|
||||
} catch (e) {
|
||||
finalCleanText = fullReply.replace(/^\["|"]$|","/g, '');
|
||||
console.error("Error al procesar la respuesta final del stream:", e, "Contenido crudo:", fullReplyRaw);
|
||||
setActiveArticle(null);
|
||||
}
|
||||
|
||||
const linkRegex = /\[.*?\]\((https?:\/\/[^\s]+)\)/;
|
||||
const match = finalCleanText.match(linkRegex);
|
||||
|
||||
// --- INICIO DE LA CORRECCIÓN ---
|
||||
// Si encontramos un nuevo enlace, actualizamos el contexto.
|
||||
// Si NO encontramos un enlace, ya no hacemos nada, permitiendo que el contexto anterior persista.
|
||||
if (match && match[1]) {
|
||||
console.log("Noticia activa establecida:", match[1]);
|
||||
setActiveArticleUrl(match[1]);
|
||||
}
|
||||
// HEMOS ELIMINADO EL BLOQUE "ELSE" QUE RESETEABA EL CONTEXTO.
|
||||
// --- FIN DE LA CORRECCIÓN ---
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// ... (el resto del bucle while sigue exactamente igual)
|
||||
const chunk = decoder.decode(value);
|
||||
fullReply += chunk;
|
||||
fullReplyRaw += chunk;
|
||||
|
||||
let cleanText = '';
|
||||
let cleanTextForDisplay = '';
|
||||
try {
|
||||
const parsedArray = JSON.parse(fullReply.replace(/,$/, '') + ']');
|
||||
cleanText = Array.isArray(parsedArray) ? parsedArray.join('') : fullReply;
|
||||
const parsedArray = JSON.parse(fullReplyRaw.replace(/,$/, '') + ']');
|
||||
const displayChunks = parsedArray[0] && parsedArray[0].startsWith('INTENT::')
|
||||
? parsedArray.slice(1)
|
||||
: parsedArray;
|
||||
cleanTextForDisplay = displayChunks.join('');
|
||||
} catch (e) {
|
||||
cleanText = fullReply.replace(/^\["|"]$|","/g, '');
|
||||
cleanTextForDisplay = fullReplyRaw.replace(/^\["INTENT::.*?","|\["|"]$|","/g, '');
|
||||
}
|
||||
|
||||
setMessages(prev => {
|
||||
const lastMessage = prev[prev.length - 1];
|
||||
const updatedLastMessage = { ...lastMessage, text: cleanText };
|
||||
return [...prev.slice(0, -1), updatedLastMessage];
|
||||
});
|
||||
if (isFirstChunk) {
|
||||
// En el primer chunk, activamos el flag de streaming
|
||||
setIsStreaming(true);
|
||||
setMessages(prev => [...prev, { text: cleanTextForDisplay, sender: 'bot' }]);
|
||||
isFirstChunk = false;
|
||||
} else {
|
||||
setMessages(prev => {
|
||||
const updatedMessages = [...prev];
|
||||
updatedMessages[updatedMessages.length - 1].text = cleanTextForDisplay;
|
||||
return updatedMessages;
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -152,15 +195,11 @@ const Chatbot: React.FC = () => {
|
||||
} 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];
|
||||
});
|
||||
|
||||
setMessages(prev => [...prev, { text: errorText, sender: 'bot' }]);
|
||||
} finally {
|
||||
// Al final, reseteamos ambos estados
|
||||
setIsLoading(false);
|
||||
setIsStreaming(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -176,7 +215,7 @@ const Chatbot: React.FC = () => {
|
||||
<span>Asistente Virtual - El Día</span>
|
||||
<button className="close-button" onClick={toggleChat}>×</button>
|
||||
</div>
|
||||
<div className="messages-container">
|
||||
<div className={`messages-container ${isLoading ? 'is-loading' : ''}`}>
|
||||
{messages.map((msg, index) => (
|
||||
<div key={index} className={`message ${msg.sender}`}>
|
||||
<ReactMarkdown rehypePlugins={[rehypeSanitize]}>
|
||||
@@ -184,11 +223,23 @@ const Chatbot: React.FC = () => {
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
))}
|
||||
{isLoading && !isStreaming && (
|
||||
<div className="message bot">
|
||||
<div className="typing-indicator">
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
{activeArticleUrl && (
|
||||
{activeArticle && (
|
||||
<div className="context-indicator">
|
||||
Hablando sobre: <span>Noticia actual</span>
|
||||
Hablando sobre:
|
||||
<a href={activeArticle.url} target="_blank" rel="noopener noreferrer">
|
||||
{activeArticle.title}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
<form className="input-form" onSubmit={handleSendMessage}>
|
||||
|
||||
Reference in New Issue
Block a user