Jump to content

User:TChin (WMF)/ActiveUsersDemo.js

From mediawiki.org

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.
$( function () {
	if ( !$( '.mw-activeusergadget-section' ).length ) {
		return;
	}

	const RECENT = 'recent';
	const THISYEAR = 'thisyear';
	const OVERAYEAR = 'overayear';
	const localizedUserNamespace = mw.config.get( 'wgFormattedNamespaces' )[2];

	const messages = {
		en: {
			recent: 'Edited recently',
			thisyear: 'Edited this year',
			overayear: 'Edited over a year ago'
		},
		de: {
			recent: 'kürzlich bearbeitet',
			thisyear: 'in diesem Jahr bearbeitet',
			overayear: 'vor über einem Jahr bearbeitet'
		}
	};

	const localizedMessages = function () {
		const lang = mw.config.get( 'wgUserLanguage' );
		if ( lang in messages ) {
			return messages[lang];
		}
		return messages.en;
	}();

	const getLastActiveMarker = function ( timestamp ) {
		const date = Date.parse( timestamp );
		const now = Date.now();
		const diff = Math.floor( ( now - date ) / ( 1000 * 60 * 60 * 24 ) );
		var timespan = RECENT;
		if ( diff > 365 ) {
			timespan = OVERAYEAR;
		} else if ( diff > 30 ) {
			timespan = THISYEAR;
		}
		const iconPath = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) +
			'/resources/lib/ooui/themes/wikimediaui/images/icons/userContributions-ltr.svg';
		const marker =
			"<span class='mw-activeusergadget-span mw-activeusergadget-" + timespan + "'>" +
			"<img src='" + iconPath + "' class='mw-activeusergadget-filter-" + timespan + "'/> " +
			localizedMessages[timespan] + "<span>";
		return $( marker );
	};

	mw.loader.using( [ 'mediawiki.api' ], function () {
		$( '.mw-activeusergadget-section a[title^="User:"]' ).each( function() {
			const link = $( this );
			const userRegex = new RegExp(`${localizedUserNamespace}:(.*?)(?=&|\/|$)`);
			// const userRegex = /User:(.*?)(?=&|\/|$)/g;
			const href = link.attr( 'href' );
			const username = href.match(userRegex)[0];
			const x = href.split(username);
			// console.log(username);
			console.log(decodeURI(username))
			if (x[1].charAt(0) === '/') {
				return;
			}
			const api = new mw.Api();
			api.get( {
				format: 'json',
				action: 'query',
				list: 'usercontribs',
				uclimit: '1',
				ucuser: decodeURI(username)
			} ).then( function ( result ) {
				if ( result.query.usercontribs.length ) {
					const timestamp = result.query.usercontribs[0].timestamp;
					getLastActiveMarker( timestamp ).insertAfter( link );
				}
			} );
		} );
	} );
} );