Jump to content

MediaWiki:Common.js: Difference between revisions

From Fedoverse Wiki, the free encyclopedia
No edit summary
No edit summary
Line 1: Line 1:
/* =========================================================
/* =========================================================
   2. PODCAST DECK
   PODCAST + YOUTUBE DECK
   Changes: runs inside mw.hook (DOM guaranteed), tries several
   - Combines podcast RSS and multiple YouTube channel feeds
   sources in order, falls through when a source returns an
   - Shows the 3 newest items across all successful sources
   empty list, and shows a link instead of staying blank.
  - 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) {
   var root = $content.find('#pc-podcast')[0];
   var root = $content.find('#pc-podcast')[0];
   if (!root || root.dataset.pcInit === '1') return;
   if (!root || root.dataset.pcInit === '1') return;
   root.dataset.pcInit = '1';
   root.dataset.pcInit = '1';


   var feed = root.dataset.feed, page = root.dataset.page;
   var feed = root.dataset.feed || '';
   var deck = root.querySelector('.pc-deck'), nav = root.querySelector('.pc-nav');
  var page = root.dataset.page || '';
   var cards = [], dots = [], active = 0;
  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) {
   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;


      return {
        var description = group
        title: txt(it, 'title'),
          ? txt(group, 'media:description')
        link: txt(it, 'link'),
          : '';
        date: txt(it, 'pubDate'),
 
        dur: fmtDur(txt(it, 'itunes:duration')),
        return {
        tag: e ? (s ? 'S' + s + ' · ' : '') + 'E' + e : '',
          title: txt(entry, 'title'),
        desc: plain(txt(it, 'description')),
          link: link,
        cover: (img && img.getAttribute('href')) || chCover
          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) {
   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(); }
  /* ---------- Feed fetching with fallbacks ---------- */
  function okJson(r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); }
 
   function normalize(list) {
    return (list || []).filter(function (item) {
      return item && item.title;
    });
  }


   function loadEpisodes() {
   function loadFeed(url, xmlParser) {
     var enc = encodeURIComponent(feed);
     var encoded = encodeURIComponent(url);
 
    // Try each source sequentially. A network error, invalid
    // response, or empty feed advances to the next source.
     var sources = [
     var sources = [
       function () { return fetch(feed).then(okText).then(fromXml); },
       function () {
       function () { return fetch('https://api.allorigins.win/raw?url=' + enc).then(okText).then(fromXml); },
        return fetch(url)
       function () { return fetch('https://api.rss2json.com/v1/api.json?rss_url=' + enc).then(okJson).then(fromJson); },
          .then(okText)
       function () { return fetch('https://corsproxy.io/?url=' + enc).then(okText).then(fromXml); }
          .then(xmlParser);
      },
       function () {
        return fetch(
          'https://api.allorigins.win/raw?url=' + encoded
        )
          .then(okText)
          .then(xmlParser);
      },
       function () {
        return fetch(
          'https://corsproxy.io/?url=' + encoded
        )
          .then(okText)
          .then(xmlParser);
      },
       function () {
        return fetch(
          'https://api.rss2json.com/v1/api.json?rss_url='
          + encoded
        )
          .then(okJson)
          .then(function (json) {
            if (json.status && json.status !== 'ok') {
              throw new Error('RSS conversion failed');
            }
            return fromJson(json);
          });
      }
     ];
     ];


    // Try each source in turn; an error OR an empty list moves on to the next
     return sources.reduce(function (previous, source) {
     return sources.reduce(function (p, src) {
       return previous.catch(function () {
       return p.catch(function () {
         return source().then(function (list) {
         return src().then(function (list) {
           list = normalize(list);
           list = list.filter(function (e) { return e.title; });
 
           if (!list.length) throw new Error('empty');
           if (!list.length) {
            throw new Error('Feed returned no usable items');
          }
 
           return list;
           return list;
         });
         });
       });
       });
     }, Promise.reject(new Error('start')));
     }, Promise.reject(new Error('Starting feed fallbacks')));
  }
 
  function loadEpisodes() {
    if (!safeUrl(feed)) {
      return Promise.reject(new Error('No valid podcast feed URL'));
    }
 
    return loadFeed(feed, fromXml).then(function (list) {
      // Keep podcast season and episode labels from the XML parser.
      return list;
    });
  }
 
  function loadYouTubeChannel(channelId) {
    var url =
      'https://www.youtube.com/feeds/videos.xml?channel_id='
      + encodeURIComponent(channelId);
 
    return loadFeed(url, fromYouTubeXml).then(function (list) {
      return list.map(function (video) {
        // Retain a consistent label for every video.
        video.tag = 'YouTube';
        return video;
      });
    });
   }
   }
  /* ---------- Card creation ---------- */


   function buildCard(ep) {
   function buildCard(ep) {
Line 113: Line 342:
       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 123: Line 354:
     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 150: Line 388:
       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 162: Line 405:
     return c;
     return c;
   }
   }
  /* ---------- Carousel behavior ---------- */


   function layout() {
   function layout() {
Line 169: Line 414:
     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 180: Line 426:


   function go(delta) {
   function go(delta) {
    if (!cards.length) return;
     active = (active + delta + cards.length) % cards.length;
     active = (active + delta + cards.length) % cards.length;
     layout();
     layout();
Line 188: Line 435:
     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 195: Line 450:
   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) {
        return dateValue(b.date) - dateValue(a.date);
      })
       .slice(0, 3);
       .slice(0, 3);


Line 211: Line 468:


     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 224: Line 482:
       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));


       var sx = null;
       // Register swipe handlers once per deck initialization.
      deck.addEventListener('pointerdown', function (e) { sx = e.clientX; });
      if (!deck.dataset.pcSwipeInit) {
      deck.addEventListener('pointerup', function (e) {
        deck.dataset.pcSwipeInit = '1';
        if (sx === null) return;
 
        var dx = e.clientX - sx;
        var sx = null;
        sx = null;
 
        if (Math.abs(dx) > 45) go(dx < 0 ? 1 : -1);
        deck.addEventListener('pointerdown', function (e) {
      });
          sx = e.clientX;
        });
 
        deck.addEventListener('pointerup', function (e) {
          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 () {
          sx = 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();
  });
});
});



Revision as of 17:09, 23 October 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 fetching with fallbacks ---------- */

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

  function loadFeed(url, xmlParser) {
    var encoded = encodeURIComponent(url);

    // Try each source sequentially. A network error, invalid
    // response, or empty feed advances to the next source.
    var sources = [
      function () {
        return fetch(url)
          .then(okText)
          .then(xmlParser);
      },
      function () {
        return fetch(
          'https://api.allorigins.win/raw?url=' + encoded
        )
          .then(okText)
          .then(xmlParser);
      },
      function () {
        return fetch(
          'https://corsproxy.io/?url=' + encoded
        )
          .then(okText)
          .then(xmlParser);
      },
      function () {
        return fetch(
          'https://api.rss2json.com/v1/api.json?rss_url='
          + encoded
        )
          .then(okJson)
          .then(function (json) {
            if (json.status && json.status !== 'ok') {
              throw new Error('RSS conversion failed');
            }
            return fromJson(json);
          });
      }
    ];

    return sources.reduce(function (previous, source) {
      return previous.catch(function () {
        return source().then(function (list) {
          list = normalize(list);

          if (!list.length) {
            throw new Error('Feed returned no usable items');
          }

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

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

    return loadFeed(feed, fromXml).then(function (list) {
      // Keep podcast season and episode labels from the XML parser.
      return list;
    });
  }

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

    return loadFeed(url, fromYouTubeXml).then(function (list) {
      return list.map(function (video) {
        // Retain a consistent label for every video.
        video.tag = 'YouTube';
        return video;
      });
    });
  }

  /* ---------- 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, 3);

    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 swipe handlers once per deck initialization.
      if (!deck.dataset.pcSwipeInit) {
        deck.dataset.pcSwipeInit = '1';

        var sx = null;

        deck.addEventListener('pointerdown', function (e) {
          sx = e.clientX;
        });

        deck.addEventListener('pointerup', function (e) {
          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 () {
          sx = 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';
    });
});

/* =========================================================
   FEDOVERSE RANDOM HOMEPAGE GIF
   ========================================================= */

$(function () {
    var picker = document.getElementById('random-gif-picker');

    // Do nothing on pages without the GIF picker.
    if (!picker) {
        return;
    }

    // CHANGE THIS to your final number of uploaded GIFs.
    var maxGif = 42;

    if (!Number.isInteger(maxGif) || maxGif < 1) {
        return;
    }

    var storageKey = 'fedoverse-random-gif-last';
    var lastGif = 0;

    // Remember the previous GIF to avoid an immediate repeat.
    try {
        lastGif = Number(localStorage.getItem(storageKey)) || 0;
    } catch (e) {}

    // Select a random GIF from 1.gif to maxGif.gif.
    var gifNumber = Math.floor(Math.random() * maxGif) + 1;

    // Choose a different GIF from the previous visit.
    if (maxGif > 1 && gifNumber === lastGif) {
        gifNumber = (gifNumber % maxGif) + 1;
    }

    try {
        localStorage.setItem(storageKey, String(gifNumber));
    } catch (e) {}

    // Create the image.
    var img = document.createElement('img');

    img.alt = '';
    img.width = 850;
    img.loading = 'eager';
    img.decoding = 'async';

img.style.display = 'block';
img.style.width = '100%';
img.style.height = '100%';
img.style.maxWidth = '100%';
img.style.maxHeight = '100%';
img.style.objectFit = 'cover';
img.style.objectPosition = 'center';

    // Load the numbered GIF from the wiki.
    img.src = mw.util.getUrl(
        'Special:Redirect/file/' + gifNumber + '.gif',
        { width: 850 }
    );

    picker.appendChild(img);
});