UNPKG

@olton/dom

Version:

DOM - Work with HTML elements, animation HTML elements and props, and ajax routines. JQuery replacer.

1,748 lines (1,745 loc) 96.8 kB
/*! * DOM - Work with HTML elements (@olton/dom, https://metroui.org.ua) * Version: 1.5.1 * Build date: 18.05.2025, 14:45:23 * Copyright 2012-2025 by Serhii Pimenov * Licensed under MIT */ // output/index.js var numProps = ["opacity", "zIndex"]; function nothing() { return null; } function isSimple(v) { return typeof v === "string" || typeof v === "boolean" || typeof v === "number"; } function isVisible(elem) { const computedStyle = getComputedStyle(elem); const hasDimensions = !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); const isNotHiddenByStyles = computedStyle.visibility !== "hidden" && computedStyle.display !== "none" && computedStyle.opacity !== "0" && elem.style.display !== "none"; return hasDimensions && isNotHiddenByStyles; } function isHidden(elem) { const s = getComputedStyle(elem); return !isVisible(elem) || +s.opacity === 0 || elem.hidden || s.visibility === "hidden"; } function not(value) { return value === void 0 || 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) { let proto; if (!obj || Object.prototype.toString.call(obj) !== "[object Object]") { return false; } proto = obj.prototype !== void 0; if (!proto) { return true; } return proto.constructor && typeof proto.constructor === "function"; } function isEmptyObject(obj) { for (const name2 in obj) { if (hasProp(obj, name2)) 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) { const split = /[+-]?\d*\.?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn|fr|lh|cqw|cqh|cqi|cqb|cqmin|cqmax|q)?$/.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 : parseInt(val) === 0 ? 0 : val + "px"; } } function acceptData(owner) { return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType; } function normName(name2) { return typeof name2 !== "string" ? void 0 : name2.replace(/-/g, "").toLowerCase(); } function hasProp(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function isLocalhost(host) { const hostname = host || globalThis.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; } function isPrivateAddress(host) { const hostname = host || globalThis.location.hostname; return /(^localhost)|(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2\d\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/.test(hostname); } function safeJsonParse(str) { try { return JSON.parse(str); } catch (e) { return str; } } var matches = Element.prototype.matches; var $ = (selector, context) => new $.init(selector, context); $.version = "1.5.1"; $.build_time = "18.05.2025, 14:45:23"; $.info = () => console.info(`%c Dom %c v${$.version} %c ${$.build_time} `, "color: white; font-weight: bold; background: #fd6a02", "color: white; background: darkgreen", "color: white; background: #0080fe;"); $.fn = $.prototype = Object.create(Array.prototype); $.prototype.constructor = $; $.prototype.uid = ""; $.extend = $.fn.extend = function() { let options, name2, 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 (name2 in options) { if (hasProp(options, name2)) target[name2] = options[name2]; } } } return target; }; $.assign = function() { let options, name2, 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 (name2 in options) { if (hasProp(options, name2) && options[name2] !== void 0) target[name2] = options[name2]; } } } return target; }; (function(workerScript) { try { const blob = new Blob([` var fakeIdToId = {}; onmessage = function (event) { var data = event.data, name = data.name, fakeId = data.fakeId, time; if(data.hasOwnProperty('time')) { time = data.time; } switch (name) { case 'setInterval': fakeIdToId[fakeId] = setInterval(function () { postMessage({fakeId: fakeId}); }, time); break; case 'clearInterval': if (fakeIdToId.hasOwnProperty (fakeId)) { clearInterval(fakeIdToId[fakeId]); delete fakeIdToId[fakeId]; } break; case 'setTimeout': fakeIdToId[fakeId] = setTimeout(function () { postMessage({fakeId: fakeId}); if (fakeIdToId.hasOwnProperty (fakeId)) { delete fakeIdToId[fakeId]; } }, time); break; case 'clearTimeout': if (fakeIdToId.hasOwnProperty (fakeId)) { clearTimeout(fakeIdToId[fakeId]); delete fakeIdToId[fakeId]; } break; } } `]); workerScript = window.URL.createObjectURL(blob); } catch (error) { } let worker, fakeIdToCallback = {}, lastFakeId = 0, maxFakeId = 2147483647, logPrefix = ""; function getFakeId() { do { if (lastFakeId === maxFakeId) { lastFakeId = 0; } else { lastFakeId++; } } while (fakeIdToCallback.hasOwnProperty(lastFakeId)); return lastFakeId; } if (typeof Worker === "undefined") { return; } try { worker = new Worker(workerScript); window.setInterval = function(callback, time) { const fakeId = getFakeId(); fakeIdToCallback[fakeId] = { callback, parameters: Array.prototype.slice.call(arguments, 2) }; worker.postMessage({ name: "setInterval", fakeId, time }); return fakeId; }; window.clearInterval = function(fakeId) { if (fakeIdToCallback.hasOwnProperty(fakeId)) { delete fakeIdToCallback[fakeId]; worker.postMessage({ name: "clearInterval", fakeId }); } }; window.setTimeout = function(callback, time) { const fakeId = getFakeId(); fakeIdToCallback[fakeId] = { callback, parameters: Array.prototype.slice.call(arguments, 2), isTimeout: true }; worker.postMessage({ name: "setTimeout", fakeId, time }); return fakeId; }; window.clearTimeout = function(fakeId) { if (fakeIdToCallback.hasOwnProperty(fakeId)) { delete fakeIdToCallback[fakeId]; worker.postMessage({ name: "clearTimeout", fakeId }); } }; window.setImmediate = function(callback) { return setTimeout(callback, 0); }; window.clearImmediate = function(fakeId) { clearTimeout(fakeId); }; worker.onmessage = function(event) { let data = event.data, fakeId = data.fakeId, request, parameters, callback; if (fakeIdToCallback.hasOwnProperty(fakeId)) { request = fakeIdToCallback[fakeId]; callback = request.callback; parameters = request.parameters; if (request.hasOwnProperty("isTimeout") && request.isTimeout) { delete fakeIdToCallback[fakeId]; } } if (typeof callback === "string") { try { callback = new Function(callback); } catch (error) { console.error(logPrefix + "Error parsing callback code string: ", error); } } if (typeof callback === "function") { callback.apply(window, parameters); } }; worker.onerror = function(event) { console.error(event); }; } catch (error) { console.log(`Can't create worker for Intervals, use standard functions.`); } })(); $.fn.extend({ _getDefaultElement(sel) { let el; if (not(sel)) { el = this[0]; } else if (sel instanceof HTMLElement) { el = sel; } else if (sel instanceof $ && sel.length > 0) { el = sel[0]; } else if (typeof sel === "string") { el = $(sel)[0]; } else { el = void 0; } return el; }, index: function(sel) { let el, _index = -1; if (this.length === 0) { return _index; } el = this._getDefaultElement(sel); if (!el) { return _index; } if (el && el.parentNode) $.each(el.parentNode.children, function(i) { if (this === el) { _index = i; } }); return _index; }, indexOf: function(sel) { let el, _index = -1; if (this.length === 0) { return _index; } el = this._getDefaultElement(sel); if (!el) { return _index; } this.each(function(i) { if (this === el) { _index = i; } }); return _index; }, get: function(i) { if (i === void 0) { return this; } return i < 0 ? this[i + this.length] : i > this.length - 1 ? void 0 : this[i]; }, eq: function(i) { if (not(i)) { return this; } return this.length > 0 ? $.extend($(this.get(i)), { _prevObj: this }) : this; }, is: function(s) { let 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") { result = false; this.each(function() { if (isVisible(this)) result = true; }); } else if (s === ":hidden") { this.each(function() { const 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() { const el = this; $.each(s, function() { const 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) { let 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() { const result = this.filter(function(el, i) { return (i + 1) % 2 !== 0; }); return $.extend(result, { _prevObj: this }); }, even: function() { const result = this.filter(function(el, i) { return (i + 1) % 2 === 0; }); return $.extend(result, { _prevObj: this }); }, filter: function(fn) { if (typeof fn === "string") { const sel = fn; fn = function(el) { return matches.call(el, sel); }; } return $.extend($.merge($(), [].filter.call(this, fn)), { _prevObj: this }); }, find: function(s) { let res = [], result; if (s instanceof $) return s; if (this.length === 0) { result = this; } else { this.each(function() { const 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) { let i, res = []; if (s instanceof $) return s; this.each(function() { const 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) { let 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 res.length ? $.extend($.merge($(), res), { _prevObj: this }) : void 0; }, parents: function(s) { let res = []; if (this.length === 0) { return; } if (s instanceof $) return s; this.each(function() { let 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) { let res = []; if (this.length === 0) { return void 0; } if (s instanceof $) { return s; } this.each(function() { const 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) { let res = []; if (this.length === 0) { return; } if (s instanceof $) return s; this.each(function() { let 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) { let res = []; if (this.length === 0) { return; } if (s instanceof $) return s; this.each(function() { const 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) { let res = []; if (this.length === 0) { return void 0; } if (!s) { return this.parent(); } let el = this[0]; while (el) { if (matches.call(el, s)) { res.push(el); break; } el = el.parentElement; } return $.extend($.merge($(), res.reverse()), { _prevObj: this }); }, has: function(selector) { let res = []; if (this.length === 0) { return; } this.each(function() { const el = $(this); const child = el.children(selector); if (child.length > 0) { res.push(this); } }); return $.extend($.merge($(), res), { _prevObj: this }); }, back: function(to_start) { let 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; } }); function createScript(script, into = document.body) { const s = document.createElement("script"); s.type = "text/javascript"; if (not(script)) return $(s); const _script = $(script)[0]; if (_script.src) { s.src = _script.src; } else { s.textContent = _script.innerText; } if (_script.type) s.type = _script.type; if (_script.async) s.async = _script.async; into.appendChild(s); if (_script.parentNode) _script.parentNode.removeChild(_script); return s; } $.extend({ script: function(el, into) { if (not(el)) { return; } if (el instanceof $) { el = el[0]; } if (el.tagName && el.tagName === "SCRIPT") { createScript(el, into); } else { const scripts = $(el).find("script"); $.each(scripts, function() { createScript(this, into); }); } }, loadScript: function(url, into = document.body, callback) { const script = document.createElement("script"); script.type = "text/javascript"; script.src = url; script.onload = callback; into.appendChild(script); } }); $.fn.extend({ script: function(into) { return this.each(function() { $.script(this, into); }); } }); $.fn.extend({ _prop: function(prop, value) { if (arguments.length === 1) { return this.length === 0 ? void 0 : this[0][prop]; } if (not(value)) { value = ""; } return this.each(function() { const el = this; el[prop] = value; if (prop === "innerHTML") { $.script(el, 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 ? void 0 : this[0].value; } return this.each(function() { const el = $(this); if (typeof this.value !== "undefined") { this.value = value; } else { el.html(value); } }); }, html: function(value) { const 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.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 = ""; if (typeof this.value !== "undefined") this.value = ""; }); }, clear: function() { return this.empty(); } }); $.each = function(ctx, cb) { let index = 0; if (typeof ctx !== "object") { ctx = []; } if (isArrayLike(ctx)) { [].forEach.call(ctx, function(val, key) { cb.apply(val, [key, val]); }); } else { for (const 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); } }); var Data = function(ns) { this.expando = "DATASET:UID:" + ns.toUpperCase(); Data.uid++; }; Data.uid = -1; Data.prototype = { cache: function(owner) { let value = owner[this.expando]; if (!value) { value = {}; if (acceptData(owner)) { if (owner.nodeType) { owner[this.expando] = value; } else { Object.defineProperty(owner, this.expando, { value, configurable: true }); } } } return value; }, set: function(owner, data, value) { let 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) { let value = key === void 0 ? this.cache(owner) : owner[this.expando] && owner[this.expando][camelCase(key)]; if (key) { return value !== void 0 ? value : owner.getAttribute && owner.getAttribute("data-" + dashedName(key)) || void 0; } value = { ...owner[this.expando] }; for (const attr of owner.attributes) { if (attr.name.startsWith("data-")) { const name2 = attr.name.slice(5); value[camelCase(name2)] = attr.value; } } return isEmptyObject(value) ? void 0 : value; }, access: function(owner, key, value) { if (key === void 0 || key && typeof key === "string" && value === void 0) { return this.get(owner, key); } this.set(owner, key, value); return value !== void 0 ? value : key; }, remove: function(owner, key) { let cache = owner[this.expando]; if (cache === void 0) { return; } if (key !== void 0) { const _keys = Array.isArray(key) ? key : [key]; for (const k of _keys) { delete cache[camelCase(k)]; owner.removeAttribute && owner.removeAttribute("data-" + k); } } if (key === void 0 || isEmptyObject(cache)) { if (owner.nodeType) { owner[this.expando] = void 0; } else { delete owner[this.expando]; } } return true; }, hasData: function(owner) { const cache = owner[this.expando]; return cache !== void 0 && !isEmptyObject(cache); } }; var dataSet = new Data("dom"); $.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", "DOM"].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) { let res, elem, data; if (this.length === 0) { return; } elem = this[0]; if (arguments.length === 0) { if (elem) { data = dataSet.get(elem); if (elem.nodeType === 1) { for (const a of elem.attributes) { if (a.name.startsWith("data-")) { const name2 = a.name.slice(5); data[camelCase(name2)] = a.value; } } } } return data; } if (arguments.length === 1 && (typeof key === "string" || Array.isArray(key))) { res = dataSet.get(elem, key); return safeJsonParse(res); } return this.each(function() { dataSet.set(this, key, val); }); }, removeData: function(key) { if (typeof key === "undefined") { return this; } return this.each(function() { const keys = Array.isArray(key) ? key : key.split(" ").map((el) => el.trim()).filter((el) => el !== ""); for (const k of keys) { dataSet.remove(this, k); } }); }, origin: function(name2, value, def) { if (this.length === 0) { return this; } if (not(name2) && not(value)) { return $.data(this[0]); } if (not(value)) { const res = $.data(this[0], "origin-" + name2); return !not(res) ? res : def; } this.data("origin-" + name2, value); return this; } }); $.extend({ device: /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()), localhost: isLocalhost(), isLocalhost, touchable: isTouch(), isPrivateAddress, hashCode: function(str) { let hash = 0, i, chr; if (str.length === 0) return hash; for (i = 0; i < str.length; i++) { chr = str.charCodeAt(i); hash = (hash << 5) - hash + chr; hash |= 0; } return hash; }, uniqueId: function(salt = "salt") { let name2; if (typeof salt === "function") { name2 = salt.name; } else if (typeof salt === "string" && salt) { name2 = salt; } else if (typeof salt === "string" && salt.length === 0) { name2 = "salt"; } else { name2 = salt.toString(); } return "dom-" + $.hashCode(name2); }, toArray: function(n) { let i, out = []; for (i = 0; i < n.length; i++) { out.push(n[i]); } return out; }, import: function(ctx) { const res = []; this.each(ctx, function() { res.push(this); }); return this.merge($(), res); }, merge: function(first, second) { let 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(); }, isSelector: function(selector) { if (typeof selector !== "string" || selector.length === 0 || selector === "#" || selector === ".") { return false; } try { document.querySelector(selector); return true; } catch (error) { return false; } }, remove: function(s) { return $(s).remove(); }, isPlainObject, isEmptyObject, isArrayLike, acceptData, not, parseUnit, getUnit, unit: parseUnit, isVisible, 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); }, hasProp, dark: globalThis.matchMedia && globalThis.matchMedia("(prefers-color-scheme: dark)").matches, serializeToArray: function(form) { const _form = $(form)[0]; if (!_form || _form.nodeName !== "FORM") { console.warn("Element is not a HTMLFromElement"); return; } let 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("&"); }, viewport: function() { const w = window, d = document, e = d.documentElement, g = d.getElementsByTagName("body")[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight || e.clientHeight || g.clientHeight; return { width: x, height: y }; } }); $.fn.extend({ items: function() { return $.toArray(this); } }); 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) { let 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] !== void 0 && this.events[index] !== null) { this.events[index] = null; return this.events[index].handler; } return void 0; }, 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 = "before") { $.each(str2arr(event), (_, eventName) => { const key = camelCase(`${type}-${eventName}`); this.eventHooks[key] = handler; }); return this; }, removeEventHook: function(event, type = "before") { $.each(str2arr(event), (_, eventName) => { delete this.eventHooks[camelCase(`${type}-${eventName}`)]; }); return this; }, removeEventHooks: function(event) { const 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 = void 0; } if (typeof options !== "object") { options = {}; } return this.each(function(_, el) { $.each(str2arr(eventsList), (_2, ev) => { let h, event = ev.split("."), name2 = normName(event[0]), ns = options.ns ? options.ns : event[1], index, originEvent; $.eventUID++; h = (e) => { let target = e.target; const beforeHook = $.eventHooks[camelCase("before-" + name2)]; const afterHook = $.eventHooks[camelCase("after-" + name2)]; 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_" + name2 + "_" + $.eventUID }); originEvent = name2 + (sel ? ":" + sel : "") + (ns ? ":" + ns : ""); el.addEventListener(name2, h, !isEmptyObject(options) ? options : false); index = $.setEventHandler({ el, event: name2, handler: h, selector: sel, ns, id: $.eventUID, options: !isEmptyObject(options) ? options : false }); $(el).origin("event-" + originEvent, index); }); }); }, one: function(events, sel, handler, options = {}) { if (typeof sel === "function") { options = handler || {}; handler = sel; sel = void 0; } 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() { const el = this; $.each($.events, function() { const 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() { const el = this; $.each(str2arr(eventsList), function() { let evMap = this.split("."), name2 = normName(evMap[0]), ns = options.ns ? options.ns : evMap[1], originEvent, index; originEvent = "event-" + name2 + (sel ? ":" + sel : "") + (ns ? ":" + ns : ""); index = $(el).origin(originEvent); if (index !== void 0 && $.events[index].handler) { el.removeEventListener(name2, $.events[index].handler, $.events[index].options); $.events[index].handler = null; } $(el).origin(originEvent, null); }); }); }, trigger: function(name2, data) { return this.fire(name2, data); }, fire: function(name2, data) { let _name, e; if (this.length === 0) { return; } _name = normName(name2); if (["focus", "blur"].indexOf(_name) > -1) { this[0][_name](); return this; } e = new CustomEvent(_name, { bubbles: true, cancelable: true, detail: data }); 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(name2) { $.fn[name2] = function(sel, fn, opt) { return arguments.length > 0 ? this.on(name2, sel, fn, opt) : this.fire(name2); }; } ); $.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 ? void 0 : $.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 ? void 0 : $.beforeunload(fn); } }); $.fn.extend({ ready: function(fn) { if (this.length && this[0] === document && typeof fn === "function") { return $.ready(fn); } } }); $.ajax = function(p) { return new Promise(function(resolve, reject) { const xhr = new XMLHttpRequest(); let method = (p.method || "GET").toUpperCase(); const headers = []; const async = not(p.async) ? true : p.async; let url = p.url; let data; const exec = function(fn, params) { if (typeof fn === "function") { fn.apply(null, params); } }; const isGet = function(method2) { return ["GET", "JSON"].indexOf(method2) !== -1; }; const plainObjectToData = function(obj) { const _data = []; $.each(obj, function(k, v) { const _v = isSimple(v) ? v : JSON.stringify(v); _data.push(k + "=" + _v); }); return _data.join("&"); }; if (p.data instanceof HTMLFormElement) { let _action = p.data.getAttribute("action").trim(); let _method = p.data.getAttribute("method").trim(); if (not(url) && _action) { url = _action; } if (_method) { 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") { const _name = p.data.getAttribute("name"); data = new FormData(); for (let 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" ? "?" + data : isEmptyObject(data) ? "" : "?" + 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) { let _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]); }); $.each(["readystatechange", "error", "timeout", "progress", "loadstart", "loadend", "abort"], function() { const ev = camelCase("on-" + (this === "readystatechange" ? "state" : this)); xhr.addEventListener(ev, function(e) { exec(p[ev], [e, xhr]); }); }); }); }; ["GET", "POST", "PUT", "PATCH", "DELETE", "JSON"].forEach(function(method) { $[method.toLowerCase()] = function(url, data, options) { const _options = { method: method === "JSON" ? "GET" : method, url, data, parseJson: method === "JSON" }; return $.ajax($.extend({}, _options, options)); }; }); $.fn.extend({ load: function(url, data, options) { const that = this; if (this.length && this[0].self === window) { return $.load(url); } return $.get(url, data, options).then(function(data2) { that.each(function() { this.innerHTML = data2; }); }); } }); $.fn.extend({ style: function(name2, pseudo) { let el; function _getStyle2(el2, prop, pseudo2) { return ["scrollLeft", "scrollTop"].includes(prop) ? $(el2)[prop]() : getComputedStyle(el2, pseudo2)[prop]; } if (typeof name2 === "string" && this.length === 0) { return void 0; } if (this.length === 0) { return this; } el = this[0]; if (!name2 || name2 === "all") { return getComputedStyle(el, pseudo); } else { let result = {}; let names = name2.split(", ").map(function(el2) { return ("" + camelCase(el2)).trim(); }); if (names.length === 1) { return _getStyle2(el, names[0], pseudo); } else { $.each(names, function() { const prop = this; result[this] = _getStyle2(el, prop, pseudo); }); return result; } } }, removeStyleProperty: function(name2) { if (not(name2) || this.length === 0) return this; const names = name2.split(", ").map(function(el) { return ("" + el).trim(); }); return this.each(function() { const el = this; $.each(names, function() { el.style.removeProperty(this); }); }); }, removeStyle: function(name2) { if (!name2) return this; const names = str2arr(name2, ", "); return this.each(function() { const el = this; $.each(names, function() { el.style[this] = ""; }); }); }, css: function(key, val) { key = key || "all"; if (typeof key === "string" && not(val)) { return this.style(key); } return this.each(function(_, el) { if (typeof key === "object") { $.each(key, function(key2, val2) { setStyleProp(el, key2, val2); }); } else if (typeof key === "string") { setStyleProp(el, key, val); } }); }, cssVar: function(name2, val) { if (not(name2)) return void 0; if (not(val)) { return getComputedStyle(this[0]).getPropertyValue("--" + name2); } else { return this.each(function() { this.style.setProperty("--" + name2, val); }); } } }); $.fn.extend({ addClass: function() { }, removeClass: function() { }, toggleClass: function() { }, containsClass: function(cls) { return this.hasClass(cls); }, hasClass: function(cls) { if (not(cls)) { return false; } let result = false; const classes = cls.split(" ").filter((v) => ("" + v).trim() !== ""); this.each(function() { const el = this; $.each(classes, function() { if (!result && el.classList && el.classList.contains(this)) { result = true; } }); }); return result; }, clearClasses: function() { return this.each(function() { this.className = ""; }); }, cls: function(array = false) { return this.length === 0 ? void 0 : array ? this[0].className.split(" ") : this[0].className; }, removeClassBy: function(mask) { return this.each(function() { const el = $(this); const classes = el.cls(true); $.each(classes, function() { const elClass = this; if (elClass.indexOf(mask) > -1) { el.removeClass(elClass); } }); }); }, classNames: function() { const args = Array.prototype.slice.call(arguments, 0); const classes = []; $.each(args, function(_, a) { if (typeof a === "string") { classes.push(a); } else if (isPlainObject(a)) { $.each(a, function(k, v) { if (v) { classes.push(k); } }); } else { nothing(); } }); return this.each(function() { this.className += " " + classes.join(" "); }); } }); ["add", "remove", "toggle"].forEach(function(method) { $.fn[method + "Class"] = function(cls) { const _classes = !cls ? [] : Array.isArray(cls) ? cls : cls.split(" ").filter(function(v) { return !!v; }); if (!_classes.length) return this; return this.each(function() { const el = this; const hasClassList = typeof el.classList !== "undefined"; if (hasClassList) { $.each(_classes, function(_, v) { el.classList[method](v); }); } else { el.className += _classes.join(" "); } }); }; }); $.parseHTML = function(data) { let base, singleTag, result = [], ctx, _context; const regexpSingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i; if (typeof data !== "string" || data.trim() === "") { return []; } data = data.trim(); singleTag = regexpSingleTag.exec(data); if (singleTag) { result.push(document.createElement(singleTag[1])); } else { if ($.isSelector(data)) { const elements = document.querySelectorAll(data); if (elements.length) { for (const el of elements) { result.push(el); } } if (result.length === 0) { result.push(document.createTextNode(data)); } return result; } ctx = document.implementation.createHTMLDocument(""); base = ctx.createElement("base"); base.href = document.location.href; ctx.head.appendChild(base); _context = ctx.body; _context.innerHTML = data; for (let i = 0; i < _context.childNodes.length; i++) { result.push(_context.childNodes[i].cloneNode(true)); } } return result; }; $.fn.extend({ _size: function(prop, val) { if (this.length === 0) return; if (not(val)) { const el = this[0]; if (prop === "height") { return el === window ? window.innerHeight : el === document ? el.body.clientHeight : parseInt(getComputedStyle(el).height); } if (prop === "width") { return el === window ? window.innerWidth : el === document ? el.body.clientWidth : parseInt(getComputedStyle(el).width); } } return this.each(function() { const el = this; if (el === window || el === document) { return; } el.style[prop] = isNaN(val) ? val : +val === 0 ? 0 : val + "px"; }); }, height: function(val) { return this._size("height", val); }, width: function(val) { return this._size("width", val); }, _sizeOut: function(prop, val) { let el, size, style, result; if (this.length === 0) { return; } const setter = typeof val === "number"; if (setter) { return this.each(function() { const el2 = this; if (el2 === window || el2 === document) { return; } let h, style2 = getComputedStyle(el2), bs = prop === "width" ? parseInt(style2["borderLeftWidth"]) + parseInt(style2["borderRightWidth"]) : parseInt(style2["borderTopWidth"]) + parseInt(style2["borderBottomWidth"]), pa = prop === "width" ? parseInt(style2["paddingLeft"]) + parseInt(style2["paddingRight"]) : parseInt(style2["paddingTop"]) + parseInt(style2["paddingBottom"]); h = $(this)[prop](val)[prop]() - bs - pa; el2.style[prop] = h + "px"; }); } const includeMargin = val === true; el = this[0]; size = el[prop === "width" ? "offsetWidth" : "offsetHeight"]; style = getComputedStyle(el); result = size + parseInt(style[prop === "width" ? "marginLeft" : "marginTop"]) + parseInt(style[prop === "width" ? "marginRight" : "marginBottom"]); return includeMargin ? result : size; }, outerWidth: function(val) { return this._sizeOut("width", val); }, outerHeight: function(val) { return this._sizeOut("hei