MediaWiki:Gadget-Global-TopLinkedPages.js: Difference between revisions
Appearance
No edit summary |
m 1 revision imported: Initial setup |
||
(No difference)
|
Latest revision as of 18:04, 25 December 2024
/**
* This gadget creates a table of the most visited pages linked from a given page
*/
const TopLinkedPages = {
init: function () {
$( '.TopLinkedPages' ).each( TopLinkedPages.getPages );
},
getPages: function () {
const $div = $( this );
const page = $div.data( 'page' ) || mw.config.get( 'wgPageName' );
const days = $div.data( 'days' ) || 30;
const params = {
action: 'query',
titles: page,
prop: 'pageviews',
pvipdays: days,
generator: 'links',
gpllimit: 'max',
redirects: true,
formatversion: 2
};
const pages = [];
new mw.Api().get( params ).done( response => TopLinkedPages.getPagesContinue( response, params, pages, $div ) );
},
getPagesContinue: function ( response, params, pages, $div ) {
for ( const page of response.query.pages ) {
if ( !page.missing && page.pageviews && !pages.some( element => element.title === page.title ) ) {
const views = Object.values( page.pageviews ).reduce( ( a, b ) => a + b, 0 );
pages.push( { title: page.title, views: views } );
}
}
if ( response.continue ) {
const cont = response.continue.continue.split( '|' )[ 0 ];
params[ cont ] = response.continue[ cont ];
new mw.Api().get( params ).done( response => TopLinkedPages.getPagesContinue( response, params, pages, $div ) );
} else {
TopLinkedPages.makeTable( pages, $div );
}
},
makeTable: function ( pages, $div ) {
// Sort the pages by pageview count
pages.sort( ( a, b ) => b.views - a.views );
// Trim the results
const limit = $div.data( 'limit' ) || 10;
const top = pages.slice( 0, limit );
// Make the table
const pageHeader = $div.data( 'page-header' ) || 'Page';
const viewsHeader = $div.data( 'views-header' ) || 'Views';
const $th1 = $( '<th></th>' ).text( pageHeader );
const $th2 = $( '<th></th>' ).text( viewsHeader );
const $thr = $( '<tr></tr>' ).append( $th1, $th2 );
const $table = $( '<table class="wikitable"></table>' ).append( $thr );
for ( const page of top ) {
const url = mw.util.getUrl( page.title );
const $link = $( '<a href="' + url + '">' + page.title + '</a>' );
const $td1 = $( '<td></td>' ).html( $link );
const $td2 = $( '<td></td>' ).text( page.views );
const $tdr = $( '<tr></tr>' ).append( $td1, $td2 );
$table.append( $tdr );
}
// Add it to the DOM
$div.html( $table );
}
};
$( TopLinkedPages.init );