Jump to content

User:Jeeputer/defconIndicator.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Fork of [[User:Enterprisey/watchlist-notice.js]] to show defcon level
// icon on top of the page, next to the notification icon

mw.loader.using('mediawiki.util', function() {
	var showDefcon = function(icon, level) {
		$('#pt-notifications-notice').after(
			$('<li>').append(
				$('<img width="20" height="20" style="cursor:pointer;" title="Vandalism level: ' +
					level + '; Click to update!">')
				.css({
					'padding': '0.25em 0.45em 0.2em',
					'cursor': 'pointer'
				})
				.attr('src',
					'https://upload.wikimedia.org/wikipedia/commons/' +
					icon)
				.click(updateDefcon)
			)
            .css({
                'opacity': '1',
                'transition': 'opacity 0.5s'
            })
			.attr('id', 'defcon-indicator')
		);
	};
	var changeIcon = function(icon, level) {
		$('#defcon-indicator img').attr(
			'src',
			'https://upload.wikimedia.org/wikipedia/commons/' +
			icon,
			'title', 'Vandalism level: ' + level + '; Click to update!'
		);
		$('#defcon-indicator').css('opacity', '1');
	};
	var updateDefcon = function() {
		$('#defcon-indicator').css('opacity', '0');
		$.getJSON(
			mw.util.wikiScript('api'), {
				format: 'json',
				action: 'parse',
				page: 'User:EnterpriseyBot/defcon',
				prop: 'wikitext'
			}).done(function(data) {
			var colors = {
				'1': '6/6d/Ledred.png',
				'2': '8/80/Ledorange.png',
				'3': '0/0a/Ledyellow.png',
				'4': '5/58/Ledgreen.png',
				'5': '7/71/Ledblue.png'
			};
			var wikitext = data.parse.wikitext['*'];
			var level = wikitext.match(
				/\|\s*level\s*\=\s*([0-9])/)[1];
			if (level) {
				var icon = colors[level];
				if (!$('#defcon-indicator').length) {
					showDefcon(icon, level);
				} else {
					changeIcon(icon, level);
				}
			} else {
				mw.notify($('<span>Looks like the wikitext at the ' +
					'<a href="/wiki/User:EnterpriseyBot/defcon">defcon page</a> ' +
					'has been changed so the script cannot find the level.</span>'
					), {
					type: 'error',
					autoHide: 'false',
					tag: 'defcon-error'
				});
			}
		});
	};
	$(document).ready(function() {
		updateDefcon();
		window.setInterval(updateDefcon, 120000);
	});
});