Diferencia entre revisiones de «MediaWiki:Common.js»

De Historia del Club Escuela de Piraguismo Aranjuez
Saltar a: navegación, buscar
(Página creada con «WIKICONSULTAS - Chat de consultas (Piragüismo en Aranjuez): (function () { 'use strict'; // === CONFIGURACIÓN === // Cambia esta URL por tu endpoint cuando lo...»)
 
Línea 199: Línea 199:
 
     // Permite abrirlo con #wikiconsultas en la URL
 
     // Permite abrirlo con #wikiconsultas en la URL
 
     if (location.hash === '#wikiconsultas') openModal(overlay, input);
 
     if (location.hash === '#wikiconsultas') openModal(overlay, input);
 +
// Abrir/cerrar al cambiar el hash (para que el enlace funcione sin recargar)
 +
window.addEventListener('hashchange', function () {
 +
  if (location.hash === '#wikiconsultas') {
 +
    openModal(overlay, input);
 
   }
 
   }
 
+
});
  mw.loader.using(['mediawiki.util']).then(init);
 
})();
 

Revisión del 09:52 6 feb 2026

/* WIKICONSULTAS - Chat de consultas (Piragüismo en Aranjuez) */
(function () {
  'use strict';

  // === CONFIGURACIÓN ===
  // Cambia esta URL por tu endpoint cuando lo tengas (puede ser Make, n8n, servidor propio, etc.)
  var WIKICONSULTAS_ENDPOINT = 'https://TU-DOMINIO.com/wikiconsultas';

  // Texto de dominio (para mantener el asistente “en su carril”)
  var SCOPE_NOTICE = 'Puedo ayudarte solo con consultas sobre el piragüismo en Aranjuez basándome en el contenido de esta wiki.';

  function addStyles() {
    mw.util.addCSS(`
      #wikiconsultas-btn{
        position:fixed; right:18px; bottom:18px; z-index:9999;
        padding:10px 14px; border-radius:999px; border:1px solid rgba(0,0,0,.15);
        background:#fff; cursor:pointer; box-shadow:0 6px 18px rgba(0,0,0,.18);
        font-weight:600;
      }
      #wikiconsultas-overlay{
        position:fixed; inset:0; z-index:99999; background:rgba(0,0,0,.45);
        display:none; align-items:center; justify-content:center; padding:18px;
      }
      #wikiconsultas-modal{
        width:min(760px, 96vw); height:min(560px, 86vh);
        background:#fff; border-radius:14px; overflow:hidden;
        box-shadow:0 14px 40px rgba(0,0,0,.25);
        display:flex; flex-direction:column;
      }
      #wikiconsultas-head{
        display:flex; align-items:center; justify-content:space-between;
        padding:12px 14px; border-bottom:1px solid rgba(0,0,0,.10);
      }
      #wikiconsultas-title{ font-size:16px; font-weight:700; }
      #wikiconsultas-close{
        border:0; background:transparent; cursor:pointer; font-size:20px; line-height:1;
        padding:6px 10px; border-radius:10px;
      }
      #wikiconsultas-close:hover{ background:rgba(0,0,0,.06); }
      #wikiconsultas-scope{
        padding:10px 14px; font-size:13px; color:#333;
        background:rgba(0,0,0,.03); border-bottom:1px solid rgba(0,0,0,.08);
      }
      #wikiconsultas-log{
        padding:14px; overflow:auto; flex:1; background:#fafafa;
      }
      .wk-msg{ margin:0 0 10px 0; display:flex; gap:10px; }
      .wk-badge{
        width:28px; height:28px; border-radius:50%;
        display:flex; align-items:center; justify-content:center;
        font-weight:700; font-size:12px; flex:0 0 auto;
        border:1px solid rgba(0,0,0,.12); background:#fff;
      }
      .wk-bubble{
        padding:10px 12px; border-radius:12px; max-width:85%;
        border:1px solid rgba(0,0,0,.10); background:#fff;
        white-space:pre-wrap;
      }
      .wk-user .wk-bubble{ background:#fff; }
      .wk-bot  .wk-bubble{ background:#ffffff; }
      #wikiconsultas-foot{
        padding:10px; border-top:1px solid rgba(0,0,0,.10);
        display:flex; gap:10px; background:#fff;
      }
      #wikiconsultas-input{
        flex:1; padding:10px 12px; border-radius:10px;
        border:1px solid rgba(0,0,0,.18);
      }
      #wikiconsultas-send{
        padding:10px 14px; border-radius:10px; border:1px solid rgba(0,0,0,.18);
        background:#fff; cursor:pointer; font-weight:700;
      }
      #wikiconsultas-send:hover{ background:rgba(0,0,0,.04); }
      .wk-muted{ color:#666; font-size:12px; margin-top:6px; }
    `);
  }

  function el(tag, attrs, children) {
    var node = document.createElement(tag);
    if (attrs) Object.keys(attrs).forEach(function (k) { node.setAttribute(k, attrs[k]); });
    (children || []).forEach(function (c) { node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); });
    return node;
  }

  function appendMsg(log, who, text) {
    var msg = el('div', { class: 'wk-msg ' + (who === 'user' ? 'wk-user' : 'wk-bot') }, [
      el('div', { class: 'wk-badge' }, [who === 'user' ? 'Tú' : 'WK']),
      el('div', { class: 'wk-bubble' }, [text])
    ]);
    log.appendChild(msg);
    log.scrollTop = log.scrollHeight;
  }

  function openModal(overlay, input) {
    overlay.style.display = 'flex';
    setTimeout(function () { input.focus(); }, 50);
  }

  function closeModal(overlay) {
    overlay.style.display = 'none';
  }

  async function askBackend(question) {
    // Si aún no has puesto endpoint real, devolvemos un aviso útil
    if (!WIKICONSULTAS_ENDPOINT || WIKICONSULTAS_ENDPOINT.indexOf('TU-DOMINIO.com') !== -1) {
      return "Aún no estoy conectado a un servicio de IA.\n\nPara activarme, configura WIKICONSULTAS_ENDPOINT en MediaWiki:Common.js con la URL de tu API.\n\nMientras tanto, dime qué página o sección te interesa y te indico dónde buscar dentro de la wiki.";
    }

    var payload = {
      assistant: "WIKICONSULTAS",
      scope: "Piragüismo en Aranjuez",
      question: question,
      pageTitle: mw.config.get('wgTitle'),
      pageName: mw.config.get('wgPageName'),
      url: location.href,
      language: "es"
    };

    var res = await fetch(WIKICONSULTAS_ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (!res.ok) throw new Error('HTTP ' + res.status);
    var data = await res.json();

    // Espera { answer: "..." } (y opcionalmente suggested_pages)
    return (data && data.answer) ? data.answer : 'No he recibido respuesta válida del servicio.';
  }

  function init() {
    if (document.getElementById('wikiconsultas-btn')) return;

    addStyles();

    var btn = el('button', { id: 'wikiconsultas-btn', type: 'button', title: 'Abrir WIKICONSULTAS' }, ['WIKICONSULTAS']);
    var overlay = el('div', { id: 'wikiconsultas-overlay', role: 'dialog', 'aria-modal': 'true' });
    var modal = el('div', { id: 'wikiconsultas-modal' });

    var head = el('div', { id: 'wikiconsultas-head' }, [
      el('div', { id: 'wikiconsultas-title' }, ['WIKICONSULTAS']),
      el('button', { id: 'wikiconsultas-close', type: 'button', title: 'Cerrar' }, ['×'])
    ]);

    var scope = el('div', { id: 'wikiconsultas-scope' }, [SCOPE_NOTICE]);

    var log = el('div', { id: 'wikiconsultas-log' });
    var foot = el('div', { id: 'wikiconsultas-foot' });
    var input = el('input', { id: 'wikiconsultas-input', type: 'text', placeholder: 'Escribe tu consulta… (ej: “¿qué etapas históricas recoge la wiki?”)' });
    var send = el('button', { id: 'wikiconsultas-send', type: 'button' }, ['Enviar']);

    foot.appendChild(input);
    foot.appendChild(send);

    modal.appendChild(head);
    modal.appendChild(scope);
    modal.appendChild(log);
    modal.appendChild(foot);
    overlay.appendChild(modal);

    document.body.appendChild(btn);
    document.body.appendChild(overlay);

    // Mensaje inicial
    appendMsg(log, 'bot', "Hola 👋 Soy WIKICONSULTAS.\nHazme preguntas sobre el piragüismo en Aranjuez basándome en el contenido de esta wiki.");

    // Eventos
    btn.addEventListener('click', function () { openModal(overlay, input); });
    document.getElementById('wikiconsultas-close').addEventListener('click', function () { closeModal(overlay); });
    overlay.addEventListener('click', function (e) { if (e.target === overlay) closeModal(overlay); });

    async function doSend() {
      var q = (input.value || '').trim();
      if (!q) return;

      appendMsg(log, 'user', q);
      input.value = '';
      appendMsg(log, 'bot', 'Pensando…');

      // Reemplaza el último “Pensando…” cuando llegue la respuesta
      var thinkingNode = log.lastChild;

      try {
        var answer = await askBackend(q);
        thinkingNode.querySelector('.wk-bubble').textContent = answer;
      } catch (err) {
        thinkingNode.querySelector('.wk-bubble').textContent =
          "No he podido conectar con el servicio.\n\nDetalles: " + (err && err.message ? err.message : String(err));
      }
    }

    send.addEventListener('click', doSend);
    input.addEventListener('keydown', function (e) {
      if (e.key === 'Enter') doSend();
      if (e.key === 'Escape') closeModal(overlay);
    });

    // Permite abrirlo con #wikiconsultas en la URL
    if (location.hash === '#wikiconsultas') openModal(overlay, input);
// Abrir/cerrar al cambiar el hash (para que el enlace funcione sin recargar)
window.addEventListener('hashchange', function () {
  if (location.hash === '#wikiconsultas') {
    openModal(overlay, input);
  }
});