« MediaWiki:Common.js » : différence entre les versions
Aller à la navigation
Aller à la recherche
Aucun résumé des modifications |
Aucun résumé des modifications |
||
| Ligne 90 : | Ligne 90 : | ||
/** | /** | ||
* | * Wikidata SPARQL tables rendering | ||
* | |||
* - Images are no longer double-encoded (was silently breaking any filename | |||
* with spaces/accents/apostrophes/etc. - that was the "some images show, | |||
* some don't" bug). | |||
* - All queries on a page go through a small shared queue: max | |||
* SPARQL_MAX_PARALLEL requests in flight at once, identical in-flight | |||
* queries are de-duplicated to a single fetch, and 429/503 responses are | |||
* retried with exponential backoff instead of just failing. This is what | |||
* was getting pages with several tables rate-limited by WDQS. | |||
* - Results are still cached (now resilient to storage quota errors) so a | |||
* repeat view of the same page doesn't hit WDQS again within the TTL. | |||
*/ | */ | ||
var WIKIDATA_PREFIX | var WIKIDATA_PREFIX = 'http://www.wikidata.org/entity/', | ||
WIKIDATA_HTTPS | WIKIDATA_HTTPS = 'https://www.wikidata.org/entity/', | ||
COMMONS_MARKER | COMMONS_MARKER = 'Special:FilePath/', | ||
SPARQL_CACHE_TTL = | SPARQL_CACHE_TTL = 2 * 60 * 1000, // 2 minutes caching | ||
SPARQL_TIMEOUT = | SPARQL_TIMEOUT = 20000, // 20s | ||
SPARQL_MAX_PARALLEL = 2, // never more than 2 concurrent requests from one page load | |||
SPARQL_RETRY_MAX = 3, | |||
SPARQL_RETRY_BASE = 1000; // ms, doubles each retry (plus Retry-After if the server sends one) | |||
function escapeHtml( text ) { | function escapeHtml( text ) { | ||
| Ligne 107 : | Ligne 121 : | ||
} | } | ||
// Tiny fast string hash (FNV-1a) — just needs to be short & collision-unlikely for cache keys | // Tiny fast string hash (FNV-1a) — just needs to be short & collision-unlikely for cache/queue keys | ||
function hashKey( str ) { | function hashKey( str ) { | ||
var h = 0x811c9dc5; | var h = 0x811c9dc5; | ||
| Ligne 115 : | Ligne 129 : | ||
} | } | ||
return h.toString( 36 ); | return h.toString( 36 ); | ||
} | |||
// --- Cache: prefer localStorage (survives across page loads/sessions, so it | |||
// actually cuts repeat traffic to WDQS), fall back to sessionStorage, then | |||
// an in-memory map so caching failures never break rendering. | |||
var memoryCache = {}; | |||
function detectStore() { | |||
var stores = [ 'localStorage', 'sessionStorage' ]; | |||
for ( var i = 0; i < stores.length; i++ ) { | |||
try { | |||
var s = window[ stores[i] ]; | |||
s.setItem( '__wdsparql_test__', '1' ); | |||
s.removeItem( '__wdsparql_test__' ); | |||
return s; | |||
} catch ( e ) { /* try next */ } | |||
} | |||
return null; | |||
} | |||
var store = detectStore(); | |||
function pruneOldestCacheEntries( s, n ) { | |||
var entries = []; | |||
for ( var i = 0; i < s.length; i++ ) { | |||
var k = s.key( i ); | |||
if ( k && k.indexOf( 'wdsparql:' ) === 0 ) { | |||
var ts = 0; | |||
try { ts = JSON.parse( s.getItem( k ) ).ts; } catch ( e ) { /* keep ts = 0, prune first */ } | |||
entries.push( { key: k, ts: ts } ); | |||
} | |||
} | |||
entries.sort( function ( a, b ) { return a.ts - b.ts; } ); | |||
for ( var j = 0; j < Math.min( n, entries.length ); j++ ) { | |||
s.removeItem( entries[j].key ); | |||
} | |||
} | } | ||
function getCachedResult( sparql ) { | function getCachedResult( sparql ) { | ||
var key = 'wdsparql:' + hashKey( sparql ); | |||
if ( store ) { | |||
try { | |||
var raw = store.getItem( key ); | |||
if ( raw ) { | |||
var cached = JSON.parse( raw ); | |||
if ( Date.now() - cached.ts <= SPARQL_CACHE_TTL ) { | |||
return cached.data; | |||
} | |||
store.removeItem( key ); | |||
} | |||
} catch ( e ) { /* fall through to memory cache */ } | |||
} | } | ||
var mem = memoryCache[ key ]; | |||
if ( mem && Date.now() - mem.ts <= SPARQL_CACHE_TTL ) { | |||
return mem.data; | |||
} | |||
return null; | |||
} | } | ||
function setCachedResult( sparql, data ) { | function setCachedResult( sparql, data ) { | ||
var key = 'wdsparql:' + hashKey( sparql ), | |||
entry = { ts: Date.now(), data: data }; | |||
memoryCache[ key ] = entry; | |||
if ( store ) { | |||
try { | |||
store.setItem( key, JSON.stringify( entry ) ); | |||
} catch ( e ) { | |||
// Quota exceeded - prune the oldest wdsparql entries and try once more. | |||
try { | |||
pruneOldestCacheEntries( store, 5 ); | |||
store.setItem( key, JSON.stringify( entry ) ); | |||
} catch ( e2 ) { | |||
// Give up on persistent caching; the memory cache still covers this pageview. | |||
} | |||
} | |||
} | |||
} | |||
// --- Request queue: caps concurrency and de-dupes identical in-flight queries | |||
var inFlight = {}, | |||
queue = [], | |||
active = 0; | |||
function pump() { | |||
while ( active < SPARQL_MAX_PARALLEL && queue.length ) { | |||
var job = queue.shift(); | |||
active++; | |||
runQuery( job.sparql ).then( | |||
function ( data ) { active--; pump(); job.resolve( data ); }, | |||
function ( err ) { active--; pump(); job.reject( err ); } | |||
); | |||
} | |||
} | |||
function enqueue( sparql ) { | |||
var key = hashKey( sparql ); | |||
if ( inFlight[ key ] ) { | |||
return inFlight[ key ]; | |||
} | } | ||
var p = new Promise( function ( resolve, reject ) { | |||
queue.push( { sparql: sparql, resolve: resolve, reject: reject } ); | |||
} ); | |||
var cleaned = p.then( | |||
function ( result ) { delete inFlight[ key ]; return result; }, | |||
function ( err ) { delete inFlight[ key ]; throw err; } | |||
); | |||
inFlight[ key ] = cleaned; | |||
pump(); | |||
return cleaned; | |||
} | } | ||
function | function runQuery( sparql, attempt ) { | ||
attempt = attempt || 0; | |||
var cached = getCachedResult( sparql ); | var cached = getCachedResult( sparql ); | ||
if ( cached ) { | if ( cached ) { | ||
| Ligne 148 : | Ligne 260 : | ||
return fetch( fetchUrl, { | return fetch( fetchUrl, { | ||
headers: { Accept: 'application/json' }, | headers: { Accept: 'application/sparql-results+json' }, | ||
signal: controller ? controller.signal : undefined | signal: controller ? controller.signal : undefined | ||
} ) | } ) | ||
.then( function ( r ) { | .then( function ( r ) { | ||
if ( timer ) { clearTimeout( timer ); } | if ( timer ) { clearTimeout( timer ); } | ||
if ( ( r.status === 429 || r.status === 503 ) && attempt < SPARQL_RETRY_MAX ) { | |||
var wait = SPARQL_RETRY_BASE * Math.pow( 2, attempt ), | |||
retryAfter = r.headers.get( 'Retry-After' ); | |||
if ( retryAfter && !isNaN( +retryAfter ) ) { | |||
wait = ( +retryAfter ) * 1000; | |||
} | |||
return new Promise( function ( resolve ) { setTimeout( resolve, wait ); } ) | |||
.then( function () { return runQuery( sparql, attempt + 1 ); } ); | |||
} | |||
if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); } | if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); } | ||
return r.json(); | return r.json(); | ||
| Ligne 160 : | Ligne 283 : | ||
return data; | return data; | ||
} ); | } ); | ||
} | |||
function fetchSparql( sparql ) { | |||
return enqueue( sparql ); | |||
} | |||
function commonsThumbUrl( value, width ) { | |||
// `value` is already a percent-encoded URI straight from the SPARQL JSON | |||
// results. Re-encoding it here (the old code's encodeURI() call) double- | |||
// escapes any filename with spaces/accents/quotes/etc., which silently | |||
// breaks the <img src> for those rows only - that was the root cause of | |||
// "some images show, some don't". Just append the width param. | |||
var thumb = value.replace( /^http:\/\//, 'https://' ), | |||
sep = thumb.indexOf( '?' ) === -1 ? '?' : '&'; | |||
return thumb + sep + 'width=' + width; | |||
} | } | ||
| Ligne 186 : | Ligne 324 : | ||
if ( val.indexOf( COMMONS_MARKER ) !== -1 ) { | if ( val.indexOf( COMMONS_MARKER ) !== -1 ) { | ||
var thumb = val | var thumb = commonsThumbUrl( val, 100 ); | ||
html.push( '<td><img src="', | html.push( | ||
'<td><img src="', escapeHtml( thumb ), '" style="max-height:80px;" alt="" loading="lazy" ', | |||
'onerror="this.onerror=null;this.replaceWith(document.createTextNode(\'—\'));" /></td>' | |||
); | |||
} else if ( val.indexOf( WIKIDATA_PREFIX ) === 0 || val.indexOf( WIKIDATA_HTTPS ) === 0 ) { | } else if ( val.indexOf( WIKIDATA_PREFIX ) === 0 || val.indexOf( WIKIDATA_HTTPS ) === 0 ) { | ||
var qid = val.substring( val.lastIndexOf( '/' ) + 1 ); | var qid = val.substring( val.lastIndexOf( '/' ) + 1 ); | ||
| Ligne 224 : | Ligne 365 : | ||
el.textContent = ( err && err.name === 'AbortError' ) | el.textContent = ( err && err.name === 'AbortError' ) | ||
? '⚠️ Timed out loading data.' | ? '⚠️ Timed out loading data.' | ||
: '⚠️ Failed to load.'; | : '⚠️ Failed to load (Wikidata may be busy - it will use the cache on the next view).'; | ||
} ); | } ); | ||
} ); | } ); | ||
Version du 21 septembre 2026 à 14:38
/* 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' );
} );
/**
* Wikidata SPARQL tables rendering
*
* - Images are no longer double-encoded (was silently breaking any filename
* with spaces/accents/apostrophes/etc. - that was the "some images show,
* some don't" bug).
* - All queries on a page go through a small shared queue: max
* SPARQL_MAX_PARALLEL requests in flight at once, identical in-flight
* queries are de-duplicated to a single fetch, and 429/503 responses are
* retried with exponential backoff instead of just failing. This is what
* was getting pages with several tables rate-limited by WDQS.
* - Results are still cached (now resilient to storage quota errors) so a
* repeat view of the same page doesn't hit WDQS again within the TTL.
*/
var WIKIDATA_PREFIX = 'http://www.wikidata.org/entity/',
WIKIDATA_HTTPS = 'https://www.wikidata.org/entity/',
COMMONS_MARKER = 'Special:FilePath/',
SPARQL_CACHE_TTL = 2 * 60 * 1000, // 2 minutes caching
SPARQL_TIMEOUT = 20000, // 20s
SPARQL_MAX_PARALLEL = 2, // never more than 2 concurrent requests from one page load
SPARQL_RETRY_MAX = 3,
SPARQL_RETRY_BASE = 1000; // ms, doubles each retry (plus Retry-After if the server sends one)
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/queue 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 );
}
// --- Cache: prefer localStorage (survives across page loads/sessions, so it
// actually cuts repeat traffic to WDQS), fall back to sessionStorage, then
// an in-memory map so caching failures never break rendering.
var memoryCache = {};
function detectStore() {
var stores = [ 'localStorage', 'sessionStorage' ];
for ( var i = 0; i < stores.length; i++ ) {
try {
var s = window[ stores[i] ];
s.setItem( '__wdsparql_test__', '1' );
s.removeItem( '__wdsparql_test__' );
return s;
} catch ( e ) { /* try next */ }
}
return null;
}
var store = detectStore();
function pruneOldestCacheEntries( s, n ) {
var entries = [];
for ( var i = 0; i < s.length; i++ ) {
var k = s.key( i );
if ( k && k.indexOf( 'wdsparql:' ) === 0 ) {
var ts = 0;
try { ts = JSON.parse( s.getItem( k ) ).ts; } catch ( e ) { /* keep ts = 0, prune first */ }
entries.push( { key: k, ts: ts } );
}
}
entries.sort( function ( a, b ) { return a.ts - b.ts; } );
for ( var j = 0; j < Math.min( n, entries.length ); j++ ) {
s.removeItem( entries[j].key );
}
}
function getCachedResult( sparql ) {
var key = 'wdsparql:' + hashKey( sparql );
if ( store ) {
try {
var raw = store.getItem( key );
if ( raw ) {
var cached = JSON.parse( raw );
if ( Date.now() - cached.ts <= SPARQL_CACHE_TTL ) {
return cached.data;
}
store.removeItem( key );
}
} catch ( e ) { /* fall through to memory cache */ }
}
var mem = memoryCache[ key ];
if ( mem && Date.now() - mem.ts <= SPARQL_CACHE_TTL ) {
return mem.data;
}
return null;
}
function setCachedResult( sparql, data ) {
var key = 'wdsparql:' + hashKey( sparql ),
entry = { ts: Date.now(), data: data };
memoryCache[ key ] = entry;
if ( store ) {
try {
store.setItem( key, JSON.stringify( entry ) );
} catch ( e ) {
// Quota exceeded - prune the oldest wdsparql entries and try once more.
try {
pruneOldestCacheEntries( store, 5 );
store.setItem( key, JSON.stringify( entry ) );
} catch ( e2 ) {
// Give up on persistent caching; the memory cache still covers this pageview.
}
}
}
}
// --- Request queue: caps concurrency and de-dupes identical in-flight queries
var inFlight = {},
queue = [],
active = 0;
function pump() {
while ( active < SPARQL_MAX_PARALLEL && queue.length ) {
var job = queue.shift();
active++;
runQuery( job.sparql ).then(
function ( data ) { active--; pump(); job.resolve( data ); },
function ( err ) { active--; pump(); job.reject( err ); }
);
}
}
function enqueue( sparql ) {
var key = hashKey( sparql );
if ( inFlight[ key ] ) {
return inFlight[ key ];
}
var p = new Promise( function ( resolve, reject ) {
queue.push( { sparql: sparql, resolve: resolve, reject: reject } );
} );
var cleaned = p.then(
function ( result ) { delete inFlight[ key ]; return result; },
function ( err ) { delete inFlight[ key ]; throw err; }
);
inFlight[ key ] = cleaned;
pump();
return cleaned;
}
function runQuery( sparql, attempt ) {
attempt = attempt || 0;
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/sparql-results+json' },
signal: controller ? controller.signal : undefined
} )
.then( function ( r ) {
if ( timer ) { clearTimeout( timer ); }
if ( ( r.status === 429 || r.status === 503 ) && attempt < SPARQL_RETRY_MAX ) {
var wait = SPARQL_RETRY_BASE * Math.pow( 2, attempt ),
retryAfter = r.headers.get( 'Retry-After' );
if ( retryAfter && !isNaN( +retryAfter ) ) {
wait = ( +retryAfter ) * 1000;
}
return new Promise( function ( resolve ) { setTimeout( resolve, wait ); } )
.then( function () { return runQuery( sparql, attempt + 1 ); } );
}
if ( !r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function ( data ) {
setCachedResult( sparql, data );
return data;
} );
}
function fetchSparql( sparql ) {
return enqueue( sparql );
}
function commonsThumbUrl( value, width ) {
// `value` is already a percent-encoded URI straight from the SPARQL JSON
// results. Re-encoding it here (the old code's encodeURI() call) double-
// escapes any filename with spaces/accents/quotes/etc., which silently
// breaks the <img src> for those rows only - that was the root cause of
// "some images show, some don't". Just append the width param.
var thumb = value.replace( /^http:\/\//, 'https://' ),
sep = thumb.indexOf( '?' ) === -1 ? '?' : '&';
return thumb + sep + 'width=' + width;
}
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 = commonsThumbUrl( val, 100 );
html.push(
'<td><img src="', escapeHtml( thumb ), '" style="max-height:80px;" alt="" loading="lazy" ',
'onerror="this.onerror=null;this.replaceWith(document.createTextNode(\'—\'));" /></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 (Wikidata may be busy - it will use the cache on the next view).';
} );
} );
// 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 */