MediaWiki:Common.js

From Medivia Online Wiki
Revision as of 20:09, 17 January 2026 by Eldrin (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
(function () {
  function normalizeToFileTitle(val) {
    if (!val) return "";
    val = val.trim();
    if (!val) return "";

    // Allow "File:Something.png" or just "Something.png"
    if (!/^File:/i.test(val)) val = "File:" + val;
    return val;
  }

  function fileTitleToThumbUrl(fileTitle) {
    // MediaWiki thumb URL via Special:Redirect (works without knowing upload path)
    // Example: /wiki/Special:Redirect/file/Some.png?width=64
    var name = fileTitle.replace(/^File:/i, "");
    return mw.util.getUrl("Special:Redirect/file/" + name) + "?width=64";
  }

  function hookPageFormsImagePreview() {
    // Page Forms inputs usually end up as <input name="...">
    var input =
      document.querySelector('input[name="image"]') ||
      document.querySelector('input[name="Item[image]"]') ||
      document.querySelector('input[name$="[image]"]');

    var img = document.getElementById("pf-image-preview");
    var txt = document.getElementById("pf-image-preview-text");
    if (!input || !img || !txt) return;

    function update() {
      var fileTitle = normalizeToFileTitle(input.value);
      if (!fileTitle) {
        img.style.display = "none";
        txt.style.display = "";
        txt.innerHTML = "<i>No image selected.</i>";
        img.removeAttribute("src");
        return;
      }

      var url = fileTitleToThumbUrl(fileTitle);
      img.onload = function () {
        img.style.display = "";
        txt.style.display = "none";
      };
      img.onerror = function () {
        img.style.display = "none";
        txt.style.display = "";
        txt.innerHTML = "<i>Image not found.</i>";
      };
      img.src = url;
    }

    // Update while typing + when autocomplete fills
    input.addEventListener("input", update);
    input.addEventListener("change", update);

    // Initial
    update();
  }

  mw.hook("wikipage.content").add(function () {
    // Run on formedit pages
    hookPageFormsImagePreview();
  });
})();