MediaWiki:Common.js

De Wikiromandie.org
Aller à la navigation Aller à la recherche

Note : après avoir publié vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou appuyez sur Ctrl + F5 ou Ctrl + R (⌘ + R sur un Mac).
  • Google Chrome : appuyez sur Ctrl + Maj + R (⌘ + Shift + R sur un Mac).
  •  Edge : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl + F5.
/* Tout JavaScript présent ici sera exécuté par tous les utilisateurs à chaque chargement de page. */

/**
 * Keep code in MediaWiki:Common.js to a minimum as it is unconditionally
 * loaded for all users on every wiki page. If possible create a gadget that is
 * enabled by default instead of adding it here (since gadgets are fully
 * optimized ResourceLoader modules with possibility to add dependencies etc.)
 *
 * Since Common.js isn't a gadget, there is no place to declare its
 * dependencies, so we have to lazy load them with mw.loader.using on demand and
 * then execute the rest in the callback. In most cases these dependencies will
 * be loaded (or loading) already and the callback will not be delayed. In case a
 * dependency hasn't arrived yet it'll make sure those are loaded before this.
 */

/* global mw, $ */
/* jshint strict:false, browser:true */

mw.loader.using( [ 'mediawiki.util' ] ).then( function () {

    mw.log.deprecate( window, 'addPortletLink', mw.util.addPortletLink, 'Use mw.util.addPortletLink instead' );

    var extraCSS = mw.util.getParamValue( 'withCSS' ),
        extraJS  = mw.util.getParamValue( 'withJS' );

    if ( extraCSS ) {
        if ( /^MediaWiki:[^&<>=%#]*\.css$/.test( extraCSS ) ) {
            mw.loader.load( '/w/index.php?title=' + encodeURIComponent( extraCSS ) + '&action=raw&ctype=text/css', 'text/css' );
        } else {
            mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withCSS value' } );
        }
    }

    if ( extraJS ) {
        if ( /^MediaWiki:[^&<>=%#]*\.js$/.test( extraJS ) ) {
            mw.loader.load( '/w/index.php?title=' + encodeURIComponent( extraJS ) + '&action=raw&ctype=text/javascript' );
        } else {
            mw.notify( 'Only pages from the MediaWiki namespace are allowed.', { title: 'Invalid withJS value' } );
        }
    }

    /**
     * Collapsible tables
     */
    mw.hook( 'wikipage.content' ).add( function ( $content ) {
        var $tables = $content.find( 'table.collapsible:not(.mw-collapsible)' );
        if ( !$tables.length ) { return; }

        $tables.addClass( 'mw-collapsible' ).each( function () {
            if ( $( this ).hasClass( 'collapsed' ) ) {
                $( this ).addClass( 'mw-collapsed' );
            }
        } );

        mw.loader.using( 'jquery.makeCollapsible' ).then( function () {
            $tables.makeCollapsible();
        } );
    } );

    mw.hook( 'wikipage.collapsibleContent' ).add( function ( $collapsibleContent ) {
        var autoCollapseThreshold = 2,
            hasOuter = $collapsibleContent.parents( '.outercollapse' ).length > 0;

        $collapsibleContent.each( function () {
            var $element = $( this );

            if ( $element.hasClass( 'collapsible' ) ) {
                $element.find( 'tr:first > th:first' ).prepend( $element.find( 'tr:first > * > .mw-collapsible-toggle' ) );
            }

            if ( $collapsibleContent.length >= autoCollapseThreshold && $element.hasClass( 'autocollapse' ) ) {
                $element.data( 'mw-collapsible' ).collapse();
            } else if ( $element.hasClass( 'innercollapse' ) && hasOuter ) {
                $element.data( 'mw-collapsible' ).collapse();
            }

            var $toggle = $element.find( '.mw-collapsible-toggle' );
            if ( $toggle.length && $toggle.parent()[0].style.color ) {
                $toggle.css( 'color', 'inherit' ).find( '.mw-collapsible-text' ).css( 'color', 'inherit' );
            }
        } );
    } );

    /**
     * Force interwiki links to open in a new tab
     */
    mw.hook( 'wikipage.content' ).add( function ( $content ) {
        $content.find( 'a.extiw' ).attr( 'target', '_blank' ).attr( 'rel', 'noopener noreferrer' );
    } );

    /**
     * Optimized Wikidata SPARQL tables rendering
     */
    var WIKIDATA_PREFIX = 'http://www.wikidata.org/entity/',
        WIKIDATA_HTTPS  = 'https://www.wikidata.org/entity/',
        COMMONS_MARKER  = 'Special:FilePath/';

    function escapeHtml( text ) {
        return String( text )
            .replace( /&/g, '&amp;' )
            .replace( /</g, '&lt;' )
            .replace( />/g, '&gt;' )
            .replace( /"/g, '&quot;' )
            .replace( /'/g, '&#39;' );
    }

    mw.hook( 'wikipage.content' ).add( function ( $content ) {
        var contextNode = ($content && $content[0]) ? $content[0] : document,
            tables = contextNode.querySelectorAll( '.wikidata-sparql-table:not([data-loaded])' );

        if ( !tables.length ) { return; }

        var renderPromises = Array.prototype.map.call( tables, function ( el ) {
            el.setAttribute( 'data-loaded', '1' );
            var sparql = el.getAttribute( 'data-sparql' ),
                title  = el.getAttribute( 'data-title' );

            if ( !sparql ) { return Promise.resolve(); }
            el.textContent = '⏳ Loading…';

            var fetchUrl = 'https://query.wikidata.org/sparql?format=json&query=' + encodeURIComponent( sparql );

            return fetch( fetchUrl, { headers: { Accept: 'application/json' } } )
                .then( function ( r ) { return r.json(); } )
                .then( function ( data ) {
                    var vars = data.head.vars,
                        rows = data.results.bindings,
                        html = [],
                        vLen = vars.length;

                    if ( title ) {
                        html.push( '<h3>', escapeHtml( title ), '</h3>' );
                    }

                    html.push( '<table class="wikitable sortable"><thead><tr>' );
                    for ( var i = 0; i < vLen; i++ ) {
                        html.push( '<th>', escapeHtml( vars[i].replace( /_/g, ' ' ) ), '</th>' );
                    }
                    html.push( '</tr></thead><tbody>' );

                    for ( var r = 0, rLen = rows.length; r < rLen; r++ ) {
                        var row = rows[r];
                        html.push( '<tr>' );
                        for ( var c = 0; c < vLen; c++ ) {
                            var v = vars[c],
                                val = row[v] ? row[v].value : '';

                            if ( val.indexOf( COMMONS_MARKER ) !== -1 ) {
                                var thumb = val.replace( /^http:\/\//, 'https://' );
                                html.push( '<td><img src="', encodeURI( thumb ), '?width=100" style="max-height:80px;" alt="" loading="lazy" /></td>' );
                            } else if ( val.indexOf( WIKIDATA_PREFIX ) === 0 || val.indexOf( WIKIDATA_HTTPS ) === 0 ) {
                                var qid = val.substring( val.lastIndexOf( '/' ) + 1 );
                                html.push( '<td><a href="https://www.wikidata.org/wiki/', qid, '" target="_blank" rel="noopener">', qid, '</a></td>' );
                            } else {
                                html.push( '<td>', escapeHtml( val ), '</td>' );
                            }
                        }
                        html.push( '</tr>' );
                    }

                    html.push( '</tbody></table>' );
                    el.innerHTML = html.join( '' );
                    return el;
                } )
                .catch( function () {
                    el.textContent = '⚠️ Failed to load.';
                } );
        } );

        Promise.all( renderPromises ).then( function ( renderedElements ) {
            var validElements = renderedElements.filter( Boolean );
            if ( validElements.length ) {
                mw.hook( 'wikipage.content' ).fire( $( validElements ) );
            }
        } );
    } );
} );

/* DO NOT ADD CODE BELOW THIS LINE */