User:Daniel Quinlan/Scripts/Clock.js
"use strict";
mw.loader.using(['mediawiki.util'], function() {
function currentTime(target) {
const now = new Date();
const hh = now.getUTCHours().toString().padStart(2, '0');
const mm = now.getUTCMinutes().toString().padStart(2, '0');
const delay = 60000 - (1000 * now.getUTCSeconds() + now.getUTCMilliseconds());
target.textContent = `${hh}:${mm}`;
setTimeout(() => currentTime(target), delay);
}
function getBorderGray(computedStyle) {
const rgbMatch = computedStyle.backgroundColor.match(/\d+/g);
if (rgbMatch && rgbMatch.length === 3) {
const avg = (Number(rgbMatch[0]) + Number(rgbMatch[1]) + Number(rgbMatch[2])) / 3;
const borderGray = avg > 128 ? Math.max(avg - 32, 0) : Math.min(avg + 32, 255);
return `rgb(${borderGray}, ${borderGray}, ${borderGray})`;
}
return 'rgb(127, 127, 127)';
}
function addClock() {
const clockElement = document.createElement('div');
clockElement.className = 'utc-clock';
const computedStyle = window.getComputedStyle(document.body);
Object.assign(clockElement.style, {
position: 'fixed',
bottom: '10px',
right: '10px',
zIndex: 1000,
padding: '3px',
border: `solid 1px var(--border-color-muted, ${getBorderGray(computedStyle)})`,
color: `var(--text-color, ${computedStyle.color})`,
backgroundColor: `var(--background-color-base, ${computedStyle.backgroundColor})`,
fontSize: 'var(--font-size-medium, 16px)'
});
document.body.appendChild(clockElement);
currentTime(clockElement);
if (mw.config.get('skin') === 'timeless') {
Object.assign(clockElement.style, { backgroundColor: 'white', color: 'black' });
}
if (window.innerWidth <= 768) {
Object.assign(clockElement.style, { bottom: '2px', right: '2px', padding: '1px', fontSize: '0.8em' });
}
}
if (mw.config.get('wgAction') === 'view' && [0, 10, 12, 14, 100].includes(mw.config.get('wgNamespaceNumber')) && window.innerWidth <= 768 && !window.location.search) {
return;
}
addClock();
});