/*!
* @smilefdd/js-mate v0.0.2
* LICENSE : MIT
* (c) 2017-2018 https://sakitam-fdd.github.io/js-mate
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Mate = factory());
}(this, (function () { 'use strict';
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var MAX_SAFE_INTEGER = 9007199254740991;
var funcToString = Function.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var objectCtorString = funcToString.call(Object);
var objectProto = Object.prototype;
var toString = objectProto.toString;
var symToStringTag = typeof Symbol !== 'undefined' ? Symbol.toStringTag : undefined;
var baseGetTag = function baseGetTag(value) {
if (value === null) {
return value === undefined ? '[object Undefined]' : '[object Null]';
}
if (!(symToStringTag && symToStringTag in Object(value))) {
return toString.call(value);
}
var isOwn = hasOwnProperty.call(value, symToStringTag);
var tag = value[symToStringTag];
var unmasked = false;
try {
value[symToStringTag] = undefined;
unmasked = true;
} catch (e) {}
var result = toString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
};
var TypeOf = function TypeOf(ob) {
return Object.prototype.toString.call(ob).slice(8, -1).toLowerCase();
};
var isFunction = function isFunction(value) {
if (!isObject(value)) {
return false;
}
var tag = baseGetTag(value);
return tag === '[object Function]' || tag === '[object AsyncFunction]' || tag === '[object GeneratorFunction]' || tag === '[object Proxy]';
};
var isObject = function isObject(value) {
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
return value !== null && (type === 'object' || type === 'function');
};
var isLength = function isLength(value) {
return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
};
var isArray = function isArray(arr) {
return Array.isArray(arr);
};
var isArrayLike = function isArrayLike(value) {
return value !== null && typeof value !== 'function' && isLength(value.length);
};
var isString = function isString(value) {
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
return type === 'string';
};
var toArray$1 = function toArray$$1(obj) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
var arr = [];
var i = obj.length;
while (i--) {
arr[i] = obj[i];
}
return arr;
}
};
var unique = function unique(arrayLike) {
try {
return Array.prototype.filter.call(arrayLike, function (item, idx) {
return arrayLike.indexOf(item) === idx;
});
} catch (e) {
if (!arrayLike.length) return arrayLike;
var res = [arrayLike[0]];
for (var i = 1; i < arrayLike.length; i++) {
if (res.indexOf(arrayLike[i]) < 0) {
res.push(arrayLike[i]);
}
}
return res;
}
};
var extend = function extend(target, ob) {
for (var i in ob) {
Object.hasOwnProperty();
target[i] = ob[i];
}
return target;
};
var isFormData = function isFormData(val) {
return typeof FormData !== 'undefined' && val instanceof FormData;
};
var encode = function encode(val) {
return encodeURIComponent(val).replace(/%40/gi, '@').replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');
};
var formatParams = function formatParams(data) {
var arr = [];
for (var name in data) {
var value = data[name];
if (isObject(value)) {
value = JSON.stringify(value);
}
arr.push(encode(name) + '=' + encode(value));
}
return arr.join('&');
};
var merge = function merge(a, b) {
for (var key in b) {
if (!a.hasOwnProperty(key)) {
a[key] = b[key];
} else if (isObject(b[key]) && isObject(a[key])) {
merge(a[key], b[key]);
}
}
return a;
};
var RegExpression = {
singleTagRE: /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
fragmentRE: /^\s*<(\w+|!)[^>]*>/,
tagExpanderRE: /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
table: document.createElement('table'),
tableRow: document.createElement('tr'),
containers: {
'*': document.createElement('div'),
'tr': document.createElement('tbody'),
'tbody': document.createElement('table'),
'thead': document.createElement('table'),
'tfoot': document.createElement('table'),
'td': document.createElement('tr'),
'th': document.createElement('tr')
}
};
var wrapMap = {
legend: {
intro: '
'
},
area: {
intro: ''
},
param: {
intro: ''
},
thead: {
intro: ''
},
tr: {
intro: ''
},
col: {
intro: ''
},
td: {
intro: ''
}
};
var Events = function () {
function Events() {
classCallCheck(this, Events);
this._events = Object.create(null);
this._hasHookEvent = false;
}
Events.prototype.on = function on(event, fn) {
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
this.on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
vm.addListener(event, fn, vm);
if (Events.hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm;
};
Events.prototype.once = function once(event, fn) {
var vm = this;
function on() {
vm.off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.on(event, on);
return vm;
};
Events.prototype.off = function off(event, fn) {
var vm = this;
if (!arguments.length) {
vm._events = Object.create(null);
return vm;
}
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
this.off(event[i], fn);
}
return vm;
}
var cbs = vm._events[event];
if (!cbs) {
return vm;
}
if (!fn) {
vm._events[event] = null;
return vm;
}
if (fn) {
var cb = void 0;
var _i = cbs.length;
while (_i--) {
cb = cbs[_i];
if (cb === fn || cb.fn === fn) {
vm.removeListener(event, fn, vm);
cbs.splice(_i, 1);
break;
}
}
}
return vm;
};
Events.prototype.emit = function emit(event) {
var vm = this;
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray$1(cbs) : cbs;
var args = toArray$1(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm;
};
Events.prototype.addListener = function addListener(event, fn, context) {
var vm = context || this;
var handler = vm[event];
if (handler) {
return this;
} else if (isArrayLike(vm)) {
handler = function handler(e) {
return fn.call(context || vm, e);
};
if ('addEventListener' in vm[0]) {
vm[0].addEventListener(event, handler, false);
} else if ('attachEvent' in vm[0]) {
vm[0].attachEvent('on' + event, handler);
}
vm[event] = handler;
return this;
} else {
handler = function handler(e) {
return fn.call(context || vm, e);
};
if ('addEventListener' in vm) {
vm.addEventListener(event, handler, false);
} else if ('attachEvent' in vm) {
vm.attachEvent('on' + event, handler);
}
vm[event] = handler;
return this;
}
};
Events.prototype.removeListener = function removeListener(event, fn, context) {
var vm = this;
var handler = vm[event];
if (handler) {
return this;
} else if (isArrayLike(vm)) {
if ('removeEventListener' in vm[0]) {
vm[0].removeEventListener(event, handler, false);
} else if ('detachEvent' in vm[0]) {
vm[0].detachEvent('on' + event, handler);
}
vm[event] = null;
return this;
} else {
if ('removeEventListener' in vm) {
vm.removeEventListener(event, handler, false);
} else if ('detachEvent' in vm) {
vm.detachEvent('on' + event, handler);
}
vm[event] = null;
return this;
}
};
return Events;
}();
Events.hookRE = /^hook:/;
var Prototype = function (_Events) {
inherits(Prototype, _Events);
function Prototype() {
classCallCheck(this, Prototype);
var _this = possibleConstructorReturn(this, _Events.call(this));
_this._events = Object.create(null);
_this._hasHookEvent = false;
return _this;
}
Prototype.prototype.ready = function ready(callback) {
if (/complete|loaded|interactive/.test(document.readyState) && document.body) {
callback(ElementSelector);
} else {
this.on('DOMContentLoaded', function () {
callback(ElementSelector);
}, false);
}
return this;
};
Prototype.prototype.each = function each$$1(callback) {
this.every(function (el, idx) {
return callback.call(el, el, idx) !== false;
});
return this;
};
Prototype.prototype.text = function text(s, type) {
type = type || 'textContent';
if (s) {
type = this.each(function (e) {
e[type] = s;
});
} else {
type = this[0] ? this[0][type] : '';
}
return type;
};
Prototype.prototype.html = function html(s) {
return this.text(s, 'innerHTML');
};
Prototype.prototype.hasClass = function hasClass(cls) {
var first = this[0];
if (!(first && first.className)) return false;
return !!first.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
Prototype.prototype.addClass = function addClass(cls) {
return this.each(function (f) {
if (!ElementSelector(f).hasClass(cls)) {
f.className += ' ' + cls;
}
});
};
Prototype.prototype.removeClass = function removeClass(cls) {
return this.each(function (f) {
if (ElementSelector(f).hasClass(cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
f.className = f.className.replace(reg, ' ');
}
});
};
Prototype.prototype.eq = function eq(index) {
return ElementSelector(this[index]);
};
Prototype.prototype.first = function first() {
return ElementSelector(this[0]);
};
Prototype.prototype.last = function last() {
return ElementSelector(this[this.length - 1]);
};
Prototype.prototype.parents = function parents(selector) {
var n = ElementSelector(selector);
var t = [];
this.each(function (e) {
e = ElementSelector(e).parent();
for (; e.length > 0;) {
if (n.indexOf(e[0]) > -1) {
t.push(e[0]);
break;
}
e = e.parent();
}
});
return ElementSelector(t);
};
Prototype.prototype.children = function children() {
var t = [];
this.each(function (e) {
t.push.apply(t, e.childNodes);
});
return ElementSelector(t.filter(function (e) {
return e.nodeType === 1;
}));
};
Prototype.prototype.css = function css(mix, value) {
var target = {};
if (value) {
target[mix] = value;
} else if (isObject(mix)) {
target = mix;
}
if (JSON.stringify(target) !== '') {
return this.each(function (ele) {
extend(ele.style, target);
});
} else {
return this[0] && getComputedStyle(this[0])[mix];
}
};
Prototype.prototype.hide = function hide() {
return this.each(function (ele) {
if (ElementSelector(ele).css('display') !== 'none') {
ElementSelector(ele).css('display', 'none');
}
});
};
Prototype.prototype.show = function show() {
return this.each(function (ele) {
ElementSelector(ele).css('display', 'block');
});
};
Prototype.prototype.attr = function attr(name, value) {
if (value !== undefined) {
return this.each(function (ele) {
if (name === 'value') {
ele.value = value;
} else {
ele.setAttribute(name, value);
}
});
} else {
return this[0] ? this[0].getAttribute(name) : '';
}
};
Prototype.prototype.val = function val(value) {
if (!value) {
return this[0] ? this[0].value : '';
} else {
return this.attr('value', value);
}
};
Prototype.prototype.removeAttr = function removeAttr(name) {
return this.each(function (ele) {
ele.removeAttribute(name);
});
};
Prototype.prototype.find = function find(selector) {
var target = [];
this.each(function (ele) {
var list = ele.querySelectorAll(selector);
list && target.push.apply(target, list);
});
return ElementSelector(target);
};
Prototype.prototype.append = function append(content) {
return this.each(function (e, index) {
if (index > 0 && (isObject(content) || content.trim() || content.trim()[0] !== '<')) {
return false;
}
ElementSelector(content).each(function (x) {
e.appendChild(x);
});
});
};
Prototype.prototype.appendTo = function appendTo(selector) {
ElementSelector(selector).eq(0).append(this);
return this;
};
Prototype.prototype.before = function before(ref) {
var source = ElementSelector(ref);
return this.each(function (e) {
source.parent()[0].insertBefore(e, source[0]);
});
};
Prototype.prototype.remove = function remove() {
return this.each(function (e) {
ElementSelector(e).parent()[0].removeChild(e);
});
};
Prototype.prototype.trigger = function trigger(event) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(event, true, true);
return this.each(function (e) {
e.dispatchEvent(evt);
});
};
return Prototype;
}(Events);
var parseDom = function parseDom(HTMLString) {
var tmp = document.createElement('div');
var tag = /[\w:-]+/.exec(HTMLString)[0];
var inMap = wrapMap[tag];
var validHTML = HTMLString.trim();
if (inMap) {
validHTML = inMap.intro + validHTML + inMap.outro;
}
tmp.insertAdjacentHTML('afterbegin', validHTML);
var node = tmp.lastChild;
if (inMap) {
var i = inMap.outro.match(/]*>/.test(selector)) {
domInstance = [parseDom(selector)];
} else {
domInstance = context && context instanceof ElementSelector ? context.find(selector) : selectElements(selector);
}
} else if (isArray(selector)) {
domInstance = selector;
} else if (selector instanceof NodeList || selector instanceof HTMLCollection) {
domInstance = toArray$1(selector);
} else if (selector instanceof ElementSelector) {
domInstance = selector;
} else {
domInstance = selector ? [selector] : [];
}
Array.prototype.push.apply(_this, unique(domInstance));
return _this;
}
return ElementSelector;
}(Prototype);
var Ajax = function () {
function Ajax(engine) {
classCallCheck(this, Ajax);
this.engine = engine || XMLHttpRequest;
this.interceptors = {
response: {
use: function use(handler, onerror) {
this.handler = handler;
this.onerror = onerror;
}
},
request: {
use: function use(handler) {
this.handler = handler;
}
}
};
this.config = {
method: 'GET',
baseURL: '',
headers: {},
timeout: 0,
withCredentials: false
};
}
Ajax.prototype.request = function request(url, data, options) {
var _this = this;
var engine = new this.engine();
var promise = new Promise(function (_resolve, _reject) {
options = options || {};
var defaultHeaders = {
'Content-type': 'application/x-www-form-urlencoded'
};
merge(defaultHeaders, _this.config.headers);
_this.config.headers = defaultHeaders;
merge(options, _this.config);
var rqi = _this.interceptors.request;
var rpi = _this.interceptors.response;
options.body = data || options.body;
var abort = false;
var operate = {
reject: function reject(e) {
abort = true;
_reject(e);
},
resolve: function resolve(d) {
abort = true;
_resolve(d);
}
};
url = url ? url.trim() : '';
options.method = options.method.toUpperCase();
options.url = url;
if (rqi.handler) {
options = rqi.handler(options, operate);
if (!options) return;
}
if (abort) return;
url = options.url ? options.url.trim() : '';
if (!url) url = location.href;
var baseUrl = options.baseURL ? options.baseURL.trim() : '';
if (url.indexOf('http') !== 0) {
var isAbsolute = url[0] === '/';
if (!baseUrl) {
var arr = location.pathname.split('/');
arr.pop();
baseUrl = location.protocol + '//' + location.host + (isAbsolute ? '' : arr.join('/'));
}
if (baseUrl[baseUrl.length - 1] !== '/') {
baseUrl += '/';
}
url = baseUrl + (isAbsolute ? url.substr(1) : url);
var t = document.createElement('a');
t.href = url;
url = t.href;
}
var responseType = options.responseType ? options.responseType.trim() : '';
engine.withCredentials = !!options.withCredentials;
var isGet = options.method === 'GET';
if (isGet) {
if (options.body) {
data = formatParams(options.body);
url += (url.indexOf('?') === -1 ? '?' : '&') + data;
}
}
engine.open(options.method, url);
try {
engine.timeout = options.timeout || 0;
if (responseType !== 'stream') {
engine.responseType = responseType;
}
} catch (e) {}
if (['object', 'array'].indexOf(TypeOf(options.body)) !== -1) {
options.headers['Content-type'] = 'application/json;charset=utf-8';
data = JSON.stringify(options.body);
}
for (var k in options.headers) {
if (k.toLowerCase() === 'content-type' && (isFormData(options.body) || !options.body || isGet)) {
delete options.headers[k];
} else {
try {
engine.setRequestHeader(k, options.headers[k]);
} catch (e) {}
}
}
var onerror = function onerror(e) {
if (rpi.onerror) {
e = rpi.onerror(e, operate);
}
return e;
};
engine.onload = function () {
if (engine.status >= 200 && engine.status < 300 || engine.status === 304) {
var response = engine.response || engine.responseText;
if ((engine.getResponseHeader('Content-Type') || '').indexOf('json') !== -1 && !isObject(response)) {
response = JSON.parse(response);
}
var _data = { data: response, engine: engine, request: options };
merge(_data, engine._response);
if (rpi.handler) {
_data = rpi.handler(_data, operate) || _data;
}
if (abort) return;
_resolve(_data);
} else {
var err = new Error(engine.statusText);
err.status = engine.status;
err = onerror(err) || err;
if (abort) return;
_reject(err);
}
};
engine.onerror = function (e) {
var err = new Error(e.msg || 'Network Error');
err.status = 0;
err = onerror(err);
if (abort) return;
_reject(err);
};
engine.ontimeout = function () {
var err = new Error('timeout [ ' + engine.timeout + 'ms ]');
err.status = 1;
err = onerror(err);
if (abort) return;
_reject(err);
};
engine._options = options;
engine.send(isGet ? null : data);
});
promise.engine = engine;
return promise;
};
Ajax.prototype.get = function get$$1(url, data, options) {
return this.request(url, data, options);
};
Ajax.prototype.post = function post(url, data, options) {
return this.request(url, data, merge({ method: 'POST' }, options));
};
Ajax.prototype.all = function all(promises) {
return Promise.all(promises);
};
Ajax.prototype.spread = function spread(callback) {
return function (arr) {
return callback.apply(null, arr);
};
};
return Ajax;
}();
var Meta = function Meta(selector, context) {
return new ElementSelector(selector, context);
};
Meta.ajax = new Ajax();
return Meta;
})));