MediaWiki:Common.js
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/',
SPARQL_CACHE_TTL = 15 * 60 * 1000, // 15 minutes
SPARQL_TIMEOUT = 15000; // 15 seconds — fail loudly instead of spinning forever
function escapeHtml( text ) {
return String( text )
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' )
.replace( /'/g, ''' );
}
// Tiny fast string hash (FNV-1a) — just needs to be short & collision-unlikely for cache keys
function hashKey( str ) {
var h = 0x811c9dc5;
for ( var i = 0; i < str.length; i++ ) {
h ^= str.charCodeAt( i );
h = ( h * 0x01000193 ) >>> 0;
}
return h.toString( 36 );
}
function getCachedResult( sparql ) {
try {
var raw = sessionStorage.getItem( 'wdsparql:' + hashKey( sparql ) );
if ( !raw ) { return null; }
var cached = JSON.parse( raw );
if ( Date.now() - cached.ts > SPARQL_CACHE_TTL ) { return null; }
return cached.data;
} catch ( e ) {
return null; // sessionStorage unavailable/full/private mode — just skip caching
}
}
function setCachedResult( sparql, data ) {
try {
sessionStorage.setItem( 'wdsparql:' + hashKey( sparql ), JSON.stringify( { ts: Date.now(), data: data } ) );
} catch ( e ) {
// quota exceeded or unavailable — ignore, caching is a nice-to-have
}
}
function fetchSparql( sparql ) {
var cached = getCachedResult( sparql );
if ( cached ) {
return Promise.resolve( cached );
}
var controller = ( typeof AbortController !== 'undefined' ) ? new AbortController() : null,
timer = controller ? setTimeout( function () { controller.abort(); }, SPARQL_TIMEOUT ) : null,
fetchUrl = 'https://query.wikidata.org/sparql?format=json&query=' + encodeURIComponent( sparql );
return fetch( fetchUrl, {
headers: { Accept: 'application/json' },
signal: controller ? controller.signal : undefined
} )
.then( function ( r ) {
if ( timer ) { clearTimeout( timer ); }
if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function ( data ) {
setCachedResult( sparql, data );
return data;
} );
}
function renderTable( data, title ) {
var vars = data.head.vars,
rows = data.results.bindings,
vLen = vars.length,
html = [];
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>' );
return html.join( '' );
}
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( null ); }
el.textContent = '⏳ Loading…';
return fetchSparql( sparql )
.then( function ( data ) {
el.innerHTML = renderTable( data, title );
return el;
} )
.catch( function ( err ) {
el.textContent = ( err && err.name === 'AbortError' )
? '⚠️ Timed out loading data.'
: '⚠️ Failed to load.';
} );
} );
// Fire the sortable hook only once, after every table on the page has settled
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 */