Jump to content

MediaWiki:Gadget-Global-RecentEditors.js

From wikiNonStop

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/**
 * This gadget creates a table of recent editors by edit count
 */
const RecentEditors = {

	init: function () {
		$( '.RecentEditors' ).each( RecentEditors.makeTable );
	},

	makeTable: function () {
		const $div = $( this );
		const page = $div.data( 'page' );
		const days = $div.data( 'days' );
		const params = {
			action: 'feedrecentchanges',
			days: days,
			limit: 50,
			target: page,
			hidebots: true,
			hideanons: true,
			hidecategorization: true,
		};

		// Remove empty params
		for ( const param in params ) {
			const value = params[ param ];
			if ( value === null || value === '' ) {
				delete params[ param ];
			}
		}

		// Get the recent changes
		new mw.Api().get( params, { dataType: 'xml' } ).fail( console.log ).done( ( xml ) => {
			const selector = $.escapeSelector( 'dc:creator' );
			const $users = $( selector, xml );

			// Count the edits of each user
			const count = {};
			$users.each( function () {
				const user = this.textContent;
				count[ user ] = count[ user ] + 1 || 1;
			} );

			// Sort by edit count
			let top = [];
			for ( const [ name, edits ] of Object.entries( count ) ) {
				top.push( { name: name, edits: edits } );
			}
			top.sort( ( a, b ) => b.edits - a.edits );

			// Trim by limit
			const limit = $div.data( 'limit' );
			top = top.slice( 0, limit );

			// Make the table
			const userHeader = $div.data( 'user-header' ) || 'User';
			const editsHeader = $div.data( 'edits-header' ) || 'Edits';
			const $th1 = $( '<th></th>' ).text( userHeader );
			const $th2 = $( '<th></th>' ).text( editsHeader );
			const $thr = $( '<tr></tr>' ).append( $th1, $th2 );
			const $table = $( '<table class="wikitable"></table>' ).append( $thr );
			for ( const user of top ) {
				const url = mw.util.getUrl( 'User:' + user.name );
				const $link = $( '<a href="' + url + '">' + user.name + '</a>' );
				const $td1 = $( '<td></td>' ).html( $link );
				const $td2 = $( '<td></td>' ).text( user.edits );
				const $tdr = $( '<tr></tr>' ).append( $td1, $td2 );
				$table.append( $tdr );
			}

			// Add it to the DOM
			$div.html( $table );
		} );
	}
};

$( RecentEditors.init );