MediaWiki:UI-js/code.js

/** * Name:       UI-js * Author:     KockaAdmiralac <1405223@gmail.com> * Description: Library for easier UI creation and manipulation * Version:    v1.0 */ (function(mw) {   'use strict';    // Prevent double loading    if(window.dev && window.dev.ui) {        return;    }

/**    * Goes through each property of an object * @param {Object} obj Object to go through * @param {Function} cb Function to call when a property is found */   function each(obj, cb) { if(typeof obj === 'object') { for(var i in obj) { // Don't check if the property is valid because // we assume those are plain objects if(typeof cb === 'function') { cb(i, obj[i]); }           }        }    }

/**    * Creates a DOM node with a given type * @param {String} type Type of the DOM node * @returns {Node} Requested DOM node */   function createNode(type) { switch(type) { case '#text': return document.createTextNode(''); case undefined: case '#document-fragment': return document.createDocumentFragment; default: return document.createElement(type); }   }

/**    * Main method of the library * @param {Object} opt Options for creating an element * @param {Node} parent Which DOM node to append to    *                      Used for children property in options *                     This parameter should not be used by users * @returns {Node} Node with given options */   function main(opt, parent) { if(typeof opt === 'string') { opt = { type: '#text', text: opt };       } else if(typeof opt !== 'object') { throw new Error('Options parameter incorrect!'); }       if('condition' in opt && !opt.condition) { return; }       var el = createNode(opt.type); if(typeof opt.text === 'string') { el.textContent = opt.text; }       if(typeof opt.html === 'string') { el.innerHTML = opt.text; }       each(opt.attr, function(k, v) {            el.setAttribute(k, v);        }); each(opt.data, function(k, v) {           el.setAttribute('data-' + k, v);        }); each(opt.style, function(k, v) {           el.style[k.toLowerCase.replace(/-(\w)/g, function(_, a) { return a.toUpperCase; })] = v;       }); each(opt.events, function(k, v) {           el.addEventListener(k, v);        }); if(typeof opt.checked === 'boolean') { el.checked = opt.checked; }       if(opt.children instanceof Array) { opt.children.forEach(function(c) {               main(c, el);            }); }       if(parent instanceof Node) { parent.appendChild(el); } else if(typeof opt.parent === 'string') { document.querySelectorAll(opt.parent).forEach(function(n) {               n.appendChild(el);            }); }       return el; }

// Expose the library function window.dev = window.dev || {}; window.dev.ui = main;

// Fire the hook so users know the loading has finished mw.hook('dev.ui').fire(window.dev.ui);

})(window.mediaWiki);