User:Arashiryuu0/global.js

/** * Testing out UCP global JS. * @namespace UCPGlobal */ // jshint browser: true, devel: true, jquery: true // jshint strict: true, freeze: true, eqeqeq: true, futurehostile: true // jshint newcap: true, noarg: true, quotmark: single, shadow: outer // jshint latedef: true, undef: true, unused: true /* global mw, Promise, Symbol, requestIdleCallback */ window.CodeblockLinesConfig = { ready: false };	'use strict'; if (window.UCP && window.UCP.globalJS) return; var has = Object.prototype.hasOwnProperty, slice = Array.prototype.slice, pages = ['js', 'css', 'json', 'javascript'], levels = ['log', 'info', 'warn', 'debug', 'error'], toString = Object.prototype.toString, preloads = 2, extension = window.location.pathname.split('.').pop; function isNil (n) { return n === undefined || n === null; }	function create (type, props) { if (typeof type !== 'string') return; var e = document.createElement(type); if (!isNil(props) && toString.call(props) === '[object Object]') { Object.assign(e, props); if (props.style) Object.assign(e.style, props.style); }		return e;	} function queryTree (tree, query, options) { if (isNil(options)) options = {}; options.walkable = isNil(options.walkable) ? Object.keys(tree) : options.walkable; options.ignore = isNil(options.ignore) ? [] : options.ignore; if (typeof query === 'string') { if (has.call(tree, query)) return tree[query]; } else if (query(tree)) { return tree; }		if (isNil(tree)) return null; var ret = null, len, i; if (Array.isArray(tree)) { for (i = 0, len = tree.length; i < len; i++) { var value = tree[i]; ret = queryTree(value, query, options); if (!isNil(ret)) return ret; }		} else { for (i = 0, len = options.walkable.length; i < len; i++) { var key = options.walkable[i]; if (!has.call(tree, key) || options.ignore.includes(key)) continue; ret = queryTree(tree[key], query, options); if (!isNil(ret)) return ret; }		}		return ret; }	function getFromHook (hookName) { if (typeof hookName !== 'string') return Promise.reject('Invalid hook name, hook names must be strings.'); return new Promise(function (resolve) {			mw.hook(hookName).add(resolve);		}); }	function getHookValues { var args = slice.call(arguments); function mapHooks (hookName) { return getFromHook(hookName); }		if (!args.length) return []; return args.map(mapHooks); }	function run { var Logger = Object.create(null), myHook = mw.hook('window.ready'); function getParts (name) { return [ '%c[' + name + ']%c \u2014 %s', 'color: #C3E88D;', '',				new Date.toUTCString ];		}		function getLevel (level) { return levels.includes(level) ? level : 'log'; }		function _log (props) { if (toString.call(props) !== '[object Object]') return null; var name = 'Logger|', type = getLevel(props.type); name += type; return function { console.group.apply(null, getParts(name)); console[type].apply(null, arguments); console.groupEnd; };		}		levels.forEach(function (level) {			Object.defineProperty(Logger, level, { value: _log({ type: level }) });		});		Object.defineProperty(Logger, Symbol.toStringTag, {			configurable: false,			writable: false,			value: 'Logger'		}); Object.freeze(Logger); window.importArticles.apply(null, [			{				type: 'script',				articles: [					'u:dev:MediaWiki:Toasts.js',					'u:dev:MediaWiki:Preact.js',					'u:dev:MediaWiki:View_Source/code.js',					'u:dev:MediaWiki:CodeblockLineNumbers/code.js'				]			},			{				type: 'style',				articles: [					'u:dev:MediaWiki:CodeblockLineNumbers.css'				]			}		]); ;(function {			if (window.hljs) return;			[				'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/atom-one-dark.min.css',				'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/highlight.min.js'			].forEach(function (url, index) { var isCss = index === 0, type = isCss ? 'text' : 'script'; $.get(url, void 0, $.noop, type).then(function {					if (isCss) {						var link = create('link', { href: url, rel: 'stylesheet' });						document.head.appendChild(link);					} else {						mw.hook('ext.hljs').fire(window.hljs);					}					--preloads;				}, Logger.error); });		});		/**		 * Change source editor theme. * @returns {void} */		;(function {		    var isEditPage = window.location.search === '?action=edit';			if (!isEditPage || !pages.includes(extension)) return;			mw.hook('codeEditor.configure').add(function  { var editor = window.ace.edit(document.querySelector('.editor.ace_editor')); requestAnimationFrame(function {					editor.setTheme('ace/theme/tomorrow_night');				}); });		});		/**		 * Codeblock theme buttons */		;(function {			if (!pages.includes(extension)) return;			var base = 'https://dev.fandom.com/wiki/MediaWiki:Highlight-js/styles/',				themes = [					'atom-one-dark',					'tomorrow-night',					'solarized-dark',					'monokai-sublime',					'dracula',					'vs2015',					'nord'				],				buttons = [],				container = create('div');			container.setAttribute('id', 'code-button-container');			container.setAttribute('style', 'display: block; padding: 5px 0 10px 0; text-align: center;');			function handleLinks (links, activeTheme) {				var found = links.find(function (link) { return link.getAttribute('href').includes(activeTheme); });				links.forEach(function (link) { if (link.getAttribute('disabled') !== null) return; link.setAttribute('disabled', ''); });				if (!found) {					var fresh = create('link', { href: base + activeTheme + '.css?action=raw&ctype=text/css', rel: 'stylesheet' });					document.head.appendChild(fresh);					return;				}				found.removeAttribute('disabled');			}			function setTheme (theme) {				var links = slice.call(document.querySelectorAll('link[href*="' + base + '"]'));				requestAnimationFrame(function { handleLinks(links, theme); });			}			function buttonClick (button) {				var theme = button.getAttribute('data-theme');				return function {					if (!theme) return;					setTheme(theme);				};			}			function addButtons  {				if (buttons.length || document.contains(container)) return;				var target = document.getElementById('mw-clearyourcache');				if (!target) return;				themes.forEach(function (theme, idx) { if (idx === 4) { var n = create('hr', {							style: {								visibility: 'hidden',								margin: '0'							}						}); buttons.push(n); }					var btn = create('div', {						className: 'wds-button',						textContent: theme					}); btn.setAttribute('data-theme', theme); btn.setAttribute('style', 'margin-right: 2px;'); btn.addEventListener('click', buttonClick(btn)); buttons.push(btn); });				buttons.forEach(function (button) { container.appendChild(button); });				target.appendChild(container);			}			mw.hook('wikipage.content').add(addButtons);		}); function ready (modules) { if (preloads > 0) return setTimeout(ready, 1000, modules); var toasts = modules[1], lines = modules[2], utils = { '$': $,				'mw': mw, 'pull': window.importArticles, 'lines': lines, 'logger': Logger, 'toasts': toasts, 'queryTree': queryTree };			Object.freeze(utils); myHook.fire(utils); }		myHook.add(function (utils) {			var highlightTheme = document.head.querySelector('link[href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/atom-one-dark.min.css"]'),				href = highlightTheme && highlightTheme.getAttribute('href');			// if (utils.lines) utils.lines.process;			if (utils.logger) utils.logger.log('tools', utils);			if (href) {				requestAnimationFrame(function { href = href.replace(/atom-one-(light|dark)/, 'vs2015'); highlightTheme.setAttribute('href', href); });			}			window.UCP.tools = utils;		}); function all (promises, callback) { return Promise.all(promises).then(callback, Logger.error); }		function useHljs (deps) { var hljs = deps[0], lines = deps[2]; if (!hljs || !lines) return; function paint (element) { requestAnimationFrame(function {					hljs.highlightBlock(element);					requestAnimationFrame(function  { if (pages.includes(extension)) { element.classList.add(hljs.getLanguage(extension).name.toLowerCase); }						requestAnimationFrame(function {							lines.process;						}); });				});			}			document.querySelectorAll('.mw-highlight pre').forEach(paint); }		all(getHookValues('ext.hljs', 'dev.toasts', 'dev.CodeblockLineNumbers'), function (deps) {			ready(deps);			useHljs(deps);		}); }	window.UCP = window.UCP || {}; window.UCP.globalJS = { version: '1.0.0' };	mw.hook('dev.preact').add(function (Preact) {		var h = Preact.h,			render = Preact.render,			useRef = Preact.useRef,			useMemo = Preact.useMemo, // jshint ignore: line			useState = Preact.useState,			useEffect = Preact.useEffect,			useReducer = Preact.useReducer, // jshint ignore: line			useCallback = Preact.useCallback,			useLayoutEffect = Preact.useLayoutEffect;		function useAnimationFrame (callback) {			var fn = useRef(callback),				frame = useRef,				animate = useCallback(function (now) { fn.current(now); frame.current = requestAnimationFrame(animate); }, []);			useLayoutEffect(function { frame.current = requestAnimationFrame(animate); return function { if (frame.current) cancelAnimationFrame(frame.current); };			}, []);		}		function useInterval (callback, delay) { // jshint ignore: line			var ref = useRef(callback),				tick = useCallback(function { ref.current; }, []);			useLayoutEffect(function { ref.current = callback; }, [callback]);			useEffect(function { var id = setInterval(tick, id); return function { clearInterval(id); };			}, [delay]);		}		function getClockState {			var date = new Date,				lang = mw.user.options.get('language') || 'en-gb';			return {				day: date.toLocaleDateString(lang, { weekday: 'long' }),				time: date.toLocaleTimeString(lang, { hour12: false })			};		}		function Clock  {			var _d = useState(getClockState),				hovered = useState(false),				update = useCallback(function  { _d.set(getClockState); }, []);			useAnimationFrame(update);			return h('span', { className: 'clock', children: [ h('span', {						className: 'clock-day',						children: _d.value.day					}), h('span', {						className: 'clock-separator',						children: String.fromCharCode(160)					}), h('span', {						className: 'clock-time',						children: _d.value.time					}) ],				onMouseEnter: function (e) { if (hovered.value) return; e.target.classList.add('hovered'); hovered.set(true); },				onMouseLeave: function (e) { if (!hovered.value) return; e.target.classList.remove('hovered'); hovered.set(false); },				onClick: function { location.href = location.href; }			});		}		function addClock {			if (document.getElementById('DisplayClock')) return;			var timeRoot = create('div', { id: 'DisplayClock' }),				target = document.querySelector('.fandom-community-header__top-container + .fandom-community-header__local-navigation');			target.appendChild(timeRoot);			render(h(Clock), timeRoot);		}		addClock;	}); requestIdleCallback(run); }); /*@end@*/
 * (function {