MediaWiki:Timeless.js

From Medivia Online Wiki
Revision as of 20:17, 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 normalizeRoot(root) {
    // Page Forms / mw.hook sometimes passes non-DOM objects.
    if (root && (root.nodeType === 1 || root.nodeType === 9) && typeof root.querySelector === "function") {
      return root; // Element (1) or Document (9)
    }
    return document;
  }

  function normalizeToFileTitle(val) {
    if (!val) return "";
    val = ("" + val).trim();
    if (!val) return "";

    // Allow pasting [[File:...|...]]
    if (val.startsWith("[[")) val = val.replace(/^\[\[\s*/, "").replace(/\s*\]\]$/, "");
    if (val.includes("|")) val = val.split("|")[0];

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

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

  function hookItemImagePreview(root) {
    root = normalizeRoot(root);

    var input = root.querySelector("input.pf-item-image");
    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) {
    setTimeout(function () { hookItemImagePreview(root); }, 150);
  }

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