Jump to content

MediaWiki:Common.js: Difference between revisions

From Fedoverse Wiki, the free encyclopedia
No edit summary
Tag: Reverted
No edit summary
 
(49 intermediate revisions by the same user not shown)
Line 1: Line 1:
/* =========================================================
/* =========================================================
   1. MINECRAFT SERVER STATUS  (was missing: nothing ever
   PODCAST + YOUTUBE DECK
      replaced "Checking…", so it stayed stuck forever)
  - Combines podcast RSS and multiple YouTube channel feeds
  - Shows the 3 newest items across all successful sources
  - Per-source fallback and error handling
  - Preserves existing .pc-* card and carousel styling
   ========================================================= */
   ========================================================= */
mw.hook('wikipage.content').add(function ($content) {
mw.hook('wikipage.content').add(function ($content) {
   $content.find('.mc-status').each(function () {
   var root = $content.find('#pc-podcast')[0];
    var box = this;
    if (box.dataset.mcInit === '1') return;
    box.dataset.mcInit = '1';


    var host = box.dataset.host || 'smp.fedoverse.com';
  if (!root || root.dataset.pcInit === '1') return;
    var stateEl = box.querySelector('.mc-state');
  root.dataset.pcInit = '1';
    var playersEl = box.querySelector('.mc-players');
    var iconEl = box.querySelector('.mc-icon');
    var motdEl = box.querySelector('.mc-motd');
    var addrEl = box.querySelector('.mc-addr');
    var mainEl = box.querySelector('.mc-main');


    function getJson(url, ms) {
  var feed = root.dataset.feed || '';
      var ctrl = window.AbortController ? new AbortController() : null;
  var page = root.dataset.page || '';
      var timer = ctrl ? setTimeout(function () { ctrl.abort(); }, ms || 8000) : null;
  var channels = (root.dataset.channels || '')
      return fetch(url, ctrl ? { signal: ctrl.signal } : undefined)
    .split(',')
        .then(function (r) {
    .map(function (id) { return id.trim(); })
          if (!r.ok) throw new Error('HTTP ' + r.status);
    .filter(function (id) {
          return r.json();
      return /^[A-Za-z0-9_-]+$/.test(id);
        })
    });
        .then(
          function (v) { clearTimeout(timer); return v; },
          function (e) { clearTimeout(timer); throw e; }
        );
    }


    // Normalise the two APIs into one shape
  var deck = root.querySelector('.pc-deck');
    function fromMcStatusIo(j) {
  var nav = root.querySelector('.pc-nav');
      if (!j || typeof j.online !== 'boolean') throw new Error('bad response');
      return {
        online: j.online,
        players: j.players ? j.players.online : 0,
        max: j.players ? j.players.max : 0,
        motd: j.motd && j.motd.clean ? String(j.motd.clean) : '',
        icon: j.icon || ''
      };
    }


    function fromMcSrvStat(j) {
  if (!deck || !nav) return;
      if (!j || typeof j.online !== 'boolean') throw new Error('bad response');
      return {
        online: j.online,
        players: j.players ? j.players.online : 0,
        max: j.players ? j.players.max : 0,
        motd: j.motd && j.motd.clean ? [].concat(j.motd.clean).join('\n') : '',
        icon: j.icon || ''
      };
    }


    function fetchStatus() {
  var cards = [];
      return getJson('https://api.mcstatus.io/v2/status/java/' + encodeURIComponent(host))
  var dots = [];
        .then(fromMcStatusIo)
  var active = 0;
        .catch(function () {
          return getJson('https://api.mcsrvstat.us/3/' + encodeURIComponent(host))
            .then(fromMcSrvStat);
        });
    }
 
    function setState(name) {
      box.dataset.state = name;
      box.classList.toggle('is-online', name === 'online');
      box.classList.toggle('is-offline', name === 'offline');
      box.classList.toggle('is-error', name === 'error');
    }


    function show(s) {
   /* ---------- Utilities ---------- */
      setState(s.online ? 'online' : 'offline');
      if (stateEl) stateEl.textContent = s.online ? 'Online' : 'Offline';
      if (playersEl) playersEl.textContent = s.online ? s.players + ' / ' + s.max : '– / –';
 
      if (motdEl) {
        motdEl.textContent = '';
        if (s.online) {
          s.motd.split('\n').forEach(function (line) {
            line = line.trim();
            if (line) {
              var d = document.createElement('div');
              d.textContent = line;
              motdEl.appendChild(d);
            }
          });
        }
      }
 
      if (iconEl) {
        iconEl.textContent = '';
        if (/^data:image\/png;base64,/i.test(s.icon)) {
          var img = document.createElement('img');
          img.alt = '';
          img.src = s.icon;
          iconEl.appendChild(img);
        }
      }
    }
 
    function showError() {
      setState('error');
      if (stateEl) stateEl.textContent = 'Status unavailable';
      if (playersEl) playersEl.textContent = '– / –';
    }
 
    function refresh() {
      if (!document.body.contains(box)) return; // page content was replaced
      fetchStatus().then(show, showError);
    }
 
    // Click / Enter on the address copies the IP
    function copyAddr() {
      if (!navigator.clipboard || !navigator.clipboard.writeText || !addrEl) return;
      navigator.clipboard.writeText(host).then(function () {
        addrEl.textContent = 'Copied!';
        setTimeout(function () { addrEl.textContent = host; }, 1200);
      }, function () { /* clipboard blocked, ignore */ });
    }
 
    if (mainEl) {
      mainEl.addEventListener('click', copyAddr);
      mainEl.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          copyAddr();
        }
      });
    }
 
    refresh();
    setInterval(refresh, 60000);
   });
});
 
 
/* =========================================================
  2. PODCAST DECK
  Changes: runs inside mw.hook (DOM guaranteed), tries several
  sources in order, falls through when a source returns an
  empty list, and shows a link instead of staying blank.
  ========================================================= */
mw.hook('wikipage.content').add(function ($content) {
  var root = $content.find('#pc-podcast')[0];
  if (!root || root.dataset.pcInit === '1') return;
  root.dataset.pcInit = '1';
 
  var feed = root.dataset.feed, page = root.dataset.page;
  var deck = root.querySelector('.pc-deck'), nav = root.querySelector('.pc-nav');
  var cards = [], dots = [], active = 0;


   function el(tag, cls, text) {
   function el(tag, cls, text) {
     var e = document.createElement(tag);
     var e = document.createElement(tag);
     if (cls) e.className = cls;
     if (cls) e.className = cls;
     if (text) e.textContent = text;
     if (text != null) e.textContent = text;
     return e;
     return e;
   }
   }


   function safeUrl(u) { return /^https?:\/\//i.test(u || '') ? u : ''; }
   function safeUrl(u) {
   function txt(node, tag) { var n = node.getElementsByTagName(tag)[0]; return n ? n.textContent.trim() : ''; }
    return /^https?:\/\//i.test(u || '') ? u : '';
  }
 
   function txt(node, tag) {
    var n = node.getElementsByTagName(tag)[0];
    return n ? n.textContent.trim() : '';
  }
 
   function plain(html) {
   function plain(html) {
     return new DOMParser().parseFromString(html || '', 'text/html').body.textContent.replace(/\s+/g, ' ').trim();
     return new DOMParser()
      .parseFromString(html || '', 'text/html')
      .body.textContent
      .replace(/\s+/g, ' ')
      .trim();
   }
   }
   function parseDate(s) {
   function parseDate(s) {
    if (!s) return new Date(NaN);
     var d = new Date(s);
     var d = new Date(s);
     if (isNaN(d)) d = new Date(String(s).replace(' ', 'T') + 'Z');
 
     if (isNaN(d)) {
      d = new Date(String(s).replace(' ', 'T') + 'Z');
    }
 
     return d;
     return d;
   }
   }
  function dateValue(s) {
    var d = parseDate(s);
    return isNaN(d) ? 0 : d.getTime();
  }
   function fmtDate(s) {
   function fmtDate(s) {
     var d = parseDate(s);
     var d = parseDate(s);
     return isNaN(d) ? '' : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
 
     return isNaN(d) ? '' : d.toLocaleDateString(
      undefined,
      {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      }
    );
   }
   }
   function fmtDur(v) {
   function fmtDur(v) {
     if (!v) return '';
     if (!v) return '';
     if (v.indexOf(':') > -1) return v.replace(/^00:/, '').replace(/^0(\d:)/, '$1');
 
     if (v.indexOf(':') > -1) {
      return v.replace(/^00:/, '').replace(/^0(\d:)/, '$1');
    }
 
     var s = parseInt(v, 10);
     var s = parseInt(v, 10);
     if (!s) return '';
     if (!s) return '';
     var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
 
     return (h ? h + ':' + ('0' + m).slice(-2) : m) + ':' + ('0' + sec).slice(-2);
     var h = Math.floor(s / 3600);
    var m = Math.floor((s % 3600) / 60);
    var sec = s % 60;
 
     return (h ? h + ':' + ('0' + m).slice(-2) : m)
      + ':' + ('0' + sec).slice(-2);
   }
   }
  function okText(r) {
    if (!r.ok) throw new Error('HTTP ' + r.status);
    return r.text();
  }
  function okJson(r) {
    if (!r.ok) throw new Error('HTTP ' + r.status);
    return r.json();
  }
  /* ---------- Podcast RSS parser ---------- */


   function fromXml(xml) {
   function fromXml(xml) {
     var doc = new DOMParser().parseFromString(xml, 'application/xml');
     var doc = new DOMParser().parseFromString(
     if (doc.getElementsByTagName('parsererror').length) throw new Error('bad xml');
      xml,
      'application/xml'
    );
 
     if (doc.getElementsByTagName('parsererror').length) {
      throw new Error('Invalid podcast XML');
    }
 
     var chImg = doc.getElementsByTagName('itunes:image')[0];
     var chImg = doc.getElementsByTagName('itunes:image')[0];
     var chCover = chImg ? chImg.getAttribute('href') : '';
     var chCover = chImg ? chImg.getAttribute('href') : '';


     return Array.prototype.map.call(doc.getElementsByTagName('item'), function (it) {
     return Array.prototype.map.call(
      var img = it.getElementsByTagName('itunes:image')[0];
      doc.getElementsByTagName('item'),
      var s = txt(it, 'itunes:season'), e = txt(it, 'itunes:episode');
      function (it) {
        var img = it.getElementsByTagName('itunes:image')[0];
        var season = txt(it, 'itunes:season');
        var episode = txt(it, 'itunes:episode');
 
        return {
          title: txt(it, 'title'),
          link: txt(it, 'link'),
          date: txt(it, 'pubDate'),
          dur: fmtDur(txt(it, 'itunes:duration')),
          tag: episode
            ? (season ? 'S' + season + ' · ' : '') + 'E' + episode
            : 'Podcast',
          desc: plain(txt(it, 'description')),
          cover: (img && img.getAttribute('href')) || chCover
        };
      }
    );
  }
 
  /* ---------- YouTube Atom/RSS parser ---------- */
 
  function fromYouTubeXml(xml) {
    var doc = new DOMParser().parseFromString(
      xml,
      'application/xml'
    );
 
    if (doc.getElementsByTagName('parsererror').length) {
      throw new Error('Invalid YouTube XML');
    }
 
    return Array.prototype.map.call(
      doc.getElementsByTagName('entry'),
      function (entry) {
        var videoId = txt(entry, 'yt:videoId');
        var links = entry.getElementsByTagName('link');
        var link = '';
 
        // Prefer the normal video page, not a related link.
        for (var i = 0; i < links.length; i++) {
          var rel = links[i].getAttribute('rel');
          var href = links[i].getAttribute('href') || '';
 
          if ((!rel || rel === 'alternate') && href) {
            link = href;
            break;
          }
        }
 
        if (!link && videoId) {
          link = 'https://www.youtube.com/watch?v=' + videoId;
        }
 
        var group = entry.getElementsByTagName('media:group')[0];
        var thumbnail = group
          ? group.getElementsByTagName('media:thumbnail')[0]
          : null;
 
        var description = group
          ? txt(group, 'media:description')
          : '';


      return {
        return {
        title: txt(it, 'title'),
          title: txt(entry, 'title'),
        link: txt(it, 'link'),
          link: link,
        date: txt(it, 'pubDate'),
          date: txt(entry, 'published') || txt(entry, 'updated'),
        dur: fmtDur(txt(it, 'itunes:duration')),
          dur: '',
        tag: e ? (s ? 'S' + s + ' · ' : '') + 'E' + e : '',
          tag: 'YouTube',
        desc: plain(txt(it, 'description')),
          desc: plain(description),
        cover: (img && img.getAttribute('href')) || chCover
          cover: thumbnail
       };
            ? thumbnail.getAttribute('url')
     });
            : videoId
              ? 'https://i.ytimg.com/vi/' + videoId + '/hqdefault.jpg'
              : ''
        };
       }
     );
   }
   }
  /* ---------- JSON feed fallback ---------- */


   function fromJson(j) {
   function fromJson(j) {
     var chCover = j.feed && j.feed.image;
     var chCover = j.feed && j.feed.image;
    // Some services return a feed image as an object.
    if (chCover && typeof chCover === 'object') {
      chCover = chCover.url || chCover.href || '';
    }
     return (j.items || []).map(function (it) {
     return (j.items || []).map(function (it) {
      var enclosure = it.enclosure;
      var cover = it.thumbnail || chCover || '';
      if (!cover && enclosure && typeof enclosure === 'object') {
        cover = enclosure.link || enclosure.url || '';
      }
       return {
       return {
         title: it.title,
         title: it.title || '',
         link: it.link,
         link: it.link || '',
         date: it.pubDate,
         date: it.pubDate || it.published || it.date || '',
         dur: '',
         dur: fmtDur(it.itunes && it.itunes.duration
         tag: '',
          ? it.itunes.duration
         desc: plain(it.description),
          : it.duration || ''),
         cover: it.thumbnail || chCover
         tag: 'Podcast',
         desc: plain(it.description || it.content || ''),
         cover: cover
       };
       };
     });
     });
   }
   }


  function okText(r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); }
  function okJson(r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }


  function loadEpisodes() {
    var enc = encodeURIComponent(feed);
    var sources = [
      function () { return fetch(feed).then(okText).then(fromXml); },
      function () { return fetch('https://api.allorigins.win/raw?url=' + enc).then(okText).then(fromXml); },
      function () { return fetch('https://api.rss2json.com/v1/api.json?rss_url=' + enc).then(okJson).then(fromJson); },
      function () { return fetch('https://corsproxy.io/?url=' + enc).then(okText).then(fromXml); }
    ];


     // Try each source in turn; an error OR an empty list moves on to the next
/* ---------- Feed loading and CORS fallbacks ---------- */
     return sources.reduce(function (p, src) {
 
      return p.catch(function () {
function normalize(list) {
        return src().then(function (list) {
  return (list || []).filter(function (item) {
          list = list.filter(function (e) { return e.title; });
     return item && item.title;
          if (!list.length) throw new Error('empty');
  });
          return list;
}
        });
 
function fetchText(url) {
  return fetch(url).then(function (response) {
    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }
    return response.text();
  });
}
 
function fetchJson(url) {
  return fetch(url).then(function (response) {
    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }
    return response.json();
  });
}
 
/* Parse RSS2JSON responses for podcasts and YouTube. */
function fromConvertedJson(json, kind) {
  if (json.status && json.status !== 'ok') {
    throw new Error(json.message || 'Feed conversion failed');
  }
 
  var feedCover = json.feed && json.feed.image;
 
  if (feedCover && typeof feedCover === 'object') {
    feedCover = feedCover.url || feedCover.href || '';
  }
 
  return (json.items || []).map(function (item) {
    var link = item.link || '';
    var videoId = '';
 
    if (kind === 'youtube') {
      var match =
        link.match(/[?&]v=([^&]+)/) ||
        link.match(/youtu\.be\/([^?&/]+)/) ||
        link.match(/\/shorts\/([^?&/]+)/);
 
      if (match) videoId = match[1];
    }
 
    var cover = item.thumbnail || feedCover || '';
 
    if (!cover && videoId) {
      cover = 'https://i.ytimg.com/vi/'
        + videoId + '/hqdefault.jpg';
    }
 
    var duration = item.itunes && item.itunes.duration
      ? item.itunes.duration
      : item.duration || '';
 
     return {
      title: item.title || '',
      link: link,
      date: item.pubDate || item.published || item.date || '',
      dur: kind === 'podcast' ? fmtDur(String(duration)) : '',
      tag: kind === 'youtube' ? 'YouTube' : 'Podcast',
      desc: plain(item.description || item.content || ''),
      cover: cover
    };
  });
}
 
/*
* jsonFirst=true: try the converter first for YouTube,
* because direct access is blocked by browser CORS.
*
* No CorsProxy request is made here because it returned 401.
*/
function loadFeed(url, xmlParser, kind, jsonFirst) {
  var encoded = encodeURIComponent(url);
 
  var direct = function () {
    return fetchText(url).then(xmlParser);
  };
 
  var converted = function () {
    return fetchJson(
      'https://api.rss2json.com/v1/api.json?rss_url='
      + encoded
    ).then(function (json) {
      return fromConvertedJson(json, kind);
    });
  };
 
var corsDev = function () {
  return fetchText(
    'https://proxy.cors.dev/' + url
  ).then(xmlParser);
};
 
var allOrigins = function () {
  return fetchText(
    'https://api.allorigins.win/raw?url=' + encoded
  ).then(xmlParser);
};
 
var sources = jsonFirst
  ? [converted, corsDev, allOrigins, direct]
  : [direct, corsDev, allOrigins, converted];
  return sources.reduce(function (previous, source) {
    return previous.catch(function () {
      return source().then(function (list) {
        list = normalize(list);
 
        if (!list.length) {
          throw new Error('No usable feed items');
        }
 
        return list;
       });
       });
     }, Promise.reject(new Error('start')));
     });
  }, Promise.reject(new Error('Starting feed fallbacks')));
}
 
function loadEpisodes() {
  if (!safeUrl(feed)) {
    return Promise.reject(new Error('Invalid podcast feed URL'));
   }
   }
  return loadFeed(feed, fromXml, 'podcast', false);
}
function loadYouTubeChannel(channelId) {
  var url =
    'https://www.youtube.com/feeds/videos.xml?channel_id='
    + encodeURIComponent(channelId);
  return loadFeed(url, fromYouTubeXml, 'youtube', true);
}
  /* ---------- Card creation ---------- */


   function buildCard(ep) {
   function buildCard(ep) {
Line 250: Line 399:
       img.alt = '';
       img.alt = '';
       img.loading = 'lazy';
       img.loading = 'lazy';
       img.onerror = function () { cover.textContent = '🎙️'; };
       img.onerror = function () {
        cover.textContent = ep.tag === 'YouTube' ? '▶️' : '🎙️';
      };
       img.src = ep.cover;
       img.src = ep.cover;
       cover.appendChild(img);
       cover.appendChild(img);
     } else {
     } else {
       cover.textContent = '🎙️';
       cover.textContent = ep.tag === 'YouTube' ? '▶️' : '🎙️';
     }
     }


Line 260: Line 411:
     var meta = el('div', 'pc-meta');
     var meta = el('div', 'pc-meta');


     if (ep.tag) meta.appendChild(el('span', 'pc-pill pc-pill-strong', ep.tag));
     if (ep.tag) {
      meta.appendChild(el('span', 'pc-pill pc-pill-strong', ep.tag));
    }
 
     var ds = fmtDate(ep.date);
     var ds = fmtDate(ep.date);
     if (ds) meta.appendChild(el('span', 'pc-pill', ds));
     if (ds) meta.appendChild(el('span', 'pc-pill', ds));
     if (ep.dur) meta.appendChild(el('span', 'pc-pill', ep.dur));
     if (ep.dur) meta.appendChild(el('span', 'pc-pill', ep.dur));
     if (meta.children.length) body.appendChild(meta);
     if (meta.children.length) body.appendChild(meta);


     var href = safeUrl(ep.link) || safeUrl(page);
     var href = safeUrl(ep.link) || safeUrl(page);
     var title = el('div', 'pc-title');
     var title = el('div', 'pc-title');
     title.setAttribute('role', 'heading');
     title.setAttribute('role', 'heading');
     title.setAttribute('aria-level', '3');
     title.setAttribute('aria-level', '3');


     var a = el('a', '', ep.title || 'Untitled episode');
     var a = el('a', '', ep.title || 'Untitled episode');
     if (href) {
     if (href) {
       a.href = href;
       a.href = href;
       a.target = '_blank';
       a.target = '_blank';
       a.rel = 'noopener';
       a.rel = 'noopener noreferrer';
     }
     }
     title.appendChild(a);
     title.appendChild(a);
     body.appendChild(title);
     body.appendChild(title);
     body.appendChild(el('p', 'pc-desc', ep.desc));
     body.appendChild(el('p', 'pc-desc', ep.desc || ''));


     c.appendChild(cover);
     c.appendChild(cover);
Line 287: Line 445:
       var o = el('div', 'mc-open');
       var o = el('div', 'mc-open');
       var oa = el('a');
       var oa = el('a');
       oa.href = href;
       oa.href = href;
       oa.target = '_blank';
       oa.target = '_blank';
       oa.rel = 'noopener';
       oa.rel = 'noopener noreferrer';
       oa.title = 'Open episode';
       oa.title = ep.tag === 'YouTube' ? 'Watch video' : 'Open episode';
       oa.setAttribute('aria-label', 'Open episode');
       oa.setAttribute(
        'aria-label',
        ep.tag === 'YouTube' ? 'Watch video' : 'Open episode'
      );
 
       oa.appendChild(el('span', 'mc-open-icon'));
       oa.appendChild(el('span', 'mc-open-icon'));
       o.appendChild(oa);
       o.appendChild(oa);
Line 299: Line 462:
     return c;
     return c;
   }
   }
  /* ---------- Carousel behavior ---------- */


   function layout() {
   function layout() {
Line 306: Line 471:
     cards.forEach(function (c, i) {
     cards.forEach(function (c, i) {
       var pos = (i - active + n) % n;
       var pos = (i - active + n) % n;
       c.dataset.pos = pos;
       c.dataset.pos = pos;
       c.inert = pos !== 0;
       c.inert = pos !== 0;
Line 317: Line 483:


   function go(delta) {
   function go(delta) {
    active = (active + delta + cards.length) % cards.length;
  if (!cards.length) return;
    layout();
 
  }
  active = (active + delta + cards.length) % cards.length;
 
  layout();
}


   function arrow(label, path, delta) {
   function arrow(label, path, delta) {
Line 325: Line 494:
     b.type = 'button';
     b.type = 'button';
     b.setAttribute('aria-label', label);
     b.setAttribute('aria-label', label);
     b.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="' + path + '"/></svg>';
 
     b.addEventListener('click', function () { go(delta); });
     b.innerHTML =
      '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
      'stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
      '<path d="' + path + '"/></svg>';
 
     b.addEventListener('click', function () {
      go(delta);
    });
 
     return b;
     return b;
   }
   }
Line 332: Line 509:
   function render(list) {
   function render(list) {
     list = list
     list = list
       .sort(function (a, b) { return parseDate(b.date) - parseDate(a.date); })
       .sort(function (a, b) {
       .slice(0, 3);
        return dateValue(b.date) - dateValue(a.date);
      })
       .slice(0, 5);


     deck.innerHTML = '';
     deck.innerHTML = '';
Line 348: Line 527:


     for (var k = cards.length; k < 3; k++) {
     for (var k = cards.length; k < 3; k++) {
       var g = el('div', 'pc-card pc-ghost');
       var ghost = el('div', 'pc-card pc-ghost');
       g.dataset.pos = k;
       ghost.dataset.pos = k;
       g.setAttribute('aria-hidden', 'true');
       ghost.setAttribute('aria-hidden', 'true');
       deck.appendChild(g);
       deck.appendChild(ghost);
     }
     }


    root.classList.remove('is-error');
     root.classList.add('is-loaded');
     root.classList.add('is-loaded');


Line 361: Line 541:
       cards.forEach(function (_, i) {
       cards.forEach(function (_, i) {
         var d = el('button', 'pc-dot');
         var d = el('button', 'pc-dot');
         d.type = 'button';
         d.type = 'button';
         d.setAttribute('aria-label', 'Episode ' + (i + 1));
         d.setAttribute('aria-label', 'Item ' + (i + 1));
 
         d.addEventListener('click', function () {
         d.addEventListener('click', function () {
           active = i;
           active = i;
           layout();
           layout();
         });
         });
         dots.push(d);
         dots.push(d);
         wrap.appendChild(d);
         wrap.appendChild(d);
       });
       });


       nav.appendChild(arrow('Previous episode', 'm15 18-6-6 6-6', -1));
       nav.appendChild(arrow('Previous item', 'm15 18-6-6 6-6', -1));
       nav.appendChild(wrap);
       nav.appendChild(wrap);
       nav.appendChild(arrow('Next episode', 'm9 18 6-6-6-6', 1));
       nav.appendChild(arrow('Next item', 'm9 18 6-6-6-6', 1));
 
      // Register vertical swipe handlers once per deck.
      if (!deck.dataset.pcSwipeInit) {
        deck.dataset.pcSwipeInit = '1';
 
        var startY = null;
        var startX = null;
 
        deck.addEventListener('pointerdown', function (e) {
          if (e.pointerType === 'mouse' && e.button !== 0) return;
          startY = e.clientY;
          startX = e.clientX;
        });
 
        deck.addEventListener('pointerup', function (e) {
          if (startY === null || startX === null) return;
 
          var dy = e.clientY - startY;
          var dx = e.clientX - startX;
 
          startY = null;
          startX = null;


      var sx = null;
          // Navigate only when the swipe is mainly vertical.
      deck.addEventListener('pointerdown', function (e) { sx = e.clientX; });
          if (Math.abs(dy) > 45 && Math.abs(dy) > Math.abs(dx)) {
      deck.addEventListener('pointerup', function (e) {
            go(dy < 0 ? 1 : -1);
        if (sx === null) return;
          }
        var dx = e.clientX - sx;
        });
        sx = null;
 
         if (Math.abs(dx) > 45) go(dx < 0 ? 1 : -1);
        deck.addEventListener('pointercancel', function () {
       });
          startY = null;
          startX = null;
         });
       }
     }
     }


     layout();
     layout();
   }
   }
  /* ---------- Error state ---------- */


   function renderError() {
   function renderError() {
     root.classList.add('is-error');
     root.classList.add('is-error');
     deck.innerHTML = '';
     deck.innerHTML = '';
     var p = el('p', 'pc-error', 'Couldn\u2019t load episodes right now. ');
    nav.innerHTML = '';
 
     var p = el(
      'p',
      'pc-error',
      'Couldn’t load podcasts or videos right now. '
    );
 
     var href = safeUrl(page);
     var href = safeUrl(page);
     if (href) {
     if (href) {
       var a = el('a', '', 'Listen on RSS.com');
       var a = el('a', '', 'Open podcast page');
       a.href = href;
       a.href = href;
       a.target = '_blank';
       a.target = '_blank';
       a.rel = 'noopener';
       a.rel = 'noopener noreferrer';
       p.appendChild(a);
       p.appendChild(a);
     }
     }
     deck.appendChild(p);
     deck.appendChild(p);
   }
   }


   loadEpisodes().then(render, renderError);
   /* ---------- Load all sources independently ---------- */
 
  function loadAllContent() {
    var tasks = [];
 
    if (safeUrl(feed)) {
      tasks.push(
        loadEpisodes().catch(function (err) {
          console.warn('[Podcast deck] Podcast feed failed:', err);
          return [];
        })
      );
    }
 
    channels.forEach(function (channelId) {
      tasks.push(
        loadYouTubeChannel(channelId).catch(function (err) {
          console.warn(
            '[Podcast deck] YouTube channel failed:',
            channelId,
            err
          );
          return [];
        })
      );
    });
 
    if (!tasks.length) {
      return Promise.reject(new Error('No feeds configured'));
    }
 
    return Promise.all(tasks).then(function (results) {
      var combined = [].concat.apply([], results);
      combined = normalize(combined);
 
      if (!combined.length) {
        throw new Error('All configured feeds failed or were empty');
      }
 
      return combined;
    });
  }
 
  loadAllContent().then(render).catch(function (err) {
    console.warn('[Podcast deck] No content could be loaded:', err);
    renderError();
  });
});
});


Line 511: Line 776:
});
});


     document.addEventListener( 'pointermove', function ( e ) {
/* =====================================
         if ( e.pointerType !== 'mouse' || reduce.matches ) { return; }
  RANDOM GIF PICKER - GIF LOADING
         var el = e.target.closest && e.target.closest( SEL );
===================================== */
         if ( !el ) { return; }
 
        var r = el.getBoundingClientRect();
(function () {
        var x = ( e.clientX - r.left ) / r.width - 0.5;   // -0.5 .. 0.5
     var selector = '#random-gif-picker';
         var y = ( e.clientY - r.top ) / r.height - 0.5;
    var excluded = [24, 29, 35];
        el.classList.add( 'is-hovering' );
 
         el.style.setProperty( '--ry', ( x * MAX_TILT * 2 ) + 'deg' );
    function getGifUrl(number) {
         el.style.setProperty( '--rx', ( -y * MAX_TILT * 2 ) + 'deg' );
        return mw.util.getUrl(
     } );
            'Special:Redirect/file/' + number + '.gif'
        );
    }
 
    function setGif(picker, url) {
         if (picker.tagName === 'IMG') {
            picker.src = url;
            return;
        }
 
        var image = picker.querySelector('img');
 
        if (image) {
            image.src = url;
            return;
        }
 
        picker.style.backgroundImage = 'url("' + url + '")';
    }
 
    function loadRandomGif(picker) {
         var previous = parseInt(
            picker.dataset.lastGifNumber,
            10
        );
 
        var candidates = [];
 
        for (var i = 1; i <= 100; i++) {
            if (
                excluded.indexOf(i) === -1 &&
                i !== previous
            ) {
                candidates.push(i);
            }
        }
 
        for (var j = candidates.length - 1; j > 0; j--) {
            var k = Math.floor(Math.random() * (j + 1));
            var temp = candidates[j];
            candidates[j] = candidates[k];
            candidates[k] = temp;
        }
 
        picker._gifLoadToken =
            (picker._gifLoadToken || 0) + 1;
 
        var token = picker._gifLoadToken;
        var index = 0;
 
        // Show placeholder immediately.
        picker.classList.add('is-gif-loading');
 
         function tryNext() {
            if (
                token !== picker._gifLoadToken ||
                !picker.isConnected
            ) {
                return;
            }
 
            if (index >= candidates.length) {
                picker.classList.remove('is-gif-loading');
 
                console.warn(
                    '[GIF Picker] Could not find a working GIF.'
                );
                return;
            }
 
            var number = candidates[index++];
            var url = getGifUrl(number);
            var probe = new Image();
 
            probe.onload = function () {
                if (
                    token !== picker._gifLoadToken ||
                    !picker.isConnected
                ) {
                    return;
                }
 
                setGif(picker, url);
 
                picker.dataset.lastGifNumber = number;
 
                // Remove placeholder once GIF is ready.
                picker.classList.remove('is-gif-loading');
            };
 
            probe.onerror = tryNext;
            probe.src = url;
        }
 
        tryNext();
    }
 
function initializePicker() {
    document.querySelectorAll(selector).forEach(function (picker) {
 
        if (picker.dataset.gifPickerInit === '1') {
            return;
        }
 
         picker.dataset.gifPickerInit = '1';
 
        // Clean up after the bounce finishes.
        picker.addEventListener('animationend', function (event) {
 
            if (
                event.target === picker &&
                event.animationName === 'gif-picker-bounce'
            ) {
                picker.classList.remove('is-gif-bouncing');
            }
 
        });
 
        // Click handler.
        picker.addEventListener('click', function (event) {
 
            // Prevent navigation if the image is inside a link.
            if (picker.closest('a')) {
                event.preventDefault();
            }
 
            // Restart animation, including on repeated clicks.
            picker.classList.remove('is-gif-bouncing');
 
            void picker.offsetWidth;
 
            picker.classList.add('is-gif-bouncing');
 
            // Load a new random GIF.
            loadRandomGif(picker);
 
         });
 
        // Initial GIF.
      loadRandomGif(picker);
 
    });
}
 
    if (window.mw && mw.hook) {
        mw.hook('wikipage.content').add(initializePicker);
    }
 
    if (document.readyState === 'loading') {
        document.addEventListener(
            'DOMContentLoaded',
            initializePicker
        );
    } else {
        initializePicker();
    }
 
})();
 
 
/* =====================================
  RANDOM GIF PICKER - MOUSE INTERACTION
===================================== */
 
(function () {
    var selector = '#random-gif-picker';
 
    function resetPicker(picker) {
        if (!picker) return;
 
         picker.style.setProperty('--tilt-x', '0deg');
        picker.style.setProperty('--tilt-y', '0deg');
 
        picker.classList.remove('is-pointer-over');
     }
 
    function initializeTilt() {
        document.querySelectorAll(selector).forEach(function (picker) {
 
            if (picker.dataset.gifTiltInit === '1') return;
            picker.dataset.gifTiltInit = '1';
 
            // CURSOR FOLLOW + 3D TILT
            picker.addEventListener('pointermove', function (e) {
                if (e.pointerType === 'touch') return;
 
                var rect = picker.getBoundingClientRect();
 
                if (!rect.width || !rect.height) return;


    document.addEventListener( 'pointerout', function ( e ) {
                var x = (e.clientX - rect.left) / rect.width;
        var el = e.target.closest && e.target.closest( SEL );
                var y = (e.clientY - rect.top) / rect.height;
        if ( !el || el.contains( e.relatedTarget ) ) { return; }
        el.classList.remove( 'is-hovering' );
        el.style.setProperty( '--rx', '0deg' );
        el.style.setProperty( '--ry', '0deg' );
    } );


    document.addEventListener( 'click', function ( e ) {
                x = Math.max(0, Math.min(1, x));
        var el = e.target.closest && e.target.closest( SEL );
                y = Math.max(0, Math.min(1, y));
        if ( !el || reduce.matches ) { return; }


        // restart the animation even on rapid repeat clicks
                var tiltX = (x - 0.5) * 14;
        el.classList.remove( 'is-pressed' );
                var tiltY = (0.5 - y) * 14;
        void el.offsetWidth;
        el.classList.add( 'is-pressed' );
        el.addEventListener( 'animationend', function done() {
            el.classList.remove( 'is-pressed' );
            el.removeEventListener( 'animationend', done );
        } );


/* Magnetic tilt for .fedo-btn */
                picker.style.setProperty(
( function () {
                    '--pointer-x',
'use strict';
                    (x * 100) + '%'
                );


var RANGE = 140;      // px from the button's edge where the pull starts
                picker.style.setProperty(
var MAX_TILT = 14;    // max rotation in degrees
                    '--pointer-y',
var PULL = 6;          // max px drift toward the cursor
                    (y * 100) + '%'
var EASE = 0.18;      // 0-1, higher = snappier
                );
var PERSPECTIVE = 600; // px, lower = stronger 3D


// Skip only on touch-only devices (no mouse to follow)
                picker.style.setProperty('--tilt-x', tiltX + 'deg');
if ( window.matchMedia( '(any-hover: none)' ).matches ) {
                picker.style.setProperty('--tilt-y', tiltY + 'deg');
return;
}


var mouse = null;
                picker.classList.add('is-pointer-over');
var running = false;
            }, { passive: true });
var states = new WeakMap();


function clamp( v, min, max ) {
            // SMOOTH RESET WHEN CURSOR LEAVES
return Math.max( min, Math.min( max, v ) );
            picker.addEventListener('pointerleave', function () {
}
                resetPicker(picker);
            });


function step() {
        });
var active = !!mouse;
    }


document.querySelectorAll( '.fedo-btn' ).forEach( function ( el ) {
    // INITIALIZE THROUGH MEDIAWIKI
var s = states.get( el );
    if (window.mw && mw.hook) {
if ( !s ) {
        mw.hook('wikipage.content').add(initializeTilt);
s = { rx: 0, ry: 0, tx: 0, ty: 0 };
    }
states.set( el, s );
// Transforms don't apply to plain inline elements
if ( getComputedStyle( el ).display === 'inline' ) {
el.style.display = 'inline-block';
}
}


// Let the click animation take over while pressed
    if (document.readyState === 'loading') {
if ( el.matches( ':active' ) ) {
        document.addEventListener('DOMContentLoaded', initializeTilt);
s.rx = s.ry = s.tx = s.ty = 0;
    } else {
el.style.removeProperty( 'transform' );
        initializeTilt();
return;
    }
}


var target = { rx: 0, ry: 0, tx: 0, ty: 0 };
    // ORIGINAL SMOOTH CLICK BOUNCE + RIPPLE
    document.addEventListener('pointerdown', function (e) {
        if (e.button !== 0) return;


if ( mouse ) {
        var picker = e.target.closest
var r = el.getBoundingClientRect();
            ? e.target.closest(selector)
var dx = mouse.x - ( r.left + r.width / 2 );
            : null;
var dy = mouse.y - ( r.top + r.height / 2 );


// Distance from the cursor to the button's edge (0 when over it)
        if (!picker) return;
var ex = Math.max( Math.abs( dx ) - r.width / 2, 0 );
var ey = Math.max( Math.abs( dy ) - r.height / 2, 0 );
var dist = Math.sqrt( ex * ex + ey * ey );


if ( dist < RANGE ) {
        // ORIGINAL ADDITIVE SCALE ANIMATION
var power = 1 - dist / RANGE;
        if (typeof picker.animate === 'function') {
var nx = clamp( dx / ( r.width / 2 + RANGE / 2 ), -1, 1 );
            try {
var ny = clamp( dy / ( r.height / 2 + RANGE / 2 ), -1, 1 );
                picker.animate(
                    [
                        { scale: '1' },
                        { scale: '.92', offset: .25 },
                        { scale: '1.055', offset: .60 },
                        { scale: '1' }
                    ],
                    {
                        duration: 320,
                        easing: 'cubic-bezier(.2,.8,.3,1)',
                        fill: 'none',
                        composite: 'add'
                    }
                );
            } catch (err) {
                // Fallback for browsers without additive animation.
                picker.style.scale = '.93';


target.ry = nx * MAX_TILT * power;
                requestAnimationFrame(function () {
target.rx = -ny * MAX_TILT * power;
                    picker.style.scale = '1';
target.tx = nx * PULL * power;
                });
target.ty = ny * PULL * power;
            }
}
        }
}


var moving = false;
        // RIPPLE
[ 'rx', 'ry', 'tx', 'ty' ].forEach( function ( k ) {
        if (picker.tagName !== 'IMG') {
s[ k ] += ( target[ k ] - s[ k ] ) * EASE;
            var rect = picker.getBoundingClientRect();
if ( Math.abs( target[ k ] - s[ k ] ) > 0.01 ) {
            var ripple = document.createElement('span');
moving = true;
}
} );


if ( moving || target.rx || target.ry ) {
            ripple.className = 'gif-picker-ripple';
active = true;
            ripple.setAttribute('aria-hidden', 'true');
el.style.setProperty( 'transform',
'perspective(' + PERSPECTIVE + 'px) ' +
'translate3d(' + s.tx.toFixed( 2 ) + 'px,' + s.ty.toFixed( 2 ) + 'px,0) ' +
'rotateX(' + s.rx.toFixed( 2 ) + 'deg) ' +
'rotateY(' + s.ry.toFixed( 2 ) + 'deg)',
'important' );
} else {
s.rx = s.ry = s.tx = s.ty = 0;
el.style.removeProperty( 'transform' );
}
} );


if ( active ) {
            ripple.style.left = (e.clientX - rect.left) + 'px';
requestAnimationFrame( step );
            ripple.style.top = (e.clientY - rect.top) + 'px';
} else {
running = false;
}
}


function start() {
            picker.appendChild(ripple);
if ( !running ) {
running = true;
requestAnimationFrame( step );
}
}


document.addEventListener( 'mousemove', function ( e ) {
            ripple.addEventListener('animationend', function () {
mouse = { x: e.clientX, y: e.clientY };
                ripple.remove();
start();
            }, { once: true });
}, { passive: true } );
        }
    });


document.documentElement.addEventListener( 'mouseleave', function () {
})();
mouse = null;
start();
} );
}() );

Latest revision as of 10:47, 3 December 2026

/* =========================================================
   PODCAST + YOUTUBE DECK
   - Combines podcast RSS and multiple YouTube channel feeds
   - Shows the 3 newest items across all successful sources
   - Per-source fallback and error handling
   - Preserves existing .pc-* card and carousel styling
   ========================================================= */

mw.hook('wikipage.content').add(function ($content) {
  var root = $content.find('#pc-podcast')[0];

  if (!root || root.dataset.pcInit === '1') return;
  root.dataset.pcInit = '1';

  var feed = root.dataset.feed || '';
  var page = root.dataset.page || '';
  var channels = (root.dataset.channels || '')
    .split(',')
    .map(function (id) { return id.trim(); })
    .filter(function (id) {
      return /^[A-Za-z0-9_-]+$/.test(id);
    });

  var deck = root.querySelector('.pc-deck');
  var nav = root.querySelector('.pc-nav');

  if (!deck || !nav) return;

  var cards = [];
  var dots = [];
  var active = 0;

  /* ---------- Utilities ---------- */

  function el(tag, cls, text) {
    var e = document.createElement(tag);
    if (cls) e.className = cls;
    if (text != null) e.textContent = text;
    return e;
  }

  function safeUrl(u) {
    return /^https?:\/\//i.test(u || '') ? u : '';
  }

  function txt(node, tag) {
    var n = node.getElementsByTagName(tag)[0];
    return n ? n.textContent.trim() : '';
  }

  function plain(html) {
    return new DOMParser()
      .parseFromString(html || '', 'text/html')
      .body.textContent
      .replace(/\s+/g, ' ')
      .trim();
  }

  function parseDate(s) {
    if (!s) return new Date(NaN);

    var d = new Date(s);

    if (isNaN(d)) {
      d = new Date(String(s).replace(' ', 'T') + 'Z');
    }

    return d;
  }

  function dateValue(s) {
    var d = parseDate(s);
    return isNaN(d) ? 0 : d.getTime();
  }

  function fmtDate(s) {
    var d = parseDate(s);

    return isNaN(d) ? '' : d.toLocaleDateString(
      undefined,
      {
        month: 'short',
        day: 'numeric',
        year: 'numeric'
      }
    );
  }

  function fmtDur(v) {
    if (!v) return '';

    if (v.indexOf(':') > -1) {
      return v.replace(/^00:/, '').replace(/^0(\d:)/, '$1');
    }

    var s = parseInt(v, 10);
    if (!s) return '';

    var h = Math.floor(s / 3600);
    var m = Math.floor((s % 3600) / 60);
    var sec = s % 60;

    return (h ? h + ':' + ('0' + m).slice(-2) : m)
      + ':' + ('0' + sec).slice(-2);
  }

  function okText(r) {
    if (!r.ok) throw new Error('HTTP ' + r.status);
    return r.text();
  }

  function okJson(r) {
    if (!r.ok) throw new Error('HTTP ' + r.status);
    return r.json();
  }

  /* ---------- Podcast RSS parser ---------- */

  function fromXml(xml) {
    var doc = new DOMParser().parseFromString(
      xml,
      'application/xml'
    );

    if (doc.getElementsByTagName('parsererror').length) {
      throw new Error('Invalid podcast XML');
    }

    var chImg = doc.getElementsByTagName('itunes:image')[0];
    var chCover = chImg ? chImg.getAttribute('href') : '';

    return Array.prototype.map.call(
      doc.getElementsByTagName('item'),
      function (it) {
        var img = it.getElementsByTagName('itunes:image')[0];
        var season = txt(it, 'itunes:season');
        var episode = txt(it, 'itunes:episode');

        return {
          title: txt(it, 'title'),
          link: txt(it, 'link'),
          date: txt(it, 'pubDate'),
          dur: fmtDur(txt(it, 'itunes:duration')),
          tag: episode
            ? (season ? 'S' + season + ' · ' : '') + 'E' + episode
            : 'Podcast',
          desc: plain(txt(it, 'description')),
          cover: (img && img.getAttribute('href')) || chCover
        };
      }
    );
  }

  /* ---------- YouTube Atom/RSS parser ---------- */

  function fromYouTubeXml(xml) {
    var doc = new DOMParser().parseFromString(
      xml,
      'application/xml'
    );

    if (doc.getElementsByTagName('parsererror').length) {
      throw new Error('Invalid YouTube XML');
    }

    return Array.prototype.map.call(
      doc.getElementsByTagName('entry'),
      function (entry) {
        var videoId = txt(entry, 'yt:videoId');
        var links = entry.getElementsByTagName('link');
        var link = '';

        // Prefer the normal video page, not a related link.
        for (var i = 0; i < links.length; i++) {
          var rel = links[i].getAttribute('rel');
          var href = links[i].getAttribute('href') || '';

          if ((!rel || rel === 'alternate') && href) {
            link = href;
            break;
          }
        }

        if (!link && videoId) {
          link = 'https://www.youtube.com/watch?v=' + videoId;
        }

        var group = entry.getElementsByTagName('media:group')[0];
        var thumbnail = group
          ? group.getElementsByTagName('media:thumbnail')[0]
          : null;

        var description = group
          ? txt(group, 'media:description')
          : '';

        return {
          title: txt(entry, 'title'),
          link: link,
          date: txt(entry, 'published') || txt(entry, 'updated'),
          dur: '',
          tag: 'YouTube',
          desc: plain(description),
          cover: thumbnail
            ? thumbnail.getAttribute('url')
            : videoId
              ? 'https://i.ytimg.com/vi/' + videoId + '/hqdefault.jpg'
              : ''
        };
      }
    );
  }

  /* ---------- JSON feed fallback ---------- */

  function fromJson(j) {
    var chCover = j.feed && j.feed.image;

    // Some services return a feed image as an object.
    if (chCover && typeof chCover === 'object') {
      chCover = chCover.url || chCover.href || '';
    }

    return (j.items || []).map(function (it) {
      var enclosure = it.enclosure;
      var cover = it.thumbnail || chCover || '';

      if (!cover && enclosure && typeof enclosure === 'object') {
        cover = enclosure.link || enclosure.url || '';
      }

      return {
        title: it.title || '',
        link: it.link || '',
        date: it.pubDate || it.published || it.date || '',
        dur: fmtDur(it.itunes && it.itunes.duration
          ? it.itunes.duration
          : it.duration || ''),
        tag: 'Podcast',
        desc: plain(it.description || it.content || ''),
        cover: cover
      };
    });
  }



/* ---------- Feed loading and CORS fallbacks ---------- */

function normalize(list) {
  return (list || []).filter(function (item) {
    return item && item.title;
  });
}

function fetchText(url) {
  return fetch(url).then(function (response) {
    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }
    return response.text();
  });
}

function fetchJson(url) {
  return fetch(url).then(function (response) {
    if (!response.ok) {
      throw new Error('HTTP ' + response.status);
    }
    return response.json();
  });
}

/* Parse RSS2JSON responses for podcasts and YouTube. */
function fromConvertedJson(json, kind) {
  if (json.status && json.status !== 'ok') {
    throw new Error(json.message || 'Feed conversion failed');
  }

  var feedCover = json.feed && json.feed.image;

  if (feedCover && typeof feedCover === 'object') {
    feedCover = feedCover.url || feedCover.href || '';
  }

  return (json.items || []).map(function (item) {
    var link = item.link || '';
    var videoId = '';

    if (kind === 'youtube') {
      var match =
        link.match(/[?&]v=([^&]+)/) ||
        link.match(/youtu\.be\/([^?&/]+)/) ||
        link.match(/\/shorts\/([^?&/]+)/);

      if (match) videoId = match[1];
    }

    var cover = item.thumbnail || feedCover || '';

    if (!cover && videoId) {
      cover = 'https://i.ytimg.com/vi/'
        + videoId + '/hqdefault.jpg';
    }

    var duration = item.itunes && item.itunes.duration
      ? item.itunes.duration
      : item.duration || '';

    return {
      title: item.title || '',
      link: link,
      date: item.pubDate || item.published || item.date || '',
      dur: kind === 'podcast' ? fmtDur(String(duration)) : '',
      tag: kind === 'youtube' ? 'YouTube' : 'Podcast',
      desc: plain(item.description || item.content || ''),
      cover: cover
    };
  });
}

/*
 * jsonFirst=true: try the converter first for YouTube,
 * because direct access is blocked by browser CORS.
 *
 * No CorsProxy request is made here because it returned 401.
 */
function loadFeed(url, xmlParser, kind, jsonFirst) {
  var encoded = encodeURIComponent(url);

  var direct = function () {
    return fetchText(url).then(xmlParser);
  };

  var converted = function () {
    return fetchJson(
      'https://api.rss2json.com/v1/api.json?rss_url='
      + encoded
    ).then(function (json) {
      return fromConvertedJson(json, kind);
    });
  };

var corsDev = function () {
  return fetchText(
    'https://proxy.cors.dev/' + url
  ).then(xmlParser);
};

var allOrigins = function () {
  return fetchText(
    'https://api.allorigins.win/raw?url=' + encoded
  ).then(xmlParser);
};

var sources = jsonFirst
  ? [converted, corsDev, allOrigins, direct]
  : [direct, corsDev, allOrigins, converted];
  return sources.reduce(function (previous, source) {
    return previous.catch(function () {
      return source().then(function (list) {
        list = normalize(list);

        if (!list.length) {
          throw new Error('No usable feed items');
        }

        return list;
      });
    });
  }, Promise.reject(new Error('Starting feed fallbacks')));
}

function loadEpisodes() {
  if (!safeUrl(feed)) {
    return Promise.reject(new Error('Invalid podcast feed URL'));
  }

  return loadFeed(feed, fromXml, 'podcast', false);
}

function loadYouTubeChannel(channelId) {
  var url =
    'https://www.youtube.com/feeds/videos.xml?channel_id='
    + encodeURIComponent(channelId);

  return loadFeed(url, fromYouTubeXml, 'youtube', true);
}


  /* ---------- Card creation ---------- */

  function buildCard(ep) {
    var c = el('article', 'pc-card');
    var cover = el('div', 'pc-cover');

    if (safeUrl(ep.cover)) {
      var img = el('img');
      img.alt = '';
      img.loading = 'lazy';
      img.onerror = function () {
        cover.textContent = ep.tag === 'YouTube' ? '▶️' : '🎙️';
      };
      img.src = ep.cover;
      cover.appendChild(img);
    } else {
      cover.textContent = ep.tag === 'YouTube' ? '▶️' : '🎙️';
    }

    var body = el('div', 'pc-body');
    var meta = el('div', 'pc-meta');

    if (ep.tag) {
      meta.appendChild(el('span', 'pc-pill pc-pill-strong', ep.tag));
    }

    var ds = fmtDate(ep.date);
    if (ds) meta.appendChild(el('span', 'pc-pill', ds));
    if (ep.dur) meta.appendChild(el('span', 'pc-pill', ep.dur));

    if (meta.children.length) body.appendChild(meta);

    var href = safeUrl(ep.link) || safeUrl(page);
    var title = el('div', 'pc-title');

    title.setAttribute('role', 'heading');
    title.setAttribute('aria-level', '3');

    var a = el('a', '', ep.title || 'Untitled episode');

    if (href) {
      a.href = href;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
    }

    title.appendChild(a);
    body.appendChild(title);
    body.appendChild(el('p', 'pc-desc', ep.desc || ''));

    c.appendChild(cover);
    c.appendChild(body);

    if (href) {
      var o = el('div', 'mc-open');
      var oa = el('a');

      oa.href = href;
      oa.target = '_blank';
      oa.rel = 'noopener noreferrer';
      oa.title = ep.tag === 'YouTube' ? 'Watch video' : 'Open episode';
      oa.setAttribute(
        'aria-label',
        ep.tag === 'YouTube' ? 'Watch video' : 'Open episode'
      );

      oa.appendChild(el('span', 'mc-open-icon'));
      o.appendChild(oa);
      c.appendChild(o);
    }

    return c;
  }

  /* ---------- Carousel behavior ---------- */

  function layout() {
    var n = cards.length;
    if (!n) return;

    cards.forEach(function (c, i) {
      var pos = (i - active + n) % n;

      c.dataset.pos = pos;
      c.inert = pos !== 0;
      c.setAttribute('aria-hidden', pos ? 'true' : 'false');
    });

    dots.forEach(function (d, i) {
      d.setAttribute('aria-current', i === active ? 'true' : 'false');
    });
  }

  function go(delta) {
  if (!cards.length) return;

  active = (active + delta + cards.length) % cards.length;

  layout();
}

  function arrow(label, path, delta) {
    var b = el('button', 'pc-btn');
    b.type = 'button';
    b.setAttribute('aria-label', label);

    b.innerHTML =
      '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
      'stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
      '<path d="' + path + '"/></svg>';

    b.addEventListener('click', function () {
      go(delta);
    });

    return b;
  }

  function render(list) {
    list = list
      .sort(function (a, b) {
        return dateValue(b.date) - dateValue(a.date);
      })
      .slice(0, 5);

    deck.innerHTML = '';
    nav.innerHTML = '';
    cards = [];
    dots = [];
    active = 0;

    list.forEach(function (ep) {
      var card = buildCard(ep);
      cards.push(card);
      deck.appendChild(card);
    });

    for (var k = cards.length; k < 3; k++) {
      var ghost = el('div', 'pc-card pc-ghost');
      ghost.dataset.pos = k;
      ghost.setAttribute('aria-hidden', 'true');
      deck.appendChild(ghost);
    }

    root.classList.remove('is-error');
    root.classList.add('is-loaded');

    if (cards.length > 1) {
      var wrap = el('div', 'pc-dots');

      cards.forEach(function (_, i) {
        var d = el('button', 'pc-dot');

        d.type = 'button';
        d.setAttribute('aria-label', 'Item ' + (i + 1));

        d.addEventListener('click', function () {
          active = i;
          layout();
        });

        dots.push(d);
        wrap.appendChild(d);
      });

      nav.appendChild(arrow('Previous item', 'm15 18-6-6 6-6', -1));
      nav.appendChild(wrap);
      nav.appendChild(arrow('Next item', 'm9 18 6-6-6-6', 1));

      // Register vertical swipe handlers once per deck.
      if (!deck.dataset.pcSwipeInit) {
        deck.dataset.pcSwipeInit = '1';

        var startY = null;
        var startX = null;

        deck.addEventListener('pointerdown', function (e) {
          if (e.pointerType === 'mouse' && e.button !== 0) return;
          startY = e.clientY;
          startX = e.clientX;
        });

        deck.addEventListener('pointerup', function (e) {
          if (startY === null || startX === null) return;

          var dy = e.clientY - startY;
          var dx = e.clientX - startX;

          startY = null;
          startX = null;

          // Navigate only when the swipe is mainly vertical.
          if (Math.abs(dy) > 45 && Math.abs(dy) > Math.abs(dx)) {
            go(dy < 0 ? 1 : -1);
          }
        });

        deck.addEventListener('pointercancel', function () {
          startY = null;
          startX = null;
        });
      }
    }

    layout();
  }
  /* ---------- Error state ---------- */

  function renderError() {
    root.classList.add('is-error');

    deck.innerHTML = '';
    nav.innerHTML = '';

    var p = el(
      'p',
      'pc-error',
      'Couldn’t load podcasts or videos right now. '
    );

    var href = safeUrl(page);

    if (href) {
      var a = el('a', '', 'Open podcast page');
      a.href = href;
      a.target = '_blank';
      a.rel = 'noopener noreferrer';
      p.appendChild(a);
    }

    deck.appendChild(p);
  }

  /* ---------- Load all sources independently ---------- */

  function loadAllContent() {
    var tasks = [];

    if (safeUrl(feed)) {
      tasks.push(
        loadEpisodes().catch(function (err) {
          console.warn('[Podcast deck] Podcast feed failed:', err);
          return [];
        })
      );
    }

    channels.forEach(function (channelId) {
      tasks.push(
        loadYouTubeChannel(channelId).catch(function (err) {
          console.warn(
            '[Podcast deck] YouTube channel failed:',
            channelId,
            err
          );
          return [];
        })
      );
    });

    if (!tasks.length) {
      return Promise.reject(new Error('No feeds configured'));
    }

    return Promise.all(tasks).then(function (results) {
      var combined = [].concat.apply([], results);
      combined = normalize(combined);

      if (!combined.length) {
        throw new Error('All configured feeds failed or were empty');
      }

      return combined;
    });
  }

  loadAllContent().then(render).catch(function (err) {
    console.warn('[Podcast deck] No content could be loaded:', err);
    renderError();
  });
});


/* =========================================================
   3. NATIVE AUDIO PLAYER (unchanged)
   ========================================================= */
mw.hook('wikipage.content').add(function ($content) {
    $content.find('.infobox-native-audio').each(function () {
        if (this.dataset.audioInitialized === '1') {
            return;
        }

        const src = this.dataset.src;

        if (!src) {
            return;
        }

        const audio = document.createElement('audio');
        audio.preload = 'metadata';
        audio.src = src;

        const player = document.createElement('div');
        player.className = 'custom-audio-player';

        player.innerHTML = `
            <button class="audio-play" type="button" aria-label="Play">▶</button>

            <div class="audio-progress-container">
                <input class="audio-progress" type="range" min="0" max="100" value="0">
            </div>

            <span class="audio-time">0:00 / 0:00</span>

            <button class="audio-volume" type="button" aria-label="Mute">🔊</button>
        `;

        const playButton = player.querySelector('.audio-play');
        const progress = player.querySelector('.audio-progress');
        const time = player.querySelector('.audio-time');
        const volumeButton = player.querySelector('.audio-volume');

        function formatTime(seconds) {
            if (!isFinite(seconds)) {
                return '0:00';
            }

            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60)
                .toString()
                .padStart(2, '0');

            return `${minutes}:${secs}`;
        }

        function updateTime() {
            progress.value = audio.duration
                ? (audio.currentTime / audio.duration) * 100
                : 0;

            time.textContent =
                `${formatTime(audio.currentTime)} / ${formatTime(audio.duration)}`;
        }

        playButton.addEventListener('click', function () {
            if (audio.paused) {
                audio.play();
            } else {
                audio.pause();
            }
        });

        audio.addEventListener('play', function () {
            playButton.textContent = '❚❚';
            playButton.setAttribute('aria-label', 'Pause');
        });

        audio.addEventListener('pause', function () {
            playButton.textContent = '▶';
            playButton.setAttribute('aria-label', 'Play');
        });

        audio.addEventListener('timeupdate', updateTime);
        audio.addEventListener('loadedmetadata', updateTime);

        progress.addEventListener('input', function () {
            if (audio.duration) {
                audio.currentTime =
                    (progress.value / 100) * audio.duration;
            }
        });

        volumeButton.addEventListener('click', function () {
            audio.muted = !audio.muted;
            volumeButton.textContent = audio.muted ? '🔇' : '🔊';
        });

        audio.addEventListener('ended', function () {
            playButton.textContent = '▶';
            progress.value = 0;
        });

        this.replaceChildren(audio, player);
        this.dataset.audioInitialized = '1';
    });
});

/* =====================================
   RANDOM GIF PICKER - GIF LOADING
===================================== */

(function () {
    var selector = '#random-gif-picker';
    var excluded = [24, 29, 35];

    function getGifUrl(number) {
        return mw.util.getUrl(
            'Special:Redirect/file/' + number + '.gif'
        );
    }

    function setGif(picker, url) {
        if (picker.tagName === 'IMG') {
            picker.src = url;
            return;
        }

        var image = picker.querySelector('img');

        if (image) {
            image.src = url;
            return;
        }

        picker.style.backgroundImage = 'url("' + url + '")';
    }

    function loadRandomGif(picker) {
        var previous = parseInt(
            picker.dataset.lastGifNumber,
            10
        );

        var candidates = [];

        for (var i = 1; i <= 100; i++) {
            if (
                excluded.indexOf(i) === -1 &&
                i !== previous
            ) {
                candidates.push(i);
            }
        }

        for (var j = candidates.length - 1; j > 0; j--) {
            var k = Math.floor(Math.random() * (j + 1));
            var temp = candidates[j];
            candidates[j] = candidates[k];
            candidates[k] = temp;
        }

        picker._gifLoadToken =
            (picker._gifLoadToken || 0) + 1;

        var token = picker._gifLoadToken;
        var index = 0;

        // Show placeholder immediately.
        picker.classList.add('is-gif-loading');

        function tryNext() {
            if (
                token !== picker._gifLoadToken ||
                !picker.isConnected
            ) {
                return;
            }

            if (index >= candidates.length) {
                picker.classList.remove('is-gif-loading');

                console.warn(
                    '[GIF Picker] Could not find a working GIF.'
                );
                return;
            }

            var number = candidates[index++];
            var url = getGifUrl(number);
            var probe = new Image();

            probe.onload = function () {
                if (
                    token !== picker._gifLoadToken ||
                    !picker.isConnected
                ) {
                    return;
                }

                setGif(picker, url);

                picker.dataset.lastGifNumber = number;

                // Remove placeholder once GIF is ready.
                picker.classList.remove('is-gif-loading');
            };

            probe.onerror = tryNext;
            probe.src = url;
        }

        tryNext();
    }

function initializePicker() {
    document.querySelectorAll(selector).forEach(function (picker) {

        if (picker.dataset.gifPickerInit === '1') {
            return;
        }

        picker.dataset.gifPickerInit = '1';

        // Clean up after the bounce finishes.
        picker.addEventListener('animationend', function (event) {

            if (
                event.target === picker &&
                event.animationName === 'gif-picker-bounce'
            ) {
                picker.classList.remove('is-gif-bouncing');
            }

        });

        // Click handler.
        picker.addEventListener('click', function (event) {

            // Prevent navigation if the image is inside a link.
            if (picker.closest('a')) {
                event.preventDefault();
            }

            // Restart animation, including on repeated clicks.
            picker.classList.remove('is-gif-bouncing');

            void picker.offsetWidth;

            picker.classList.add('is-gif-bouncing');

            // Load a new random GIF.
            loadRandomGif(picker);

        });

        // Initial GIF.
       loadRandomGif(picker);

    });
}

    if (window.mw && mw.hook) {
        mw.hook('wikipage.content').add(initializePicker);
    }

    if (document.readyState === 'loading') {
        document.addEventListener(
            'DOMContentLoaded',
            initializePicker
        );
    } else {
        initializePicker();
    }

})();


/* =====================================
   RANDOM GIF PICKER - MOUSE INTERACTION
===================================== */

(function () {
    var selector = '#random-gif-picker';

    function resetPicker(picker) {
        if (!picker) return;

        picker.style.setProperty('--tilt-x', '0deg');
        picker.style.setProperty('--tilt-y', '0deg');

        picker.classList.remove('is-pointer-over');
    }

    function initializeTilt() {
        document.querySelectorAll(selector).forEach(function (picker) {

            if (picker.dataset.gifTiltInit === '1') return;
            picker.dataset.gifTiltInit = '1';

            // CURSOR FOLLOW + 3D TILT
            picker.addEventListener('pointermove', function (e) {
                if (e.pointerType === 'touch') return;

                var rect = picker.getBoundingClientRect();

                if (!rect.width || !rect.height) return;

                var x = (e.clientX - rect.left) / rect.width;
                var y = (e.clientY - rect.top) / rect.height;

                x = Math.max(0, Math.min(1, x));
                y = Math.max(0, Math.min(1, y));

                var tiltX = (x - 0.5) * 14;
                var tiltY = (0.5 - y) * 14;

                picker.style.setProperty(
                    '--pointer-x',
                    (x * 100) + '%'
                );

                picker.style.setProperty(
                    '--pointer-y',
                    (y * 100) + '%'
                );

                picker.style.setProperty('--tilt-x', tiltX + 'deg');
                picker.style.setProperty('--tilt-y', tiltY + 'deg');

                picker.classList.add('is-pointer-over');
            }, { passive: true });

            // SMOOTH RESET WHEN CURSOR LEAVES
            picker.addEventListener('pointerleave', function () {
                resetPicker(picker);
            });

        });
    }

    // INITIALIZE THROUGH MEDIAWIKI
    if (window.mw && mw.hook) {
        mw.hook('wikipage.content').add(initializeTilt);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeTilt);
    } else {
        initializeTilt();
    }

    // ORIGINAL SMOOTH CLICK BOUNCE + RIPPLE
    document.addEventListener('pointerdown', function (e) {
        if (e.button !== 0) return;

        var picker = e.target.closest
            ? e.target.closest(selector)
            : null;

        if (!picker) return;

        // ORIGINAL ADDITIVE SCALE ANIMATION
        if (typeof picker.animate === 'function') {
            try {
                picker.animate(
                    [
                        { scale: '1' },
                        { scale: '.92', offset: .25 },
                        { scale: '1.055', offset: .60 },
                        { scale: '1' }
                    ],
                    {
                        duration: 320,
                        easing: 'cubic-bezier(.2,.8,.3,1)',
                        fill: 'none',
                        composite: 'add'
                    }
                );
            } catch (err) {
                // Fallback for browsers without additive animation.
                picker.style.scale = '.93';

                requestAnimationFrame(function () {
                    picker.style.scale = '1';
                });
            }
        }

        // RIPPLE
        if (picker.tagName !== 'IMG') {
            var rect = picker.getBoundingClientRect();
            var ripple = document.createElement('span');

            ripple.className = 'gif-picker-ripple';
            ripple.setAttribute('aria-hidden', 'true');

            ripple.style.left = (e.clientX - rect.left) + 'px';
            ripple.style.top = (e.clientY - rect.top) + 'px';

            picker.appendChild(ripple);

            ripple.addEventListener('animationend', function () {
                ripple.remove();
            }, { once: true });
        }
    });

})();