User:Loki Laufeyjarson/common.js: Difference between revisions

From Heroes 3 wiki
Jump to navigation Jump to search
Test
No edit summary
Line 2: Line 2:
   var cache = Object.create(null);
   var cache = Object.create(null);


   function resolveUrl($el) {
   function playFromHref(href) {
    var u = $el.attr('data-audio-url');
     if (!href) return;
     if (u) return u;
     var url = new URL(href, location.href).toString();
     var f = $el.attr('data-audio-file');
     var a = cache[url] || (cache[url] = new Audio(url));
     if (!f || /\{\{/.test(f)) return null;  
     try {
     return mw.util.getUrl('Special:FilePath/' + f);
      a.currentTime = 0;
      a.play && a.play();
    } catch (_) {}
   }
   }


   $(document).on('click', '.click-audio', function (e) {
   $(document).on('click', '.click-audio a.image', function (e) {
    e.preventDefault();
     var href = $(this).attr('href') || '';
     var $el = $(this);
     if (/\/(Media:|Special:FilePath\/)/i.test(href) || /\.(mp3|wav|ogg|m4a|webm)(\?|#|$)/i.test(href)) {
    var url = resolveUrl($el);
      e.preventDefault();
     if (!url) return;
      playFromHref(href);
    var a = cache[url] || (cache[url] = new Audio(url));
    }
    a.currentTime = 0;
    a.play && a.play();
   });
   });


  // Optional: pointer cursor + keyboard
   mw.hook('wikipage.content').add(function ($c) {
   mw.hook('wikipage.content').add(function ($c) {
     $c.find('.click-audio').css('cursor', 'pointer').attr({ role: 'button', tabindex: 0 });
     $c.find('.click-audio')
      .css('cursor', 'pointer')
      .attr({ role: 'button', tabindex: 0 });
   });
   });
});
});

Revision as of 01:47, 10 September 2025

mw.loader.using('mediawiki.util').then(function () {
  var cache = Object.create(null);

  function playFromHref(href) {
    if (!href) return;
    var url = new URL(href, location.href).toString();
    var a = cache[url] || (cache[url] = new Audio(url));
    try {
      a.currentTime = 0;
      a.play && a.play();
    } catch (_) {}
  }

  $(document).on('click', '.click-audio a.image', function (e) {
    var href = $(this).attr('href') || '';
    if (/\/(Media:|Special:FilePath\/)/i.test(href) || /\.(mp3|wav|ogg|m4a|webm)(\?|#|$)/i.test(href)) {
      e.preventDefault();
      playFromHref(href);
    }
  });

  mw.hook('wikipage.content').add(function ($c) {
    $c.find('.click-audio')
      .css('cursor', 'pointer')
      .attr({ role: 'button', tabindex: 0 });
  });
});