MediaWiki:Gadget-countdown-timer.js

From IdleOn MMO Wiki
Revision as of 05:36, 22 May 2024 by Nads (talk | contribs)

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: 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();
	});
});