MediaWiki:Timeless.js

From Medivia Online Wiki
Revision as of 20:16, 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 users to paste [[File:...|...]]
    if (val.startsWith("[[")) val = val.replace(/^\[\[\s*/, "").replace(/\s*\]\]$/, "");
    if (val.includes("|")) val = val.split("|")[0];

    // Ensure File:
    if (!/^File:/i.test(val)) val = "File:" + val;

    return val;
  }

  function fileTitleToThumbUrl(fileTitle) {
    // Works without knowing upload path
    var name = fileTitle.replace(/^File:/i, "");
    return mw.util.getUrl("Special:Redirect/file/" + name) + "?width=64";
  }

  function hookItemImagePreview(root) {
    root = root || document;

    // Primary: class we set in the form
    var input = root.querySelector("input.pf-item-image");

    // Fallbacks (in case PageForms didn't apply class)
    if (!input) {
      input =
        root.querySelector('input[name="image"]') ||
        root.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 setEmpty(msgHtml) {
      img.style.display = "none";
      img.removeAttribute("src");
      txt.style.display = "";
      txt.innerHTML = msgHtml;
    }

    function update() {
      var fileTitle = normalizeToFileTitle(input.value);
      if (!fileTitle) return setEmpty("<i>No image selected.</i>");

      var url = fileTitleToThumbUrl(fileTitle);

      img.onload = function () {
        img.style.display = "";
        txt.style.display = "none";
      };
      img.onerror = function () {
        setEmpty("<i>Image not found.</i>");
      };

      img.src = url;
    }

    input.addEventListener("input", update);
    input.addEventListener("change", update);
    update();
  }

  function run(root) {
    // Delay helps on Special:FormEdit where inputs may appear after initial render
    setTimeout(function () { hookItemImagePreview(root); }, 150);
  }

  if (window.mw && mw.hook) {
    mw.hook("wikipage.content").add(run);
  }
  document.addEventListener("DOMContentLoaded", function () { run(document); });
})();