User:Saftzie/ui.clock.js

/* * Adds a UTC clock * * 29 Dec 2008: Poke  *  Original version * 8 Nov 2013: Suppa chuppa, Ryan PM, and Cqm  *  Updated for oasis and made gadget-compatible * 18 Jul 2014: Saftzie *  Refactored and rewritten, also using the interval idea from *  http://www.mediawiki.org/wiki/MediaWiki:Gadget-UTCLiveClock.js */

window.user = window.user || {}; window.user.ui = window.user.ui || {}; window.user.ui.clock = (function (mw, $) { 'use strict';

var self = {}, gdomText = document.createTextNode(''), gidTimeout = -1, // cannot run = -1; okay to run = 0; already running > 0 gbCancel = false;

// update the displayed time function onTick {   var d = new Date, s = d.toUTCString;

if (!gbCancel) {     gidTimeout = window.setTimeout(onTick, 1100 - d.getMilliseconds); gdomText.data = s.replace('GMT', '(UTC)').replace(' 0', ' ').substr(5); } }

// start the clock, if it's stopped function run {   if (gidTimeout === 0) {     gbCancel = false; onTick; } }

// stop the clock, if it's running function stop {   if (gidTimeout > 0) {     // try to stop the next tick, although it may already be too late window.clearTimeout(gidTimeout); gidTimeout = 0; gbCancel = true; } }

// insert nodes into the DOM $(function  {    var wgSkin = mw.config.get('skin'),        domA = document.createElement('a'),        domLI = document.createElement('li'),        domUL;

// make sure there's someplace to add it   if (wgSkin === 'oasis') {     domUL = document.getElementById('GlobalNavigation'); }   else // monobook {     domUL = document.getElementById('p-personal'); if (domUL) {       domUL = domUL.getElementsByTagName('ul'); if (domUL.length > 0) {         domUL = domUL[0]; }       else {         domUL = undefined; }     }    }    if (!domUL) {     self.message = 'Unable to update DOM.'; return; }

// assemble it   domA.title = 'Purge the server cache and update the contents of this page.'; domA.href = mw.config.get('wgArticlePath') .replace('$1', mw.config.get('wgPageName')) + '?action=purge'; domA.appendChild(gdomText);

domLI.id = 'pt-clock'; // the ID allows styling, if desired domLI.appendChild(domA);

// add it   if ((mw.config.get('skin') === 'oasis') && (!!domUL)) {     domUL.appendChild(domLI); }   else {     domUL.insertBefore(domLI, domUL.firstChild); }

// run it   onTick; });

self.run = run; self.stop = stop;

return self; }(mediaWiki, jQuery));