MediaWiki:Common.js

From Jcastle.info
Revision as of 14:03, 3 May 2025 by Eric (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.
/* Any JavaScript here will be loaded for all users on every page load. */
mw.loader.load('//use.fontawesome.com/053a76b93c.js');
// Load EXIF.js for reading image metadata
mw.loader.load('https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js');

$(document).ready(function () {
    $(document).on('change', 'input[type="file"]', function (e) {
        const file = e.target.files[0];
        if (!file || !file.type.startsWith('image/')) return;

        EXIF.getData(file, function () {
            const lat = EXIF.getTag(this, "GPSLatitude");
            const latRef = EXIF.getTag(this, "GPSLatitudeRef");
            const lon = EXIF.getTag(this, "GPSLongitude");
            const lonRef = EXIF.getTag(this, "GPSLongitudeRef");

            // Convert DMS to decimal
            function convertDMSToDecimal(dms, ref) {
                const [deg, min, sec] = dms;
                let dec = deg + (min / 60) + (sec / 3600);
                if (ref === "S" || ref === "W") dec *= -1;
                return dec.toFixed(6);
            }

            if (lat && lon && latRef && lonRef) {
                const latDec = convertDMSToDecimal(lat, latRef);
                const lonDec = convertDMSToDecimal(lon, lonRef);
                const gpsString = `${latDec}, ${lonDec}`;

                // Find the description/template box (usually part of SimpleBatchUpload UI)
                const textarea = document.querySelector('textarea[name="description"]');
                if (textarea) {
                    let text = textarea.value;

                    // If field exists, replace it
                    if (text.includes("|GPSLOCATION=")) {
                        textarea.value = text.replace(/(\|GPSLOCATION=)[^\n]*/, `$1${gpsString}`);
                    } else if (text.includes("{{Castle PhotoBatch")) {
                        // Insert GPSLOCATION line in proper place
                        textarea.value = text.replace(
                            /(\{\{Castle PhotoBatch[\s\S]*?)(\|[^=]*=)/,
                            `$1|GPSLOCATION=${gpsString}\n$2`
                        );
                    } else {
                        // If template isn't yet filled, prefill
                        textarea.value =
`{{Castle PhotoBatch
|CASTLENAME=
|SOURCE=
|PHOTODATE=
|GPSLOCATION=${gpsString}
|OTHER=
}}` + "\n\n" + text;
                    }
                }
            } else {
                console.log("No GPS EXIF data found.");
            }
        });
    });
});