Jump to content

MediaWiki:Common.js: Difference between revisions

From Costa Sano MediaWiki
No edit summary
No edit summary
 
(11 intermediate revisions by the same user not shown)
Line 38: Line 38:


/************************************************************
/************************************************************
  * 2. AUTOMATIC GEOCODING (updated for current Form:Place)
  * 2. PAGE FORMS GEOCODING (ON BLUR ONLY – STABLE)
  ************************************************************/
  ************************************************************/
$(function () {


    const addr = $('input[name="Address"]');
mw.hook('wikipage.content').add(function () {
    const lat  = $('input[name="Latitude"]');
    const lon  = $('input[name="Longitude"]');


     console.log("Address fields found:", addr.length);
     function setupGeocoding(addressField, latField, lonField) {


    if (!addr.length || !lat.length || !lon.length) {
        const addr = $('input[name$="[' + addressField + ']"]');
        console.log("Geocoding fields not found");
        const lat  = $('input[name$="[' + latField + ']"]');
         return;
        const lon  = $('input[name$="[' + lonField + ']"]');
 
        if (!addr.length || !lat.length || !lon.length) return;
 
        // Remove previous handlers to avoid duplicates
        addr.off('.pfGeocode');
 
        addr.on('blur.pfGeocode', function () {
 
            const q = addr.val().trim();
            if (!q) return;
 
            console.log('Geocoding on blur:', q);
 
            const url =
                'https://nominatim.openstreetmap.org/search' +
                '?format=json&limit=1&q=' + encodeURIComponent(q);
 
            $.getJSON(url, function (data) {
                if (data && data.length) {
                    lat.val(data[0].lat).trigger('change');
                    lon.val(data[0].lon).trigger('change');
                }
            });
         });
     }
     }


     addr.on('change', function () {
     // === ENABLE FOR PLACE ===
    setupGeocoding('Address', 'Latitude', 'Longitude');
});


        const q = addr.val().trim();
        if (!q) return;


         console.log("Geocoding address:", q);
/************************************************************
* 3. GENERIC OSM LINK HELPER (SAFE)
************************************************************/
 
mw.hook('wikipage.content').add(function () {
 
    function setupOSMLink(latField, lonField) {
 
        const lat = $('input[name$="[' + latField + ']"]');
         const lon = $('input[name$="[' + lonField + ']"]');


         const url =
         if (!lat.length || !lon.length) return;
            'https://nominatim.openstreetmap.org/search' +
            '?format=json&limit=1&q=' + encodeURIComponent(q);


         $.getJSON(url, function (data) {
         const linkBox =
             if (data && data.length) {
            $('<div class="pf-osm-link" style="margin-top:4px;"></div>');
                 lat.val(data[0].lat).trigger('change');
        lon.closest('td').append(linkBox);
                 lon.val(data[0].lon).trigger('change');
 
        function update() {
 
            const la = lat.val();
            const lo = lon.val();
 
             if (la && lo) {
                 const url =
                    'https://www.openstreetmap.org/?mlat=' + la +
                    '&mlon=' + lo;
                linkBox.html(
                    '<a href="' + url +
                    '" target="_blank">View on OpenStreetMap</a>'
                );
            } else {
                 linkBox.empty();
             }
             }
         });
         }
     });
 
        lat.on('change keyup', update);
        lon.on('change keyup', update);
        update();
     }
 
    // === ENABLE FOR PLACE ===
    setupOSMLink('Latitude', 'Longitude');
});
});


/************************************************************
/************************************************************
  * 3. OSM LINK BELOW LONGITUDE FIELD (updated)
  * 4. EMPTY MANDATORY FIELD CHECK (PAGE FORMS ONLY)
  ************************************************************/
  ************************************************************/
$(function () {
mw.hook('wikipage.content').add(function () {


     const lat = $('input[name="Latitude"]');
     // Only run on Page Forms edit pages
    const lon = $('input[name="Longitude"]');
    if (mw.config.get('wgCanonicalSpecialPageName') !== 'FormEdit') {
        return;
    }


     if (!lat.length || !lon.length) return;
    // Save buttons used by Page Forms
    const saveButtons = $('input[name="wpSave"], button[name="wpSave"]');
     if (!saveButtons.length) return;


     const linkBox = $('<div id="pf-osm-link" style="margin-top:4px;"></div>');
     // Avoid duplicate bindings
     lon.closest('td').append(linkBox);
     saveButtons.off('.pfRequiredCheck');


     function updateOSMLink() {
     saveButtons.on('click.pfRequiredCheck', function (e) {
 
        const requiredFields = [
            { name: 'Label', label: 'Name' }
        ];
 
        let missing = [];
 
        requiredFields.forEach(function (f) {
            const input = $(
                'input[name$="[' + f.name + ']"], ' +
                'textarea[name$="[' + f.name + ']"], ' +
                'select[name$="[' + f.name + ']"]'
            );
 
            if (!input.length || !input.val().trim()) {
                missing.push(f.label);
            }
        });


         const la = lat.val();
         if (missing.length) {
        const lo = lon.val();
            e.preventDefault();
            e.stopImmediatePropagation();


        if (la && lo) {
            alert(
            const url =
                 'Please fill in the following required field(s):\n\n' +
                 'https://www.openstreetmap.org/?mlat=' + la +
                 missing.join('\n')
                 '&mlon=' + lo;
            linkBox.html(
                '<a href="' + url + '" target="_blank">View on OpenStreetMap</a>'
             );
             );
        } else {
 
             linkBox.empty();
             return false;
         }
         }
    });
});
/* =========================================================
  5. Prefill Page Forms page-name field on Asset dashboard
  ========================================================= */
mw.loader.using('mediawiki.user', function () {
    function prefillAssetPageName() {
        var input = document.querySelector(
            'input.oo-ui-inputWidget-input[name="page_name"]'
        );
        if (!input) return false;
        if (!input.value || input.value.trim() === '') {
            input.value = mw.user.getName() + ' asset input';
        }
        return true;
     }
     }


     lat.on('change keyup', updateOSMLink);
     // Try immediately
     lon.on('change keyup', updateOSMLink);
     if (prefillAssetPageName()) return;


     updateOSMLink();
     // Retry briefly because Page Forms renders late
    var attempts = 0;
    var timer = setInterval(function () {
        attempts++;
        if (prefillAssetPageName() || attempts >= 10) {
            clearInterval(timer);
        }
    }, 300);
});
});

Latest revision as of 18:05, 18 February 2026

/************************************************************
 * 1. AUTO‑PURGE FOR ALL DASHBOARD:* PAGES
 ************************************************************/
$(function () {

    // Prevent purge logic from running on edit, history, diff, preview, etc.
    if (mw.config.get('wgAction') !== 'view') return;

    const title = mw.config.get('wgPageName');

    if (title && title.startsWith('Dashboard:')) {

        // Only purge once
        if (!location.search.includes('mw_purged=1')) {

            new mw.Api().get({
                action: 'query',
                meta: 'tokens',
                type: 'csrf'
            }).done(function (data) {

                const token = data.query.tokens.csrftoken;

                new mw.Api().post({
                    action: 'purge',
                    titles: title,
                    token: token
                }).always(function () {

                    // Reload the dashboard normally, marked as purged
                    const url = mw.util.getUrl(title, { mw_purged: 1 });
                    location.replace(url);
                });
            });
        }
    }
});

/************************************************************
 * 2. PAGE FORMS GEOCODING (ON BLUR ONLY – STABLE)
 ************************************************************/

mw.hook('wikipage.content').add(function () {

    function setupGeocoding(addressField, latField, lonField) {

        const addr = $('input[name$="[' + addressField + ']"]');
        const lat  = $('input[name$="[' + latField + ']"]');
        const lon  = $('input[name$="[' + lonField + ']"]');

        if (!addr.length || !lat.length || !lon.length) return;

        // Remove previous handlers to avoid duplicates
        addr.off('.pfGeocode');

        addr.on('blur.pfGeocode', function () {

            const q = addr.val().trim();
            if (!q) return;

            console.log('Geocoding on blur:', q);

            const url =
                'https://nominatim.openstreetmap.org/search' +
                '?format=json&limit=1&q=' + encodeURIComponent(q);

            $.getJSON(url, function (data) {
                if (data && data.length) {
                    lat.val(data[0].lat).trigger('change');
                    lon.val(data[0].lon).trigger('change');
                }
            });
        });
    }

    // === ENABLE FOR PLACE ===
    setupGeocoding('Address', 'Latitude', 'Longitude');
});


/************************************************************
 * 3. GENERIC OSM LINK HELPER (SAFE)
 ************************************************************/

mw.hook('wikipage.content').add(function () {

    function setupOSMLink(latField, lonField) {

        const lat = $('input[name$="[' + latField + ']"]');
        const lon = $('input[name$="[' + lonField + ']"]');

        if (!lat.length || !lon.length) return;

        const linkBox =
            $('<div class="pf-osm-link" style="margin-top:4px;"></div>');
        lon.closest('td').append(linkBox);

        function update() {

            const la = lat.val();
            const lo = lon.val();

            if (la && lo) {
                const url =
                    'https://www.openstreetmap.org/?mlat=' + la +
                    '&mlon=' + lo;
                linkBox.html(
                    '<a href="' + url +
                    '" target="_blank">View on OpenStreetMap</a>'
                );
            } else {
                linkBox.empty();
            }
        }

        lat.on('change keyup', update);
        lon.on('change keyup', update);
        update();
    }

    // === ENABLE FOR PLACE ===
    setupOSMLink('Latitude', 'Longitude');
});

/************************************************************
 * 4. EMPTY MANDATORY FIELD CHECK (PAGE FORMS ONLY)
 ************************************************************/
mw.hook('wikipage.content').add(function () {

    // Only run on Page Forms edit pages
    if (mw.config.get('wgCanonicalSpecialPageName') !== 'FormEdit') {
        return;
    }

    // Save buttons used by Page Forms
    const saveButtons = $('input[name="wpSave"], button[name="wpSave"]');
    if (!saveButtons.length) return;

    // Avoid duplicate bindings
    saveButtons.off('.pfRequiredCheck');

    saveButtons.on('click.pfRequiredCheck', function (e) {

        const requiredFields = [
            { name: 'Label', label: 'Name' }
        ];

        let missing = [];

        requiredFields.forEach(function (f) {
            const input = $(
                'input[name$="[' + f.name + ']"], ' +
                'textarea[name$="[' + f.name + ']"], ' +
                'select[name$="[' + f.name + ']"]'
            );

            if (!input.length || !input.val().trim()) {
                missing.push(f.label);
            }
        });

        if (missing.length) {
            e.preventDefault();
            e.stopImmediatePropagation();

            alert(
                'Please fill in the following required field(s):\n\n' +
                missing.join('\n')
            );

            return false;
        }
    });
});

/* =========================================================
   5. Prefill Page Forms page-name field on Asset dashboard
   ========================================================= */
mw.loader.using('mediawiki.user', function () {

    function prefillAssetPageName() {
        var input = document.querySelector(
            'input.oo-ui-inputWidget-input[name="page_name"]'
        );
        if (!input) return false;

        if (!input.value || input.value.trim() === '') {
            input.value = mw.user.getName() + ' asset input';
        }

        return true;
    }

    // Try immediately
    if (prefillAssetPageName()) return;

    // Retry briefly because Page Forms renders late
    var attempts = 0;
    var timer = setInterval(function () {
        attempts++;
        if (prefillAssetPageName() || attempts >= 10) {
            clearInterval(timer);
        }
    }, 300);
});