User:TChin (WMF)/ActiveUsersDemo.js

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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* jshint esversion: 8 */
mw.loader.using(['moment', 'oojs-ui-core'], async (require) => {
	const page = mw.config.get( 'wgPageName' );
	
	// if(page !== 'Community_Wishlist_Survey_2022/Bots_and_gadgets/Gadget:_Who_is_active') {
	// 	return;
	// }
	
	const container = document.getElementById('mw-content-text');

	const button = new OO.ui.ButtonWidget( {
			label: 'Show active users!'
		} );
		
	button.on( 'click', () => {
		runGadget(container);
	} );
	container.insertAdjacentElement('afterbegin', button.$element[0] )
	
	async function runGadget(container) {
		const links = Array.from(container.getElementsByTagName('a'));
		
		// Turns the array of link elements to filtered object of user page => link element
		const userLinks = links.reduce((users, link) => {
			const href = link.getAttribute('href') ?? '';
			
			// Extracts from `User:` up to `?`, `\`, or end of string
			const userRegex = /User:(.*?)(?=&|\/|$)/g;
			const user = href.match(userRegex);
			if (user != null) {
				users[user[0]] = link;
			}
			return users;
		}, {});
		
		console.log(userLinks);
		
		const moment = require( 'moment' );
		
		// Gets last edit and asynchronously injects timestamp next to username on page
		for (const [userPage, userLink] of Object.entries(userLinks)) {
			getUser(userPage)
				.then(timestamp => {
					const toInsert = document.createElement('time');
					const lastActive = moment(timestamp).fromNow();
					toInsert.innerHTML = ` (Last active ${lastActive})`;
					toInsert.setAttribute('datetime', timestamp);
					userLink.insertAdjacentElement('beforeend', toInsert)
				}, err => {
					console.log(err)
				});
		}
		
		async function getUser(user) {
			const res = await fetch(
				`https://meta.wikimedia.org/w/api.php?action=query&format=json&list=usercontribs&uclimit=1&ucuser=${user}&ucprop=ids%7Ctitle%7Ctimestamp`
				);
			const resJson = await res.json();
			return resJson.query.usercontribs[0]?.timestamp ?? null;
		}
	}
})