User:TChin (WMF)/ActiveUsersDemo.js

/* 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)) { getUserTimestamp(userPage) .then(timestamp => {					console.log([decodeURI(userPage), 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 getUserTimestamp(username) { const api = new mw.Api; const timestamp = api.get( {				format: 'json',				action: 'query',				list: 'usercontribs',				uclimit: '1',				ucuser: decodeURI(username)			} ).then( ( result ) => {				if ( result.query.usercontribs.length ) {					const timestamp = result.query.usercontribs[0].timestamp;					return timestamp;				} else {					return null;				}			} ); return timestamp; }	} })