MediaWiki:Common.js

From Portland Homeless Resources Wiki
Jump to navigation Jump to search

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */
// iOS map-link rewrite: Google Maps -> Apple Maps
// Requires exported address links to be wrapped like:
// <span class="oc-maplink" data-addr="RAW ADDRESS">[https://... Display]</span>
(function () {
  function isIOS() {
    const ua = navigator.userAgent || "";
    const iOSUA = /iPhone|iPad|iPod/i.test(ua);
    const iPadOS13Plus = (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
    return iOSUA || iPadOS13Plus;
  }

  function encodeAppleQuery(addr) {
    return encodeURIComponent(addr);
  }

  function extractGoogleQuery(href) {
    try {
      const u = new URL(href, window.location.href);
      const q = u.searchParams.get("query");
      if (q) return q;
      const q2 = u.searchParams.get("q");
      if (q2) return q2;
    } catch (e) {}
    return null;
  }

  function rewriteMapLinks() {
    if (!isIOS()) return;

    const spans = document.querySelectorAll("span.oc-maplink");
    spans.forEach(function (span) {
      const a = span.querySelector("a");
      if (!a) return;

      // Prefer raw address from wrapper attribute
      const raw = span.getAttribute("data-addr");
      if (raw && raw.trim()) {
        a.href = "https://maps.apple.com/?q=" + encodeAppleQuery(raw.trim());
        return;
      }

      // Fallback: convert from existing Google href if present
      const gq = extractGoogleQuery(a.href);
      if (gq) {
        let decoded = gq;
        try { decoded = decodeURIComponent(gq.replace(/\+/g, "%20")); } catch (e) {}
        a.href = "https://maps.apple.com/?q=" + encodeAppleQuery(decoded);
      }
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", rewriteMapLinks);
  } else {
    rewriteMapLinks();
  }

  if (window.mw && mw.hook) {
    mw.hook("wikipage.content").add(rewriteMapLinks);
  }
})();