Files
admin-edu-space/frontend/public/js/walkthrough-engine.js
T

253 lines
9.4 KiB
JavaScript

/**
* walkthrough-engine.js - Motor de Asistencia Interactiva y Spotlight para UdeCi (SDD-011)
* "Enseñar a pescar, no dar el pescado". Ilumina elementos en vivo, guía al usuario
* y aguarda a que sea él quien ejecute la acción.
*/
(function() {
'use strict';
const PENDING_STEP_KEY = 'edu_space_walkthrough_pending_step';
let currentStepData = null;
let activeHighlightEl = null;
let backdropEl = null;
let tooltipEl = null;
let mobileBarEl = null;
let redirectBannerEl = null;
function isMobile() {
return window.innerWidth < 768;
}
function removeElement(el) {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
}
function clearSpotlight() {
if (activeHighlightEl) {
activeHighlightEl.classList.remove('walkthrough-highlight');
activeHighlightEl = null;
}
removeElement(backdropEl);
backdropEl = null;
removeElement(tooltipEl);
tooltipEl = null;
removeElement(mobileBarEl);
mobileBarEl = null;
removeElement(redirectBannerEl);
redirectBannerEl = null;
currentStepData = null;
}
function createBackdrop() {
if (backdropEl) return backdropEl;
backdropEl = document.createElement('div');
backdropEl.className = 'walkthrough-backdrop';
document.body.appendChild(backdropEl);
return backdropEl;
}
function showRedirectBanner(targetUrl, stepMessage) {
clearSpotlight();
redirectBannerEl = document.createElement('div');
redirectBannerEl.className = 'walkthrough-redirect-banner';
redirectBannerEl.innerHTML = `
<div class="d-flex align-items-center gap-2">
<span class="badge bg-primary rounded-pill px-2 py-1"><i class="bi bi-compass"></i> Guía UdeCi</span>
<span class="small fw-semibold">Debemos ir a la pantalla correspondiente para continuar.</span>
</div>
<div class="d-flex align-items-center gap-2">
<button type="button" class="btn btn-sm btn-primary walkthrough-btn-action" id="walkthroughGoBtn">
Ir a la pantalla <i class="bi bi-arrow-right"></i>
</button>
<button type="button" class="btn btn-sm btn-outline-secondary border-0" id="walkthroughCancelRedirectBtn" title="Cancelar">
<i class="bi bi-x-lg"></i>
</button>
</div>
`;
document.body.appendChild(redirectBannerEl);
document.getElementById('walkthroughGoBtn').addEventListener('click', () => {
sessionStorage.setItem(PENDING_STEP_KEY, JSON.stringify(currentStepData));
window.location.href = targetUrl;
});
document.getElementById('walkthroughCancelRedirectBtn').addEventListener('click', () => {
clearSpotlight();
sessionStorage.removeItem(PENDING_STEP_KEY);
});
}
function positionTooltip(targetEl, tooltip) {
const rect = targetEl.getBoundingClientRect();
const tooltipWidth = 320;
const margin = 12;
let top = rect.bottom + window.scrollY + margin;
let left = rect.left + window.scrollX;
// Ajuste si se sale a la derecha
if (left + tooltipWidth > window.innerWidth - 20) {
left = window.innerWidth - tooltipWidth - 20;
}
if (left < 10) left = 10;
// Si se sale por abajo de la pantalla, posicionar arriba del elemento
if (rect.bottom + 180 > window.innerHeight) {
top = rect.top + window.scrollY - 160;
}
tooltip.style.top = `${Math.max(10, top)}px`;
tooltip.style.left = `${left}px`;
}
function renderTooltipDesktop(targetEl, step) {
removeElement(tooltipEl);
tooltipEl = document.createElement('div');
tooltipEl.className = 'walkthrough-tooltip';
tooltipEl.innerHTML = `
<div class="walkthrough-tooltip-header">
<span class="walkthrough-badge">UdeCi · Paso ${step.step_number} de ${step.total_steps}</span>
<button type="button" class="btn-close btn-close-white btn-sm" id="walkthroughCloseBtn" aria-label="Cerrar"></button>
</div>
<div class="walkthrough-tooltip-body">
${step.message}
</div>
<div class="walkthrough-tooltip-footer">
<span class="walkthrough-action-hint">
<i class="bi bi-hand-index-thumb"></i> Haz clic en el botón iluminado
</span>
<button type="button" class="btn btn-sm btn-outline-secondary py-0 px-2" style="font-size: 0.75rem;" id="walkthroughSkipBtn">
Omitir
</button>
</div>
`;
document.body.appendChild(tooltipEl);
positionTooltip(targetEl, tooltipEl);
document.getElementById('walkthroughCloseBtn').addEventListener('click', clearSpotlight);
document.getElementById('walkthroughSkipBtn').addEventListener('click', clearSpotlight);
}
function renderMobileBar(step) {
removeElement(mobileBarEl);
mobileBarEl = document.createElement('div');
mobileBarEl.className = 'walkthrough-mobile-bar';
mobileBarEl.innerHTML = `
<div class="d-flex align-items-center justify-content-between mb-2">
<span class="badge bg-primary">UdeCi · Paso ${step.step_number}/${step.total_steps}</span>
<button type="button" class="btn btn-sm btn-outline-light border-0 py-0" id="walkthroughMobileClose">
<i class="bi bi-x-lg"></i>
</button>
</div>
<div class="small fw-semibold mb-2">
${step.message}
</div>
<div class="d-flex align-items-center justify-content-between">
<span class="small text-muted"><i class="bi bi-hand-index"></i> Presiona el elemento iluminado</span>
<button type="button" class="btn btn-sm btn-outline-secondary" id="walkthroughMobileSkip">Omitir</button>
</div>
`;
document.body.appendChild(mobileBarEl);
document.getElementById('walkthroughMobileClose').addEventListener('click', clearSpotlight);
document.getElementById('walkthroughMobileSkip').addEventListener('click', clearSpotlight);
}
function highlightElement(el, step) {
clearSpotlight();
currentStepData = step;
activeHighlightEl = el;
createBackdrop();
el.classList.add('walkthrough-highlight');
// Scroll suave hacia el elemento
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
if (isMobile()) {
renderMobileBar(step);
} else {
renderTooltipDesktop(el, step);
}
// Listener para detectar la interacción del usuario
const handleUserAction = function() {
// Micro-feedback de éxito
if (activeHighlightEl) {
activeHighlightEl.style.transition = 'all 0.3s ease';
activeHighlightEl.style.transform = 'scale(1.05)';
}
setTimeout(() => {
clearSpotlight();
sessionStorage.removeItem(PENDING_STEP_KEY);
}, 500);
el.removeEventListener('click', handleUserAction);
};
el.addEventListener('click', handleUserAction, { once: true });
}
function startStep(step) {
if (!step || !step.selector) return;
currentStepData = step;
const currentPath = window.location.pathname;
const targetPath = step.target_url;
// Si el usuario está en otra pantalla, sugerir redirección
if (targetPath && !currentPath.includes(targetPath) && !targetPath.includes(currentPath)) {
showRedirectBanner(targetPath, step.message);
return;
}
// Si ya estamos en la pantalla, buscar selector
let targetEl = document.querySelector(step.selector);
// Si no lo encuentra de inmediato (por modales o carga diferida), reintentar brevemente
if (!targetEl) {
let attempts = 0;
const timer = setInterval(() => {
attempts++;
targetEl = document.querySelector(step.selector);
if (targetEl) {
clearInterval(timer);
highlightElement(targetEl, step);
} else if (attempts >= 8) {
clearInterval(timer);
console.warn(`[WalkthroughEngine] Elemento no encontrado: ${step.selector}`);
}
}, 250);
} else {
highlightElement(targetEl, step);
}
}
function checkPendingStep() {
try {
const raw = sessionStorage.getItem(PENDING_STEP_KEY);
if (raw) {
const step = JSON.parse(raw);
sessionStorage.removeItem(PENDING_STEP_KEY);
setTimeout(() => {
startStep(step);
}, 400);
}
} catch (e) {}
}
// Exponer API global
window.WalkthroughEngine = {
startStep,
clearSpotlight,
checkPendingStep
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', checkPendingStep);
} else {
checkPendingStep();
}
})();