MediaWiki:Gadget-countdown-timer.js: Difference between revisions

From IdleOn MMO Wiki
No edit summary
No edit summary
Line 65: Line 65:
.addClass('managed')
.addClass('managed')
.each(() => {
.each(() => {
console.log('FOUND TIMER!')
const timer = new CountdownTimer($(this));
const timer = new CountdownTimer($(this));
timers.push(timer);
timers.push(timer);

Revision as of 05:36, 22 May 2024

/* jshint esversion: 6 */

$(() => {
	
	let timers = [];
	
	class CountdownTimer {
		constructor($elem) {
			this.$elem = $elem;
			// TODO Query the element for the expiration time.
			this.expiration = Date.now() + (90 * 1000);
		}
		
		tick() {
			const time = Math.floor((this.expiration - Date.now()) / 1000);
			
			const s = time % 60;
			const m = Math.floor(time / 60) % 60;
			const h = Math.floor(time / 3600) % 24;
			const d = Math.floor(time / 86400);
			
			let text = '';
			
			let showUnit = d > 0;
			if (showUnit) {
				text += d + 'd';
			}
			
			showUnit |= h > 0;
			if (showUnit) {
				text += h + 'h';
			}
			
			showUnit |= m > 0;
			if (showUnit) {
				text += m + 'm';
			}
			
			showUnit |= s > 0;
			if (showUnit) {
				text += s + 's';
			}
			
			$elem.text(text);
			
			return time > 0;
		}
	}
	
	function tick() {
		// Tick and automatically remove expired timers.
		timers = timers.filter(t => t.tick());
		if (timers.length != 0) {
			setTimeout(tick, 1000);
		}
	}
	
	mw.hook('wikipage.content').add($content => {
		const $targets = $content.find('time.countdown-timer:not(.managed)');
		if ($targets.length == 0) {
			return;
		}
		
		$targets
			.addClass('managed')
			.each(() => {
				console.log('FOUND TIMER!')
				const timer = new CountdownTimer($(this));
				timers.push(timer);
			});
			
		tick();
	});
});