UNPKG

metro4

Version:

The front-end framework for Build responsive, mobile-first projects on the web with the first front-end component library in Metro Style

1,889 lines (1,550 loc) 111 kB
/* * m4q v1.1.0, (https://github.com/olton/m4q.git) * Copyright 2018 - 2021 by Sergey Pimenov * Helper for DOM manipulation, animation, and ajax routines. * Licensed under MIT */ (function (global, undefined) { // Source: src/mode.js /* jshint -W097 */ 'use strict'; // Source: src/func.js /* global dataSet */ /* exported isDark, isTouch, isSimple, isHidden, isPlainObject, isEmptyObject, isArrayLike, str2arr, parseUnit, getUnit, setStyleProp, acceptData, dataAttr, normName, strip, dashedName, isLocalhost */ var numProps = ['opacity', 'zIndex', "order", "zoom"]; function isSimple(v){ return typeof v === "string" || typeof v === "boolean" || typeof v === "number"; } function isVisible(elem) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); } function isHidden(elem) { var s = getComputedStyle(elem); return !isVisible(elem) || +s.opacity === 0 || elem.hidden || s.visibility === "hidden"; } function not(value){ return value === undefined || value === null; } function camelCase(string){ return string.replace( /-([a-z])/g, function(all, letter){ return letter.toUpperCase(); }); } function dashedName(str){ return str.replace(/([A-Z])/g, function(u) { return "-" + u.toLowerCase(); }); } function isPlainObject( obj ) { var proto; if ( !obj || Object.prototype.toString.call( obj ) !== "[object Object]" ) { return false; } proto = obj.prototype !== undefined; if ( !proto ) { return true; } return proto.constructor && typeof proto.constructor === "function"; } function isEmptyObject( obj ) { for (var name in obj ) { if (hasProp(obj, name)) return false; } return true; } function isArrayLike (o){ return o instanceof Object && 'length' in o; } function str2arr (str, sep) { sep = sep || " "; return str.split(sep).map(function(el){ return (""+el).trim(); }).filter(function(el){ return el !== ""; }); } function parseUnit(str, out) { if (!out) out = [ 0, '' ]; str = String(str); out[0] = parseFloat(str); out[1] = str.match(/[\d.\-+]*\s*(.*)/)[1] || ''; return out; } function getUnit(val, und){ var split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(val); return typeof split[1] !== "undefined" ? split[1] : und; } function setStyleProp(el, key, val){ key = camelCase(key); if (["scrollLeft", "scrollTop"].indexOf(key) > -1) { el[key] = (parseInt(val)); } else { el.style[key] = isNaN(val) || numProps.indexOf(""+key) > -1 ? val : val + 'px'; } } function acceptData(owner){ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); } function getData(data){ try { return JSON.parse(data); } catch (e) { return data; } } function dataAttr(elem, key, data){ var name; if ( not(data) && elem.nodeType === 1 ) { name = "data-" + key.replace( /[A-Z]/g, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { data = getData( data ); dataSet.set( elem, key, data ); } else { data = undefined; } } return data; } function normName(name) { return typeof name !== "string" ? undefined : name.replace(/-/g, "").toLowerCase(); } function strip(name, what) { return typeof name !== "string" ? undefined : name.replace(what, ""); } function hasProp(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } function isLocalhost(host){ var hostname = host || window.location.hostname; return ( hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "" || hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) !== null ); } function isTouch() { return (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); } function isDark(){ var prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)") return prefersDarkScheme.matches } // Source: src/setimmediate.js /* global global */ /* * setImmediate polyfill * Version 1.0.5 * Url: https://github.com/YuzuJS/setImmediate * Copyright (c) 2016 Yuzu (https://github.com/YuzuJS) * Licensed under MIT */ (function (global) { if (global.setImmediate) { return; } var nextHandle = 1; var tasksByHandle = {}; var currentlyRunningATask = false; var registerImmediate; function setImmediate(callback) { if (typeof callback !== "function") { /* jshint -W054 */ callback = new Function("" + callback); } var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } tasksByHandle[nextHandle] = { callback: callback, args: args }; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { if (currentlyRunningATask) { setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } // global.process function installNextTickImplementation() { registerImmediate = function(handle) { global.process.nextTick(function () { runIfPresent(handle); }); }; } // web workers function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } // Browsers function installPostMessageImplementation() { var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; global.addEventListener("message", onGlobalMessage, false); registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; if ({}.toString.call(global.process) === "[object process]") { installNextTickImplementation(); } else if (global.MessageChannel) { installMessageChannelImplementation(); } else { installPostMessageImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? window : global : self)); // Source: src/core.js /* global hasProp */ var m4qVersion = "v1.1.0. Built at 05/05/2021 22:47:56"; /* eslint-disable-next-line */ var matches = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; var $ = function(selector, context){ return new $.init(selector, context); }; $.version = m4qVersion; $.fn = $.prototype = { version: m4qVersion, constructor: $, length: 0, uid: "", push: [].push, sort: [].sort, splice: [].splice, indexOf: [].indexOf, reverse: [].reverse }; $.extend = $.fn.extend = function(){ var options, name, target = arguments[ 0 ] || {}, i = 1, length = arguments.length; if ( typeof target !== "object" && typeof target !== "function" ) { target = {}; } if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { if ( ( options = arguments[ i ] ) != null ) { for ( name in options ) { if (hasProp(options, name)) target[ name ] = options[ name ]; } } } return target; }; $.assign = function(){ var options, name, target = arguments[ 0 ] || {}, i = 1, length = arguments.length; if ( typeof target !== "object" && typeof target !== "function" ) { target = {}; } if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { if ( ( options = arguments[ i ] ) != null ) { for ( name in options ) { if (hasProp(options, name) && options[name] !== undefined) target[ name ] = options[ name ]; } } } return target; }; // if (typeof window["hideM4QVersion"] === "undefined") console.info("m4q " + $.version); // Source: src/interval.js /* global $ */ var now = function(){ return Date.now(); }; $.extend({ intervalId: -1, intervalQueue: [], intervalTicking: false, intervalTickId: null, setInterval: function(fn, int){ var that = this; this.intervalId++; this.intervalQueue.push({ id: this.intervalId, fn: fn, interval: int, lastTime: now() }); if (!this.intervalTicking) { var tick = function(){ that.intervalTickId = requestAnimationFrame(tick); $.each(that.intervalQueue, function(){ var item = this; if (item.interval < 17 || now() - item.lastTime >= item.interval) { item.fn(); item.lastTime = now(); } }); }; this.intervalTicking = true; tick(); } return this.intervalId; }, clearInterval: function(id){ for(var i = 0; i < this.intervalQueue.length; i++){ if (id === this.intervalQueue[i].id) { this.intervalQueue.splice(i, 1); break; } } if (this.intervalQueue.length === 0) { cancelAnimationFrame(this.intervalTickId); this.intervalTicking = false; } }, setTimeout: function(fn, interval){ var that = this, id = this.setInterval(function(){ that.clearInterval(id); fn(); }, interval); return id; }, clearTimeout: function(id){ return this.clearInterval(id); } }); // Source: src/contains.js /* global $, not, matches, isArrayLike, isVisible */ $.fn.extend({ index: function(sel){ var el, _index = -1; if (this.length === 0) { return _index; } if (not(sel)) { el = this[0]; } else if (sel instanceof $ && sel.length > 0) { el = sel[0]; } else if (typeof sel === "string") { el = $(sel)[0]; } else { el = undefined; } if (not(el)) { return _index; } if (el && el.parentNode) $.each(el.parentNode.children, function(i){ if (this === el) { _index = i; } }); return _index; }, get: function(i){ if (i === undefined) { return this.items(); } return i < 0 ? this[ i + this.length ] : this[ i ]; }, eq: function(i){ return !not(i) && this.length > 0 ? $.extend($(this.get(i)), {_prevObj: this}) : this; }, is: function(s){ var result = false; if (this.length === 0) { return false; } if (s instanceof $) { return this.same(s); } if (s === ":selected") { this.each(function(){ if (this.selected) result = true; }); } else if (s === ":checked") { this.each(function(){ if (this.checked) result = true; }); } else if (s === ":visible") { this.each(function(){ if (isVisible(this)) result = true; }); } else if (s === ":hidden") { this.each(function(){ var styles = getComputedStyle(this); if ( this.getAttribute('type') === 'hidden' || this.hidden || styles.display === 'none' || styles.visibility === 'hidden' || parseInt(styles.opacity) === 0 ) result = true; }); } else if (typeof s === "string" && [':selected'].indexOf(s) === -1) { this.each(function(){ if (matches.call(this, s)) { result = true; } }); } else if (isArrayLike(s)) { this.each(function(){ var el = this; $.each(s, function(){ var sel = this; if (el === sel) { result = true; } }); }); } else if (typeof s === "object" && s.nodeType === 1) { this.each(function(){ if (this === s) { result = true; } }); } return result; }, same: function(o){ var result = true; if (!(o instanceof $)) { o = $(o); } if (this.length !== o.length) return false; this.each(function(){ if (o.items().indexOf(this) === -1) { result = false; } }); return result; }, last: function(){ return this.eq(this.length - 1); }, first: function(){ return this.eq(0); }, odd: function(){ var result = this.filter(function(el, i){ return i % 2 === 0; }); return $.extend(result, {_prevObj: this}); }, even: function(){ var result = this.filter(function(el, i){ return i % 2 !== 0; }); return $.extend(result, {_prevObj: this}); }, filter: function(fn){ if (typeof fn === "string") { var sel = fn; fn = function(el){ return matches.call(el, sel); }; } return $.extend($.merge($(), [].filter.call(this, fn)), {_prevObj: this}); }, find: function(s){ var res = [], result; if (s instanceof $) return s; if (this.length === 0) { result = this; } else { this.each(function () { var el = this; if (typeof el.querySelectorAll === "undefined") { return ; } res = res.concat([].slice.call(el.querySelectorAll(s))); }); result = $.merge($(), res); } return $.extend(result, {_prevObj: this}); }, contains: function(s){ return this.find(s).length > 0; }, children: function(s){ var i, res = []; if (s instanceof $) return s; this.each(function(){ var el = this; for(i = 0; i < el.children.length; i++) { if (el.children[i].nodeType === 1) res.push(el.children[i]); } }); res = s ? res.filter(function(el){ return matches.call(el, s); }) : res; return $.extend($.merge($(), res), {_prevObj: this}); }, parent: function(s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; this.each(function(){ if (this.parentNode) { if (res.indexOf(this.parentNode) === -1) res.push(this.parentNode); } }); res = s ? res.filter(function(el){ return matches.call(el, s); }) : res; return $.extend($.merge($(), res), {_prevObj: this}); }, parents: function(s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; this.each(function(){ var par = this.parentNode; while (par) { if (par.nodeType === 1 && res.indexOf(par) === -1) { if (!not(s)) { if (matches.call(par, s)) { res.push(par); } } else { res.push(par); } } par = par.parentNode; } }); return $.extend($.merge($(), res), {_prevObj: this}); }, siblings: function(s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; this.each(function(){ var el = this; if (el.parentNode) { $.each(el.parentNode.children, function(){ if (el !== this) res.push(this); }); } }); if (s) { res = res.filter(function(el){ return matches.call(el, s); }); } return $.extend($.merge($(), res), {_prevObj: this}); }, _siblingAll: function(dir, s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; this.each(function(){ var el = this; while (el) { el = el[dir]; if (!el) break; res.push(el); } }); if (s) { res = res.filter(function(el){ return matches.call(el, s); }); } return $.extend($.merge($(), res), {_prevObj: this}); }, _sibling: function(dir, s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; this.each(function(){ var el = this[dir]; if (el && el.nodeType === 1) { res.push(el); } }); if (s) { res = res.filter(function(el){ return matches.call(el, s); }); } return $.extend($.merge($(), res), {_prevObj: this}); }, prev: function(s){ return this._sibling('previousElementSibling', s); }, next: function(s){ return this._sibling('nextElementSibling', s); }, prevAll: function(s){ return this._siblingAll('previousElementSibling', s); }, nextAll: function(s){ return this._siblingAll('nextElementSibling', s); }, closest: function(s){ var res = []; if (this.length === 0) { return ; } if (s instanceof $) return s; if (!s) { return this.parent(s); } this.each(function(){ var el = this; while (el) { if (!el) break; if (matches.call(el, s)) { res.push(el); return ; } el = el.parentElement; } }); return $.extend($.merge($(), res.reverse()), {_prevObj: this}); }, has: function(selector){ var res = []; if (this.length === 0) { return ; } this.each(function(){ var el = $(this); var child = el.children(selector); if (child.length > 0) { res.push(this); } }); return $.extend($.merge($(), res), {_prevObj: this}); }, back: function(to_start){ var ret; if (to_start === true) { ret = this._prevObj; while (ret) { if (!ret._prevObj) break; ret = ret._prevObj; } } else { ret = this._prevObj ? this._prevObj : this; } return ret; } }); // Source: src/script.js /* global $, not */ function createScript(script){ var s = document.createElement('script'); s.type = 'text/javascript'; if (not(script)) return $(s); var _script = $(script)[0]; if (_script.src) { s.src = _script.src; } else { s.textContent = _script.innerText; } document.body.appendChild(s); if (_script.parentNode) _script.parentNode.removeChild(_script); return s; } $.extend({ script: function(el){ if (not(el)) { return createScript(); } var _el = $(el)[0]; if (_el.tagName && _el.tagName === "SCRIPT") { createScript(_el); } else $.each($(_el).find("script"), function(){ createScript(this); }); } }); $.fn.extend({ script: function(){ return this.each(function(){ $.script(this); }); } }); // Source: src/prop.js /* global $, not */ $.fn.extend({ _prop: function(prop, value){ if (arguments.length === 1) { return this.length === 0 ? undefined : this[0][prop]; } if (not(value)) { value = ''; } return this.each(function(){ var el = this; el[prop] = value; if (prop === "innerHTML") { $.script(el); } }); }, prop: function(prop, value){ return arguments.length === 1 ? this._prop(prop) : this._prop(prop, typeof value === "undefined" ? "" : value); }, val: function(value){ if (not(value)) { return this.length === 0 ? undefined : this[0].value; } return this.each(function(){ var el = $(this); if (typeof this.value !== "undefined") { this.value = value; } else { el.html(value); } }); }, html: function(value){ var that = this, v = []; if (arguments.length === 0) { return this._prop('innerHTML'); } if (value instanceof $) { value.each(function(){ v.push($(this).outerHTML()); }); } else { v.push(value); } that._prop('innerHTML', v.length === 1 && not(v[0]) ? "" : v.join("\n")); return this; }, outerHTML: function(){ return this._prop('outerHTML'); }, text: function(value){ return arguments.length === 0 ? this._prop('textContent') : this._prop('textContent', typeof value === "undefined" ? "" : value); }, innerText: function(value){ return arguments.length === 0 ? this._prop('innerText') : this._prop('innerText', typeof value === "undefined" ? "" : value); }, empty: function(){ return this.each(function(){ if (typeof this.innerHTML !== "undefined") this.innerHTML = ""; }); }, clear: function(){ return this.empty(); } }); // Source: src/each.js /* global $, isArrayLike, hasProp */ $.each = function(ctx, cb){ var index = 0; if (isArrayLike(ctx)) { [].forEach.call(ctx, function(val, key) { cb.apply(val, [key, val]); }); } else { for(var key in ctx) { if (hasProp(ctx, key)) cb.apply(ctx[key], [key, ctx[key], index++]); } } return ctx; }; $.fn.extend({ each: function(cb){ return $.each(this, cb); } }); // Source: src/data.js /* global acceptData, camelCase, $, not, dataAttr, isEmptyObject, hasProp */ /* * Data routines * Url: https://jquery.com * Copyright (c) Copyright JS Foundation and other contributors, https://js.foundation/ * Licensed under MIT */ var Data = function(ns){ this.expando = "DATASET:UID:" + ns.toUpperCase(); Data.uid++; }; Data.uid = -1; Data.prototype = { cache: function(owner){ var value = owner[this.expando]; if (!value) { value = {}; if (acceptData(owner)) { if (owner.nodeType) { owner[this.expando] = value; } else { Object.defineProperty(owner, this.expando, { value: value, configurable: true }); } } } return value; }, set: function(owner, data, value){ var prop, cache = this.cache(owner); if (typeof data === "string") { cache[camelCase(data)] = value; } else { for (prop in data) { if (hasProp(data, prop)) cache[camelCase(prop)] = data[prop]; } } return cache; }, get: function(owner, key){ return key === undefined ? this.cache(owner) : owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function(owner, key, value){ if (key === undefined || ((key && typeof key === "string") && value === undefined) ) { return this.get(owner, key); } this.set(owner, key, value); return value !== undefined ? value : key; }, remove: function(owner, key){ var i, cache = owner[this.expando]; if (cache === undefined) { return ; } if (key !== undefined) { if ( Array.isArray( key ) ) { key = key.map( camelCase ); } else { key = camelCase( key ); key = key in cache ? [ key ] : ( key.match( /[^\x20\t\r\n\f]+/g ) || [] ); // ??? } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } if ( key === undefined || isEmptyObject( cache ) ) { if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } return true; }, hasData: function(owner){ var cache = owner[ this.expando ]; return cache !== undefined && !isEmptyObject( cache ); } }; var dataSet = new Data('m4q'); $.extend({ hasData: function(elem){ return dataSet.hasData(elem); }, data: function(elem, key, val){ return dataSet.access(elem, key, val); }, removeData: function(elem, key){ return dataSet.remove(elem, key); }, dataSet: function(ns){ if (not(ns)) return dataSet; if (['INTERNAL', 'M4Q'].indexOf(ns.toUpperCase()) > -1) { throw Error("You can not use reserved name for your dataset"); } return new Data(ns); } }); $.fn.extend({ data: function(key, val){ var res, elem, data, attrs, name, i; if (this.length === 0) { return ; } elem = this[0]; if ( arguments.length === 0 ) { if ( this.length ) { data = dataSet.get( elem ); if ( elem.nodeType === 1) { attrs = elem.attributes; i = attrs.length; while ( i-- ) { if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } } } return data; } if ( arguments.length === 1 ) { res = dataSet.get(elem, key); if (res === undefined) { if ( elem.nodeType === 1) { if (elem.hasAttribute("data-"+key)) { res = elem.getAttribute("data-"+key); } } } return res; } return this.each( function() { dataSet.set( this, key, val ); } ); }, removeData: function( key ) { return this.each( function() { dataSet.remove( this, key ); } ); }, origin: function(name, value, def){ if (this.length === 0) { return this; } if (not(name) && not(value)) { return $.data(this[0]); } if (not(value)) { var res = $.data(this[0], "origin-"+name); return !not(res) ? res : def; } this.data("origin-"+name, value); return this; } }); // Source: src/utils.js /* global $, not, isDark, camelCase, dashedName, isPlainObject, isEmptyObject, isArrayLike, acceptData, parseUnit, getUnit, isVisible, isHidden, matches, strip, normName, hasProp, isLocalhost, isTouch */ $.extend({ device: (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase())), localhost: isLocalhost(), isLocalhost: isLocalhost, touchable: isTouch(), dark: isDark(), uniqueId: function (prefix) { var d = new Date().getTime(); if (not(prefix)) { prefix = 'm4q'; } return (prefix !== '' ? prefix + '-' : '') + 'xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); }, toArray: function(n){ var i, out = []; for (i = 0 ; i < n.length; i++ ) { out.push(n[i]); } return out; }, import: function(ctx){ var res = []; this.each(ctx, function(){ res.push(this); }); return this.merge($(), res); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, type: function(obj){ return Object.prototype.toString.call(obj).replace(/^\[object (.+)]$/, '$1').toLowerCase(); }, sleep: function(ms) { ms += new Date().getTime(); /* eslint-disable-next-line */ while (new Date() < ms){} }, isSelector: function(selector){ if (typeof selector !== 'string') { return false; } try { document.querySelector(selector); } catch(error) { return false; } return true; }, remove: function(s){ return $(s).remove(); }, camelCase: camelCase, dashedName: dashedName, isPlainObject: isPlainObject, isEmptyObject: isEmptyObject, isArrayLike: isArrayLike, acceptData: acceptData, not: not, parseUnit: parseUnit, getUnit: getUnit, unit: parseUnit, isVisible: isVisible, isHidden: isHidden, matches: function(el, s) {return matches.call(el, s);}, random: function(from, to) { if (arguments.length === 1 && isArrayLike(from)) { return from[Math.floor(Math.random()*(from.length))]; } return Math.floor(Math.random()*(to-from+1)+from); }, strip: strip, normName: normName, hasProp: hasProp, serializeToArray: function(form){ var _form = $(form)[0]; if (!_form || _form.nodeName !== "FORM") { console.warn("Element is not a HTMLFromElement"); return; } var i, j, q = []; for (i = _form.elements.length - 1; i >= 0; i = i - 1) { if (_form.elements[i].name === "") { continue; } switch (_form.elements[i].nodeName) { case 'INPUT': switch (_form.elements[i].type) { case 'checkbox': case 'radio': if (_form.elements[i].checked) { q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].value)); } break; case 'file': break; default: q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].value)); } break; case 'TEXTAREA': q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].value)); break; case 'SELECT': switch (_form.elements[i].type) { case 'select-one': q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].value)); break; case 'select-multiple': for (j = _form.elements[i].options.length - 1; j >= 0; j = j - 1) { if (_form.elements[i].options[j].selected) { q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].options[j].value)); } } break; } break; case 'BUTTON': switch (_form.elements[i].type) { case 'reset': case 'submit': case 'button': q.push(_form.elements[i].name + "=" + encodeURIComponent(_form.elements[i].value)); break; } break; } } return q; }, serialize: function(form){ return $.serializeToArray(form).join("&"); } }); $.fn.extend({ items: function(){ return $.toArray(this); } }); // Source: src/events.js /* global $, not, camelCase, str2arr, normName, matches, isEmptyObject, isPlainObject */ // (function () { // if ( typeof window.CustomEvent === "function" ) return false; // // function CustomEvent ( event, params ) { // params = params || { bubbles: false, cancelable: false, detail: null }; // var evt = document.createEvent( 'CustomEvent' ); // evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); // return evt; // } // // CustomEvent.prototype = window.Event.prototype; // // window.CustomEvent = CustomEvent; // })(); var overriddenStop = Event.prototype.stopPropagation; var overriddenPrevent = Event.prototype.preventDefault; Event.prototype.stopPropagation = function(){ this.isPropagationStopped = true; overriddenStop.apply(this, arguments); }; Event.prototype.preventDefault = function(){ this.isPreventedDefault = true; overriddenPrevent.apply(this, arguments); }; Event.prototype.stop = function(immediate){ return immediate ? this.stopImmediatePropagation() : this.stopPropagation(); }; $.extend({ events: [], eventHooks: {}, eventUID: -1, /* * el, eventName, handler, selector, ns, id, options * */ setEventHandler: function(obj){ var i, freeIndex = -1, eventObj, resultIndex; if (this.events.length > 0) { for(i = 0; i < this.events.length; i++) { if (this.events[i].handler === null) { freeIndex = i; break; } } } eventObj = { element: obj.el, event: obj.event, handler: obj.handler, selector: obj.selector, ns: obj.ns, id: obj.id, options: obj.options }; if (freeIndex === -1) { this.events.push(eventObj); resultIndex = this.events.length - 1; } else { this.events[freeIndex] = eventObj; resultIndex = freeIndex; } return resultIndex; }, getEventHandler: function(index){ if (this.events[index] !== undefined && this.events[index] !== null) { this.events[index] = null; return this.events[index].handler; } return undefined; }, off: function(){ $.each(this.events, function(){ this.element.removeEventListener(this.event, this.handler, true); }); this.events = []; return this; }, getEvents: function(){ return this.events; }, getEventHooks: function(){ return this.eventHooks; }, addEventHook: function(event, handler, type){ if (not(type)) { type = "before"; } $.each(str2arr(event), function(){ this.eventHooks[camelCase(type+"-"+this)] = handler; }); return this; }, removeEventHook: function(event, type){ if (not(type)) { type = "before"; } $.each(str2arr(event), function(){ delete this.eventHooks[camelCase(type+"-"+this)]; }); return this; }, removeEventHooks: function(event){ var that = this; if (not(event)) { this.eventHooks = {}; } else { $.each(str2arr(event), function(){ delete that.eventHooks[camelCase("before-"+this)]; delete that.eventHooks[camelCase("after-"+this)]; }); } return this; } }); $.fn.extend({ on: function(eventsList, sel, handler, options){ if (this.length === 0) { return ; } if (typeof sel === 'function') { options = handler; handler = sel; sel = undefined; } if (!isPlainObject(options)) { options = {}; } return this.each(function(){ var el = this; $.each(str2arr(eventsList), function(){ var h, ev = this, event = ev.split("."), name = normName(event[0]), ns = options.ns ? options.ns : event[1], index, originEvent; $.eventUID++; h = function(e){ var target = e.target; var beforeHook = $.eventHooks[camelCase("before-"+name)]; var afterHook = $.eventHooks[camelCase("after-"+name)]; if (typeof beforeHook === "function") { beforeHook.call(target, e); } if (!sel) { handler.call(el, e); } else { while (target && target !== el) { if (matches.call(target, sel)) { handler.call(target, e); if (e.isPropagationStopped) { e.stopImmediatePropagation(); break; } } target = target.parentNode; } } if (typeof afterHook === "function") { afterHook.call(target, e); } if (options.once) { index = +$(el).origin( "event-"+e.type+(sel ? ":"+sel:"")+(ns ? ":"+ns:"") ); if (!isNaN(index)) $.events.splice(index, 1); } }; Object.defineProperty(h, "name", { value: handler.name && handler.name !== "" ? handler.name : "func_event_"+name+"_"+$.eventUID }); originEvent = name+(sel ? ":"+sel:"")+(ns ? ":"+ns:""); el.addEventListener(name, h, !isEmptyObject(options) ? options : false); index = $.setEventHandler({ el: el, event: name, handler: h, selector: sel, ns: ns, id: $.eventUID, options: !isEmptyObject(options) ? options : false }); $(el).origin('event-'+originEvent, index); }); }); }, one: function(events, sel, handler, options){ if (!isPlainObject(options)) { options = {}; } options.once = true; return this.on.apply(this, [events, sel, handler, options]); }, off: function(eventsList, sel, options){ if (isPlainObject(sel)) { options = sel; sel = null; } if (!isPlainObject(options)) { options = {}; } if (not(eventsList) || eventsList.toLowerCase() === 'all') { return this.each(function(){ var el = this; $.each($.events, function(){ var e = this; if (e.element === el) { el.removeEventListener(e.event, e.handler, e.options); e.handler = null; $(el).origin("event-"+name+(e.selector ? ":"+e.selector:"")+(e.ns ? ":"+e.ns:""), null); } }); }); } return this.each(function(){ var el = this; $.each(str2arr(eventsList), function(){ var evMap = this.split("."), name = normName(evMap[0]), ns = options.ns ? options.ns : evMap[1], originEvent, index; originEvent = "event-"+name+(sel ? ":"+sel:"")+(ns ? ":"+ns:""); index = $(el).origin(originEvent); if (index !== undefined && $.events[index].handler) { el.removeEventListener(name, $.events[index].handler, $.events[index].options); $.events[index].handler = null; } $(el).origin(originEvent, null); }); }); }, trigger: function(name, data){ return this.fire(name, data); }, fire: function(name, data){ var _name, e; if (this.length === 0) { return ; } _name = normName(name); if (['focus', 'blur'].indexOf(_name) > -1) { this[0][_name](); return this; } if (typeof CustomEvent !== "undefined") { e = new CustomEvent(_name, { bubbles: true, cancelable: true, detail: data }); } else { e = document.createEvent('Events'); e.detail = data; e.initEvent(_name, true, true); } return this.each(function(){ this.dispatchEvent(e); }); } }); ( "blur focus resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu touchstart touchend touchmove touchcancel" ) .split( " " ) .forEach( function( name ) { $.fn[ name ] = function( sel, fn, opt ) { return arguments.length > 0 ? this.on( name, sel, fn, opt ) : this.fire( name ); }; }); $.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); $.ready = function(fn, options){ document.addEventListener('DOMContentLoaded', fn, (options || false)); }; $.load = function(fn){ return $(window).on("load", fn); }; $.unload = function(fn){ return $(window).on("unload", fn); }; $.fn.extend({ unload: function(fn){ return (this.length === 0 || this[0].self !== window) ? undefined : $.unload(fn); } }); $.beforeunload = function(fn){ if (typeof fn === "string") { return $(window).on("beforeunload", function(e){ e.returnValue = fn; return fn; }); } else { return $(window).on("beforeunload", fn); } }; $.fn.extend({ beforeunload: function(fn){ return (this.length === 0 || this[0].self !== window) ? undefined : $.beforeunload(fn); } }); $.fn.extend({ ready: function(fn){ if (this.length && this[0] === document && typeof fn === 'function') { return $.ready(fn); } } }); // Source: src/ajax.js /* global $, Promise, not, isSimple, isPlainObject, isEmptyObject, camelCase */ /* can be changed to fetch */ $.ajax = function(p){ return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(), data; var method = (p.method || "GET").toUpperCase(); var headers = []; var async = not(p.async) ? true : p.async; var url = p.url; var urlWithParams = url.indexOf("?") > -1; var joinParamsSymbol = urlWithParams ? "&" : "?"; var exec = function(fn, params){ if (typeof fn === "function") { fn.apply(null, params); } }; var isGet = function(method){ return ["GET", "JSON"].indexOf(method) !== -1; }; var plainObjectToData = function(obj){ var _data = []; $.each(obj, function(k, v){ var _v = isSimple(v) ? v : JSON.stringify(v); _data.push(k+"=" + _v); }); return _data.join("&"); }; if (p.data instanceof HTMLFormElement) { var _action = p.data.getAttribute("action"); var _method = p.data.getAttribute("method"); if (not(url) && _action && _action.trim() !== "") {url = _action;} if (_method && _method.trim() !== "") {method = _method.toUpperCase();} } if (p.timeout) { xhr.timeout = p.timeout; } if (p.withCredentials) { xhr.withCredentials = p.withCredentials; } if (p.data instanceof HTMLFormElement) { data = $.serialize(p.data); } else if (p.data instanceof HTMLElement && p.data.getAttribute("type") && p.data.getAttribute("type").toLowerCase() === "file") { var _name = p.data.getAttribute("name"); data = new FormData(); for (var i = 0; i < p.data.files.length; i++) { data.append(_name, p.data.files[i]); } } else if (isPlainObject(p.data)) { data = plainObjectToData(p.data); } else if (p.data instanceof FormData) { data = p.data; } else if (typeof p.data === "string") { data = p.data; } else { data = new FormData(); data.append("_data", JSON.stringify(p.data)); } if (isGet(method)) { url += (typeof data === "string" ? joinParamsSymbol + data : isEmptyObject(data) ? "" : joinParamsSymbol + JSON.stringify(data)); } xhr.open(method, url, async, p.user, p.password); if (p.headers) { $.each(p.headers, function(k, v){ xhr.setRequestHeader(k, v); headers.push(k); }); } if (!isGet(method)) { if (headers.indexOf("Content-type") === -1 && p.contentType !== false) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } } xhr.send(data); xhr.addEventListener("load", function(e){ if (xhr.readyState === 4 && xhr.status < 300) { var _return = p.returnValue && p.returnValue === 'xhr' ? xhr : xhr.response; if (p.parseJson) { try { _return = JSON.parse(_return); } catch (ex) { _return = {}; } } exec(resolve, [_return]); exec(p.onSuccess, [e, xhr]); } else { exec(reject, [xhr]); exec(p.onFail, [e, xhr]); } exec(p.onLoad, [e, xhr]);