feat(ai): redesign mobile chat widget with Mercado Libre bottom-sheet UX and keyboard docking (v3.8.36)
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
/**
|
||||
* ai-chat-widget.js - Lógica interactiva de UdeCi (SDD-010)
|
||||
* Asistente y Tutor Virtual de UniCABA con soporte RAG,
|
||||
* respuestas concisas y botones de opciones interactivas.
|
||||
* ai-chat-widget.js - Tutor Virtual UdeCi (UniCABA)
|
||||
* Experiencia de usuario y diseño tipo Bottom Sheet móvil estilo Mercado Libre.
|
||||
* Incluye soporte RAG, input dock inteligente, manejo de teclado virtual,
|
||||
* chips de rol, copia de mensajes y síntesis de voz en español.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
let isProcessing = false;
|
||||
let touchStartY = 0;
|
||||
let touchDeltaY = 0;
|
||||
|
||||
// Limpiar clave histórica compartida para evitar contaminación entre perfiles
|
||||
// Limpiar claves obsoletas
|
||||
try {
|
||||
sessionStorage.removeItem('edu_space_udeci_chat_history_v2');
|
||||
localStorage.removeItem('edu_space_udeci_chat_history_v2');
|
||||
@@ -24,7 +27,6 @@
|
||||
if (rawId && rawId.toString().trim()) {
|
||||
return 'usr_' + rawId.toString().trim().replace(/[^a-zA-Z0-9_-]/g, '_');
|
||||
}
|
||||
// Identificador único de sesión por pestaña si no está logueado
|
||||
let anonId = sessionStorage.getItem('edu_space_anon_chat_session');
|
||||
if (!anonId) {
|
||||
anonId = 'anon_' + Math.random().toString(36).substring(2, 10) + '_' + Date.now();
|
||||
@@ -38,17 +40,23 @@
|
||||
}
|
||||
|
||||
const ROLE_CHIPS = {
|
||||
docente: [
|
||||
{ label: "📝 Notas de Alumnos", query: "¿Cuáles son las notas y calificaciones de mis alumnos?" },
|
||||
{ label: "📅 Hitos y Exámenes", query: "¿Cuáles son los hitos evaluativos y fechas de examen programadas?" },
|
||||
{ label: "📍 Mis Comisiones", query: "¿Cuáles son mis comisiones a cargo y aulas asignadas?" }
|
||||
admin: [
|
||||
{ label: "📊 Métricas del Sistema", query: "¿Cuáles son las estadísticas y métricas generales del sistema?" },
|
||||
{ label: "⚙️ Configuración Global", query: "¿Cómo configuro el servidor LLM y los parámetros de IA?" },
|
||||
{ label: "🛡️ Roles y Usuarios", query: "¿Cómo administro los usuarios y roles RBAC?" },
|
||||
{ label: "📍 Ocupación de Sedes", query: "¿Cuál es el estado de ocupación de las sedes y aulas?" }
|
||||
],
|
||||
bedelia: [
|
||||
{ label: "🔄 Flujo 9 Pasos", query: "¿Cuáles son los 9 pasos del flujo de Bedelía?" },
|
||||
{ label: "⚠️ Conflictos Áulicos", query: "¿Cómo funciona la matriz de conflictos y aforo?" },
|
||||
{ label: "🧬 Optimizador IA", query: "¿Cómo uso el optimizador de aulas?" },
|
||||
{ label: "🧬 Optimizador IA", query: "¿Cómo uso el optimizador genético de aulas?" },
|
||||
{ label: "📑 Importar Sheets", query: "¿Cómo uso el importador de Google Sheets?" }
|
||||
],
|
||||
docente: [
|
||||
{ label: "📝 Notas de Alumnos", query: "¿Cuáles son las notas y calificaciones de mis alumnos?" },
|
||||
{ label: "📅 Hitos y Exámenes", query: "¿Cuáles son los hitos evaluativos y fechas de examen programadas?" },
|
||||
{ label: "📍 Mis Comisiones", query: "¿Cuáles son mis comisiones a cargo y aulas asignadas?" }
|
||||
],
|
||||
alumno: [
|
||||
{ label: "📍 Próxima Presencial", query: "¿Cuándo y dónde es mi próxima clase presencial?" },
|
||||
{ label: "📊 Mis Notas", query: "¿Cuáles son mis notas, calificaciones y regularidad en mis materias?" },
|
||||
@@ -82,15 +90,15 @@
|
||||
}
|
||||
|
||||
function getWelcomeMessage(role, name) {
|
||||
const greeting = name ? `¡Hola, **${name}**! 👋` : '¡Hola! 👋';
|
||||
const greeting = name ? `¡Hola, ${name}!` : '¡Hola!';
|
||||
if (role === 'admin') {
|
||||
return `${greeting} Soy **UdeCi**, tu tutor de Edu-Space para Administración y Gobierno del Sistema. ¿Qué deseas gestionar o configurar hoy?`;
|
||||
return `${greeting} Soy **UdeCi**, tu tutor de Edu-Space para Administración y Gobierno del Sistema. ¿En qué te puedo ayudar hoy?`;
|
||||
} else if (role === 'bedelia') {
|
||||
return `${greeting} Soy **UdeCi**, tu asistente de soporte técnico para Bedelía. Puedo guiarte en el circuito de 9 pasos, resolución de conflictos y Moodle.`;
|
||||
return `${greeting} Soy **UdeCi**, tu asistente de soporte para Bedelía. Puedo orientarte en el circuito de 9 pasos, resolución de conflictos y reservas.`;
|
||||
} else if (role === 'docente') {
|
||||
return `${greeting} Soy **UdeCi**, tu tutor de Edu-Space para docentes. Puedo orientarte sobre asignaciones de aulas, el Gradebook y tus clases asignadas.`;
|
||||
return `${greeting} Soy **UdeCi**, tu tutor docente. Puedo orientarte sobre asignaciones de aulas, comisiones y el Libro de Calificaciones.`;
|
||||
} else {
|
||||
return `${greeting} Soy **UdeCi**, tu tutor virtual de cursada. Puedo orientarte sobre en qué aula cursas hoy, horarios y notas.`;
|
||||
return `${greeting} Soy **UdeCi**, tu tutor virtual de cursada. Puedo orientarte sobre aulas, horarios y notas. ¿En qué te puedo ayudar?`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +120,7 @@
|
||||
function renderMarkdown(text) {
|
||||
if (!text) return '';
|
||||
|
||||
// 1. Proteger enlaces Markdown [texto](url) antes del escape HTML
|
||||
// Proteger enlaces Markdown [texto](url)
|
||||
const links = [];
|
||||
let processed = text.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (match, label, url) => {
|
||||
const idx = links.length;
|
||||
@@ -120,7 +128,7 @@
|
||||
return `__MD_LINK_${idx}__`;
|
||||
});
|
||||
|
||||
// 2. Proteger URLs directas https://...
|
||||
// Proteger URLs directas https://...
|
||||
const rawUrls = [];
|
||||
processed = processed.replace(/(https?:\/\/[^\s<"'>)]+)/g, (match, url) => {
|
||||
const idx = rawUrls.length;
|
||||
@@ -128,40 +136,45 @@
|
||||
return `__RAW_URL_${idx}__`;
|
||||
});
|
||||
|
||||
// 3. Escaping HTML seguro
|
||||
// Escaping seguro de HTML
|
||||
let escaped = processed
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>');
|
||||
|
||||
// 4. Negrita **texto**
|
||||
// Negrita **texto**
|
||||
escaped = escaped.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
|
||||
// 5. Cursiva *texto*
|
||||
// Cursiva *texto*
|
||||
escaped = escaped.replace(/\*(.*?)\*/g, '<em>$1</em>');
|
||||
// 6. Código inline `codigo`
|
||||
// Código inline `codigo`
|
||||
escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
// 7. Saltos de línea
|
||||
// Saltos de línea
|
||||
escaped = escaped.replace(/\n/g, '<br>');
|
||||
|
||||
// 8. Restaurar enlaces Markdown como botones/hipervínculos atractivos
|
||||
// Restaurar enlaces Markdown como botones atractivos
|
||||
escaped = escaped.replace(/__MD_LINK_(\d+)__/g, (match, idx) => {
|
||||
const item = links[parseInt(idx, 10)];
|
||||
if (!item) return '';
|
||||
return `<a href="${item.url}" target="_blank" rel="noopener noreferrer" class="ai-chat-link"><i class="bi bi-box-arrow-up-right me-1"></i>${item.label}</a>`;
|
||||
});
|
||||
|
||||
// 9. Restaurar URLs directas como enlaces clickeables
|
||||
// Restaurar URLs directas como enlaces clickeables
|
||||
escaped = escaped.replace(/__RAW_URL_(\d+)__/g, (match, idx) => {
|
||||
const url = rawUrls[parseInt(idx, 10)];
|
||||
if (!url) return '';
|
||||
const displayUrl = url.length > 48 ? url.substring(0, 45) + '...' : url;
|
||||
const displayUrl = url.length > 46 ? url.substring(0, 43) + '...' : url;
|
||||
return `<a href="${url}" target="_blank" rel="noopener noreferrer" class="ai-chat-link"><i class="bi bi-link-45deg me-1"></i>${displayUrl}</a>`;
|
||||
});
|
||||
|
||||
return escaped;
|
||||
}
|
||||
|
||||
function appendMessage(role, content, options = [], save = true) {
|
||||
function formatCurrentTime() {
|
||||
const now = new Date();
|
||||
return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function appendMessage(role, content, options = [], save = true, timeStr = null) {
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (!messagesContainer) return;
|
||||
|
||||
@@ -169,23 +182,99 @@
|
||||
const msgDiv = document.createElement('div');
|
||||
msgDiv.className = `ai-msg ${isUser ? 'ai-msg-user' : 'ai-msg-assistant'}`;
|
||||
|
||||
let html = renderMarkdown(content);
|
||||
const formattedHtml = renderMarkdown(content);
|
||||
const timestamp = timeStr || formatCurrentTime();
|
||||
|
||||
// Si es mensaje del asistente y tiene opciones, renderizar botones interactivos
|
||||
if (!isUser && options && options.length > 0) {
|
||||
html += '<div class="ai-msg-options">';
|
||||
options.forEach(opt => {
|
||||
const cleanOpt = opt.replace(/^[📍📝👥🔄⚠️🧬📑📚📊❓]\s*/, '').trim();
|
||||
html += `<button type="button" class="ai-option-btn" data-query="${opt}">${opt}</button>`;
|
||||
});
|
||||
html += '</div>';
|
||||
if (isUser) {
|
||||
msgDiv.innerHTML = `
|
||||
<div class="ai-msg-text">${formattedHtml}</div>
|
||||
<span class="ai-msg-time">${timestamp}</span>
|
||||
`;
|
||||
} else {
|
||||
let optionsHtml = '';
|
||||
if (options && options.length > 0) {
|
||||
optionsHtml = '<div class="ai-msg-options">';
|
||||
options.forEach(opt => {
|
||||
optionsHtml += `<button type="button" class="ai-option-btn" data-query="${opt}">${opt}</button>`;
|
||||
});
|
||||
optionsHtml += '</div>';
|
||||
}
|
||||
|
||||
msgDiv.innerHTML = `
|
||||
<div class="ai-msg-body">${formattedHtml}</div>
|
||||
${optionsHtml}
|
||||
<div class="ai-msg-actions">
|
||||
<button type="button" class="ai-action-icon-btn copy-btn" title="Copiar respuesta" aria-label="Copiar">
|
||||
<i class="bi bi-copy"></i>
|
||||
</button>
|
||||
<button type="button" class="ai-action-icon-btn speak-btn" title="Escuchar en voz alta" aria-label="Escuchar">
|
||||
<i class="bi bi-volume-up"></i>
|
||||
</button>
|
||||
<button type="button" class="ai-action-icon-btn thumbs-up-btn" title="Respuesta útil" aria-label="Útil">
|
||||
<i class="bi bi-hand-thumbs-up"></i>
|
||||
</button>
|
||||
<button type="button" class="ai-action-icon-btn thumbs-down-btn" title="No me sirvió" aria-label="No útil">
|
||||
<i class="bi bi-hand-thumbs-down"></i>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Configurar botones de acción interactivos estilo Mercado Libre
|
||||
const copyBtn = msgDiv.querySelector('.copy-btn');
|
||||
if (copyBtn) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
const temp = document.createElement('div');
|
||||
temp.innerHTML = formattedHtml;
|
||||
const plain = temp.textContent || temp.innerText || '';
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(plain).then(() => {
|
||||
copyBtn.innerHTML = '<i class="bi bi-check-lg text-success"></i>';
|
||||
setTimeout(() => { copyBtn.innerHTML = '<i class="bi bi-copy"></i>'; }, 2000);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const speakBtn = msgDiv.querySelector('.speak-btn');
|
||||
if (speakBtn) {
|
||||
speakBtn.addEventListener('click', () => {
|
||||
if ('speechSynthesis' in window) {
|
||||
if (window.speechSynthesis.speaking) {
|
||||
window.speechSynthesis.cancel();
|
||||
speakBtn.classList.remove('active');
|
||||
return;
|
||||
}
|
||||
const temp = document.createElement('div');
|
||||
temp.innerHTML = formattedHtml;
|
||||
const plain = temp.textContent || temp.innerText || '';
|
||||
const utter = new SpeechSynthesisUtterance(plain);
|
||||
utter.lang = 'es-AR';
|
||||
speakBtn.classList.add('active');
|
||||
utter.onend = () => speakBtn.classList.remove('active');
|
||||
utter.onerror = () => speakBtn.classList.remove('active');
|
||||
window.speechSynthesis.speak(utter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const thumbsUp = msgDiv.querySelector('.thumbs-up-btn');
|
||||
const thumbsDown = msgDiv.querySelector('.thumbs-down-btn');
|
||||
if (thumbsUp && thumbsDown) {
|
||||
thumbsUp.addEventListener('click', () => {
|
||||
thumbsUp.classList.toggle('active');
|
||||
thumbsDown.classList.remove('active');
|
||||
});
|
||||
thumbsDown.addEventListener('click', () => {
|
||||
thumbsDown.classList.toggle('active');
|
||||
thumbsUp.classList.remove('active');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
msgDiv.innerHTML = html;
|
||||
messagesContainer.appendChild(msgDiv);
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
|
||||
// Asignar listeners a los botones de opciones dentro de la burbuja
|
||||
// Asignar listeners a los chips de opciones
|
||||
msgDiv.querySelectorAll('.ai-option-btn').forEach(btn => {
|
||||
btn.addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
@@ -196,7 +285,7 @@
|
||||
|
||||
if (save) {
|
||||
const history = loadHistory();
|
||||
history.push({ role, content, options });
|
||||
history.push({ role, content, options, timeStr: timestamp });
|
||||
saveHistory(history);
|
||||
}
|
||||
}
|
||||
@@ -207,8 +296,11 @@
|
||||
const textarea = document.getElementById('aiChatInput');
|
||||
const typing = document.getElementById('aiChatTyping');
|
||||
const sendBtn = document.getElementById('aiChatSendBtn');
|
||||
const chipsDrawer = document.getElementById('aiChatQuickChips');
|
||||
|
||||
if (textarea) textarea.value = '';
|
||||
if (chipsDrawer) chipsDrawer.classList.add('d-none');
|
||||
|
||||
appendMessage('user', queryText, [], true);
|
||||
|
||||
isProcessing = true;
|
||||
@@ -240,45 +332,58 @@
|
||||
})
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok && data.response) {
|
||||
appendMessage('assistant', data.response, data.quick_options || [], true);
|
||||
|
||||
// Si UdeCi emite una directiva de guía interactiva, activar el Spotlight
|
||||
if (data.guide_step && window.WalkthroughEngine) {
|
||||
const panel = document.getElementById('aiChatPanel');
|
||||
const launcher = document.getElementById('aiChatLauncher');
|
||||
if (panel && launcher) {
|
||||
panel.classList.add('d-none');
|
||||
launcher.style.transform = '';
|
||||
launcher.classList.remove('chat-open');
|
||||
document.body.classList.remove('ai-chat-mobile-open');
|
||||
}
|
||||
setTimeout(() => {
|
||||
window.WalkthroughEngine.startStep(data.guide_step);
|
||||
}, 250);
|
||||
}
|
||||
} else {
|
||||
const errorMsg = data.detail || data.message || 'UdeCi no pudo procesar la respuesta en este momento.';
|
||||
appendMessage('assistant', `⚠️ ${errorMsg}`, [], false);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Error HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const reply = data.reply || "Disculpa, no pude procesar tu solicitud en este momento.";
|
||||
const options = Array.isArray(data.options) ? data.options : [];
|
||||
appendMessage('assistant', reply, options, true);
|
||||
} catch (err) {
|
||||
appendMessage('assistant', `⚠️ Error de comunicación: ${err.message}`, [], false);
|
||||
console.error("[UdeCi Widget] Error al consultar API:", err);
|
||||
appendMessage('assistant', "Hubo una interrupción en la conexión con el tutor inteligente. Por favor, verifica tu conexión o intenta nuevamente en unos instantes.", [], true);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
if (typing) typing.classList.add('d-none');
|
||||
if (sendBtn) sendBtn.disabled = false;
|
||||
if (textarea) textarea.focus();
|
||||
if (textarea && window.innerWidth > 768) textarea.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function populateRoleChips() {
|
||||
const chipsContainer = document.getElementById('aiRoleChipsContainer');
|
||||
if (!chipsContainer || chipsContainer.children.length > 0) return;
|
||||
|
||||
const role = getUserRole();
|
||||
const chips = ROLE_CHIPS[role] || ROLE_CHIPS.alumno;
|
||||
|
||||
chips.forEach(c => {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'ai-chip-pill';
|
||||
btn.textContent = c.label;
|
||||
btn.setAttribute('data-query', c.query);
|
||||
btn.addEventListener('click', () => {
|
||||
sendQuery(c.query);
|
||||
});
|
||||
chipsContainer.appendChild(btn);
|
||||
});
|
||||
}
|
||||
|
||||
function initChat() {
|
||||
const launcher = document.getElementById('aiChatLauncher');
|
||||
const panel = document.getElementById('aiChatPanel');
|
||||
const backdrop = document.getElementById('aiChatBackdrop');
|
||||
const backBtn = document.getElementById('aiChatBackBtn');
|
||||
const closeBtn = document.getElementById('aiChatCloseBtn');
|
||||
const clearBtn = document.getElementById('aiChatClearBtn');
|
||||
const chipsToggleBtn = document.getElementById('aiChatChipsToggleBtn');
|
||||
const plusBtn = document.getElementById('aiChatPlusBtn');
|
||||
const chipsDrawer = document.getElementById('aiChatQuickChips');
|
||||
const closeChipsBtn = document.getElementById('aiChatCloseChipsBtn');
|
||||
const textarea = document.getElementById('aiChatInput');
|
||||
const form = document.getElementById('aiChatForm');
|
||||
const handleBar = document.getElementById('aiSheetHandleBar');
|
||||
|
||||
if (!launcher || !panel) return;
|
||||
|
||||
@@ -287,44 +392,118 @@
|
||||
|
||||
function openChat() {
|
||||
panel.classList.remove('d-none');
|
||||
launcher.style.transform = 'scale(0.9)';
|
||||
if (backdrop) backdrop.classList.remove('d-none');
|
||||
launcher.classList.add('chat-open');
|
||||
|
||||
if (window.innerWidth <= 768) {
|
||||
document.body.classList.add('ai-chat-mobile-open');
|
||||
}
|
||||
|
||||
populateRoleChips();
|
||||
|
||||
setTimeout(() => {
|
||||
if (textarea) textarea.focus();
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (messagesContainer) messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
if (textarea && window.innerWidth > 768) textarea.focus();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function closeChat() {
|
||||
panel.classList.add('d-none');
|
||||
launcher.style.transform = '';
|
||||
if (backdrop) backdrop.classList.add('d-none');
|
||||
launcher.classList.remove('chat-open');
|
||||
document.body.classList.remove('ai-chat-mobile-open');
|
||||
|
||||
if (chipsDrawer) chipsDrawer.classList.add('d-none');
|
||||
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
|
||||
window.speechSynthesis.cancel();
|
||||
}
|
||||
|
||||
// Restaurar transform o estilos modificados por gestos
|
||||
panel.style.transform = '';
|
||||
panel.style.height = '';
|
||||
panel.style.bottom = '';
|
||||
}
|
||||
|
||||
// Toggle panel
|
||||
launcher.addEventListener('click', () => {
|
||||
const isHidden = panel.classList.contains('d-none');
|
||||
if (isHidden) {
|
||||
openChat();
|
||||
} else {
|
||||
closeChat();
|
||||
}
|
||||
if (isHidden) openChat(); else closeChat();
|
||||
});
|
||||
|
||||
if (closeBtn) {
|
||||
closeBtn.addEventListener('click', closeChat);
|
||||
if (backBtn) backBtn.addEventListener('click', closeChat);
|
||||
if (closeBtn) closeBtn.addEventListener('click', closeChat);
|
||||
if (backdrop) backdrop.addEventListener('click', closeChat);
|
||||
|
||||
// Deslizar hacia abajo en la drag handle bar para cerrar (Touch Gesture)
|
||||
if (handleBar) {
|
||||
handleBar.addEventListener('touchstart', (e) => {
|
||||
touchStartY = e.touches[0].clientY;
|
||||
touchDeltaY = 0;
|
||||
}, { passive: true });
|
||||
|
||||
handleBar.addEventListener('touchmove', (e) => {
|
||||
touchDeltaY = e.touches[0].clientY - touchStartY;
|
||||
if (touchDeltaY > 0) {
|
||||
panel.style.transform = `translateY(${touchDeltaY}px)`;
|
||||
}
|
||||
}, { passive: true });
|
||||
|
||||
handleBar.addEventListener('touchend', () => {
|
||||
if (touchDeltaY > 65) {
|
||||
closeChat();
|
||||
} else {
|
||||
panel.style.transform = '';
|
||||
}
|
||||
touchDeltaY = 0;
|
||||
});
|
||||
}
|
||||
|
||||
// Drawer de consultas rápidas (+)
|
||||
function toggleChips() {
|
||||
if (!chipsDrawer) return;
|
||||
populateRoleChips();
|
||||
chipsDrawer.classList.toggle('d-none');
|
||||
}
|
||||
if (plusBtn) plusBtn.addEventListener('click', toggleChips);
|
||||
if (chipsToggleBtn) chipsToggleBtn.addEventListener('click', toggleChips);
|
||||
if (closeChipsBtn) closeChipsBtn.addEventListener('click', () => {
|
||||
chipsDrawer.classList.add('d-none');
|
||||
});
|
||||
|
||||
// Manejo del Teclado Virtual en Dispositivos Móviles (visualViewport)
|
||||
if (window.visualViewport) {
|
||||
window.visualViewport.addEventListener('resize', () => {
|
||||
if (window.innerWidth <= 768 && !panel.classList.contains('d-none')) {
|
||||
const currentViewHeight = window.visualViewport.height;
|
||||
const screenHeight = window.innerHeight;
|
||||
|
||||
// Si la altura del viewport se reduce significativamente (teclado abierto)
|
||||
if (currentViewHeight < screenHeight * 0.88) {
|
||||
panel.style.height = `${currentViewHeight}px`;
|
||||
panel.style.bottom = `${Math.max(0, screenHeight - currentViewHeight - (window.visualViewport.offsetTop || 0))}px`;
|
||||
} else {
|
||||
// Teclado cerrado
|
||||
panel.style.height = '';
|
||||
panel.style.bottom = '';
|
||||
}
|
||||
|
||||
const messagesContainer = document.getElementById('aiChatMessages');
|
||||
if (messagesContainer) {
|
||||
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Escape para cerrar
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && panel && !panel.classList.contains('d-none')) {
|
||||
closeChat();
|
||||
}
|
||||
});
|
||||
|
||||
// Reiniciar conversación del usuario actual
|
||||
// Reiniciar conversación
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', () => {
|
||||
sessionStorage.removeItem(getStorageKey());
|
||||
@@ -334,20 +513,20 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Cargar historial previo o mensaje de bienvenida
|
||||
// Cargar historial previo o bienvenida
|
||||
const history = loadHistory();
|
||||
if (history.length > 0) {
|
||||
history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false));
|
||||
history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false, msg.timeStr));
|
||||
} else {
|
||||
appendMessage('assistant', getWelcomeMessage(role, name), [], false);
|
||||
}
|
||||
|
||||
// Atajo Enter para enviar
|
||||
// Atajo Enter en desktop
|
||||
if (textarea) {
|
||||
textarea.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (form) form.dispatchEvent(new Event('submit', { cancelable: true }));
|
||||
window.handleAiChatSubmit(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user