alpinejs
Version:
<div dir="rtl">
1,428 lines (1,236 loc) • 284 kB
JavaScript
(function (factory) {
typeof define === 'function' && define.amd ? define(factory) :
factory();
}((function () { 'use strict';
(function() {
var select = HTMLSelectElement.prototype;
if (select.hasOwnProperty("selectedOptions")) return
Object.defineProperty(select, "selectedOptions", {
get: function() {
return this.querySelectorAll(":checked")
},
enumerable: true,
configurable: true,
});
})();
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
(function(){function n(){function v(){return null}function l(a){return a?"object"===typeof a||"function"===typeof a:!1}function p(a){if(null!==a&&!l(a))throw new TypeError("Object prototype may only be an Object or null: "+a);}var q=null,e=Object,w=!!e.create||!({__proto__:null}instanceof e),A=e.create||(w?function(a){p(a);return {__proto__:a}}:function(a){function c(){}p(a);if(null===a)throw new SyntaxError("Native Object.create is required to create objects with null prototype");c.prototype=a;return new c}),
B=e.getPrototypeOf||([].__proto__===Array.prototype?function(a){a=a.__proto__;return l(a)?a:null}:v);var m=function(a,c){function k(){}if(void 0===(this&&this instanceof m?this.constructor:void 0))throw new TypeError("Constructor Proxy requires 'new'");if(!l(a)||!l(c))throw new TypeError("Cannot create proxy with a non-object as target or handler");q=function(){a=null;k=function(b){throw new TypeError("Cannot perform '"+b+"' on a proxy that has been revoked");};};setTimeout(function(){q=null;},0);var g=
c;c={get:null,set:null,apply:null,construct:null};for(var h in g){if(!(h in c))throw new TypeError("Proxy polyfill does not support trap '"+h+"'");c[h]=g[h];}"function"===typeof g&&(c.apply=g.apply.bind(g));g=B(a);var r=!1,t=!1;if("function"===typeof a){var f=function(){var b=this&&this.constructor===f,d=Array.prototype.slice.call(arguments);k(b?"construct":"apply");return b&&c.construct?c.construct.call(this,a,d):!b&&c.apply?c.apply(a,this,d):b?(d.unshift(a),new (a.bind.apply(a,d))):a.apply(this,
d)};r=!0;}else a instanceof Array?(f=[],t=!0):f=w||null!==g?A(g):{};var x=c.get?function(b){k("get");return c.get(this,b,f)}:function(b){k("get");return this[b]},C=c.set?function(b,d){k("set");c.set(this,b,d,f);}:function(b,d){k("set");this[b]=d;},y={};e.getOwnPropertyNames(a).forEach(function(b){if(!((r||t)&&b in f)){var d=e.getOwnPropertyDescriptor(a,b);e.defineProperty(f,b,{enumerable:!!d.enumerable,get:x.bind(a,b),set:C.bind(a,b)});y[b]=!0;}});h=!0;if(r||t){var D=e.setPrototypeOf||([].__proto__===
Array.prototype?function(b,d){p(d);b.__proto__=d;return b}:v);g&&D(f,g)||(h=!1);}if(c.get||!h)for(var u in a)y[u]||e.defineProperty(f,u,{get:x.bind(a,u)});e.seal(a);e.seal(f);return f};m.revocable=function(a,c){return {proxy:new m(a,c),revoke:q}};return m}var z="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)||"undefined"!==typeof navigator&&"ReactNative"===navigator.product?commonjsGlobal:self;z.Proxy||(z.Proxy=n(),z.Proxy.revocable=z.Proxy.revocable);})();
!function(e){var t=e.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode;}return null});}(window);
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode && this.parentNode.removeChild(this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype].filter(Boolean));
/*
* classList.js: Cross-browser full element.classList implementation.
* 1.1.20170427
*
* By Eli Grey, http://eligrey.com
* License: Dedicated to the public domain.
* See https://github.com/eligrey/classList.js/blob/master/LICENSE.md
*/
/*global self, document, DOMException */
/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */
if ("document" in window.self) {
// Full polyfill for browsers with no classList support
// Including IE < Edge missing SVGElement.classList
if (!("classList" in document.createElement("_"))
|| document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg","g"))) {
(function (view) {
if (!('Element' in view)) return;
var
classListProp = "classList"
, protoProp = "prototype"
, elemCtrProto = view.Element[protoProp]
, objCtr = Object
, strTrim = String[protoProp].trim || function () {
return this.replace(/^\s+|\s+$/g, "");
}
, arrIndexOf = Array[protoProp].indexOf || function (item) {
var
i = 0
, len = this.length
;
for (; i < len; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
}
// Vendors: please allow content code to instantiate DOMExceptions
, DOMEx = function (type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
}
, checkTokenAndGetIndex = function (classList, token) {
if (token === "") {
throw new DOMEx(
"SYNTAX_ERR"
, "An invalid or illegal string was specified"
);
}
if (/\s/.test(token)) {
throw new DOMEx(
"INVALID_CHARACTER_ERR"
, "String contains an invalid character"
);
}
return arrIndexOf.call(classList, token);
}
, ClassList = function (elem) {
var
trimmedClasses = strTrim.call(elem.getAttribute("class") || "")
, classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
, i = 0
, len = classes.length
;
for (; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.setAttribute("class", this.toString());
};
}
, classListProto = ClassList[protoProp] = []
, classListGetter = function () {
return new ClassList(this);
}
;
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += "";
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function () {
var
tokens = arguments
, i = 0
, l = tokens.length
, token
, updated = false
;
do {
token = tokens[i] + "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
updated = true;
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.remove = function () {
var
tokens = arguments
, i = 0
, l = tokens.length
, token
, updated = false
, index
;
do {
token = tokens[i] + "";
index = checkTokenAndGetIndex(this, token);
while (index !== -1) {
this.splice(index, 1);
updated = true;
index = checkTokenAndGetIndex(this, token);
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.toggle = function (token, force) {
token += "";
var
result = this.contains(token)
, method = result ?
force !== true && "remove"
:
force !== false && "add"
;
if (method) {
this[method](token);
}
if (force === true || force === false) {
return force;
} else {
return !result;
}
};
classListProto.toString = function () {
return this.join(" ");
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter
, enumerable: true
, configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
// adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
// modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
if (ex.number === undefined || ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(window.self));
}
// There is full or partial native classList support, so just check if we need
// to normalize the add/remove and toggle APIs.
(function () {
var testElement = document.createElement("_");
testElement.classList.add("c1", "c2");
// Polyfill for IE 10/11 and Firefox <26, where classList.add and
// classList.remove exist but support only one argument at a time.
if (!testElement.classList.contains("c2")) {
var createMethod = function(method) {
var original = DOMTokenList.prototype[method];
DOMTokenList.prototype[method] = function(token) {
var i, len = arguments.length;
for (i = 0; i < len; i++) {
token = arguments[i];
original.call(this, token);
}
};
};
createMethod('add');
createMethod('remove');
}
testElement.classList.toggle("c3", false);
// Polyfill for IE 10 and Firefox <24, where classList.toggle does not
// support the second argument.
if (testElement.classList.contains("c3")) {
var _toggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function(token, force) {
if (1 in arguments && !this.contains(token) === !force) {
return force;
} else {
return _toggle.call(this, token);
}
};
}
testElement = null;
}());
}
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// minimal template polyfill
(function() {
var needsTemplate = (typeof HTMLTemplateElement === 'undefined');
var brokenDocFragment = !(document.createDocumentFragment().cloneNode() instanceof DocumentFragment);
var needsDocFrag = false;
// NOTE: Replace DocumentFragment to work around IE11 bug that
// causes children of a document fragment modified while
// there is a mutation observer to not have a parentNode, or
// have a broken parentNode (!?!)
if (/Trident/.test(navigator.userAgent)) {
(function() {
needsDocFrag = true;
var origCloneNode = Node.prototype.cloneNode;
Node.prototype.cloneNode = function cloneNode(deep) {
var newDom = origCloneNode.call(this, deep);
if (this instanceof DocumentFragment) {
newDom.__proto__ = DocumentFragment.prototype;
}
return newDom;
};
// IE's DocumentFragment querySelector code doesn't work when
// called on an element instance
DocumentFragment.prototype.querySelectorAll = HTMLElement.prototype.querySelectorAll;
DocumentFragment.prototype.querySelector = HTMLElement.prototype.querySelector;
Object.defineProperties(DocumentFragment.prototype, {
'nodeType': {
get: function () {
return Node.DOCUMENT_FRAGMENT_NODE;
},
configurable: true
},
'localName': {
get: function () {
return undefined;
},
configurable: true
},
'nodeName': {
get: function () {
return '#document-fragment';
},
configurable: true
}
});
var origInsertBefore = Node.prototype.insertBefore;
function insertBefore(newNode, refNode) {
if (newNode instanceof DocumentFragment) {
var child;
while ((child = newNode.firstChild)) {
origInsertBefore.call(this, child, refNode);
}
} else {
origInsertBefore.call(this, newNode, refNode);
}
return newNode;
}
Node.prototype.insertBefore = insertBefore;
var origAppendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function appendChild(child) {
if (child instanceof DocumentFragment) {
insertBefore.call(this, child, null);
} else {
origAppendChild.call(this, child);
}
return child;
};
var origRemoveChild = Node.prototype.removeChild;
var origReplaceChild = Node.prototype.replaceChild;
Node.prototype.replaceChild = function replaceChild(newChild, oldChild) {
if (newChild instanceof DocumentFragment) {
insertBefore.call(this, newChild, oldChild);
origRemoveChild.call(this, oldChild);
} else {
origReplaceChild.call(this, newChild, oldChild);
}
return oldChild;
};
Document.prototype.createDocumentFragment = function createDocumentFragment() {
var frag = this.createElement('df');
frag.__proto__ = DocumentFragment.prototype;
return frag;
};
var origImportNode = Document.prototype.importNode;
Document.prototype.importNode = function importNode(impNode, deep) {
deep = deep || false;
var newNode = origImportNode.call(this, impNode, deep);
if (impNode instanceof DocumentFragment) {
newNode.__proto__ = DocumentFragment.prototype;
}
return newNode;
};
})();
}
// NOTE: we rely on this cloneNode not causing element upgrade.
// This means this polyfill must load before the CE polyfill and
// this would need to be re-worked if a browser supports native CE
// but not <template>.
var capturedCloneNode = Node.prototype.cloneNode;
var capturedCreateElement = Document.prototype.createElement;
var capturedImportNode = Document.prototype.importNode;
var capturedRemoveChild = Node.prototype.removeChild;
var capturedAppendChild = Node.prototype.appendChild;
var capturedReplaceChild = Node.prototype.replaceChild;
var capturedParseFromString = DOMParser.prototype.parseFromString;
var capturedHTMLElementInnerHTML = Object.getOwnPropertyDescriptor(window.HTMLElement.prototype, 'innerHTML') || {
/**
* @this {!HTMLElement}
* @return {string}
*/
get: function() {
return this.innerHTML;
},
/**
* @this {!HTMLElement}
* @param {string}
*/
set: function(text) {
this.innerHTML = text;
}
};
var capturedChildNodes = Object.getOwnPropertyDescriptor(window.Node.prototype, 'childNodes') || {
/**
* @this {!Node}
* @return {!NodeList}
*/
get: function() {
return this.childNodes;
}
};
var elementQuerySelectorAll = Element.prototype.querySelectorAll;
var docQuerySelectorAll = Document.prototype.querySelectorAll;
var fragQuerySelectorAll = DocumentFragment.prototype.querySelectorAll;
var scriptSelector = 'script:not([type]),script[type="application/javascript"],script[type="text/javascript"]';
function QSA(node, selector) {
// IE 11 throws a SyntaxError with `scriptSelector` if the node has no children due to the `:not([type])` syntax
if (!node.childNodes.length) {
return [];
}
switch (node.nodeType) {
case Node.DOCUMENT_NODE:
return docQuerySelectorAll.call(node, selector);
case Node.DOCUMENT_FRAGMENT_NODE:
return fragQuerySelectorAll.call(node, selector);
default:
return elementQuerySelectorAll.call(node, selector);
}
}
// returns true if nested templates cannot be cloned (they cannot be on
// some impl's like Safari 8 and Edge)
// OR if cloning a document fragment does not result in a document fragment
var needsCloning = (function() {
if (!needsTemplate) {
var t = document.createElement('template');
var t2 = document.createElement('template');
t2.content.appendChild(document.createElement('div'));
t.content.appendChild(t2);
var clone = t.cloneNode(true);
return (clone.content.childNodes.length === 0 || clone.content.firstChild.content.childNodes.length === 0
|| brokenDocFragment);
}
})();
var TEMPLATE_TAG = 'template';
var PolyfilledHTMLTemplateElement = function() {};
if (needsTemplate) {
var contentDoc = document.implementation.createHTMLDocument('template');
var canDecorate = true;
var templateStyle = document.createElement('style');
templateStyle.textContent = TEMPLATE_TAG + '{display:none;}';
var head = document.head;
head.insertBefore(templateStyle, head.firstElementChild);
/**
Provides a minimal shim for the <template> element.
*/
PolyfilledHTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
// if elements do not have `innerHTML` on instances, then
// templates can be patched by swizzling their prototypes.
var canProtoPatch =
!(document.createElement('div').hasOwnProperty('innerHTML'));
/**
The `decorate` method moves element children to the template's `content`.
NOTE: there is no support for dynamically adding elements to templates.
*/
PolyfilledHTMLTemplateElement.decorate = function(template) {
// if the template is decorated or not in HTML namespace, return fast
if (template.content ||
template.namespaceURI !== document.documentElement.namespaceURI) {
return;
}
template.content = contentDoc.createDocumentFragment();
var child;
while ((child = template.firstChild)) {
capturedAppendChild.call(template.content, child);
}
// NOTE: prefer prototype patching for performance and
// because on some browsers (IE11), re-defining `innerHTML`
// can result in intermittent errors.
if (canProtoPatch) {
template.__proto__ = PolyfilledHTMLTemplateElement.prototype;
} else {
template.cloneNode = function(deep) {
return PolyfilledHTMLTemplateElement._cloneNode(this, deep);
};
// add innerHTML to template, if possible
// Note: this throws on Safari 7
if (canDecorate) {
try {
defineInnerHTML(template);
defineOuterHTML(template);
} catch (err) {
canDecorate = false;
}
}
}
// bootstrap recursively
PolyfilledHTMLTemplateElement.bootstrap(template.content);
};
// Taken from https://github.com/jquery/jquery/blob/73d7e6259c63ac45f42c6593da8c2796c6ce9281/src/manipulation/wrapMap.js
var topLevelWrappingMap = {
'option': ['select'],
'thead': ['table'],
'col': ['colgroup', 'table'],
'tr': ['tbody', 'table'],
'th': ['tr', 'tbody', 'table'],
'td': ['tr', 'tbody', 'table']
};
var getTagName = function(text) {
// Taken from https://github.com/jquery/jquery/blob/73d7e6259c63ac45f42c6593da8c2796c6ce9281/src/manipulation/var/rtagName.js
return ( /<([a-z][^/\0>\x20\t\r\n\f]+)/i.exec(text) || ['', ''])[1].toLowerCase();
};
var defineInnerHTML = function defineInnerHTML(obj) {
Object.defineProperty(obj, 'innerHTML', {
get: function() {
return getInnerHTML(this);
},
set: function(text) {
// For IE11, wrap the text in the correct (table) context
var wrap = topLevelWrappingMap[getTagName(text)];
if (wrap) {
for (var i = 0; i < wrap.length; i++) {
text = '<' + wrap[i] + '>' + text + '</' + wrap[i] + '>';
}
}
contentDoc.body.innerHTML = text;
PolyfilledHTMLTemplateElement.bootstrap(contentDoc);
while (this.content.firstChild) {
capturedRemoveChild.call(this.content, this.content.firstChild);
}
var body = contentDoc.body;
// If we had wrapped, get back to the original node
if (wrap) {
for (var j = 0; j < wrap.length; j++) {
body = body.lastChild;
}
}
while (body.firstChild) {
capturedAppendChild.call(this.content, body.firstChild);
}
},
configurable: true
});
};
var defineOuterHTML = function defineOuterHTML(obj) {
Object.defineProperty(obj, 'outerHTML', {
get: function() {
return '<' + TEMPLATE_TAG + '>' + this.innerHTML + '</' + TEMPLATE_TAG + '>';
},
set: function(innerHTML) {
if (this.parentNode) {
contentDoc.body.innerHTML = innerHTML;
var docFrag = this.ownerDocument.createDocumentFragment();
while (contentDoc.body.firstChild) {
capturedAppendChild.call(docFrag, contentDoc.body.firstChild);
}
capturedReplaceChild.call(this.parentNode, docFrag, this);
} else {
throw new Error("Failed to set the 'outerHTML' property on 'Element': This element has no parent node.");
}
},
configurable: true
});
};
defineInnerHTML(PolyfilledHTMLTemplateElement.prototype);
defineOuterHTML(PolyfilledHTMLTemplateElement.prototype);
/**
The `bootstrap` method is called automatically and "fixes" all
<template> elements in the document referenced by the `doc` argument.
*/
PolyfilledHTMLTemplateElement.bootstrap = function bootstrap(doc) {
var templates = QSA(doc, TEMPLATE_TAG);
for (var i=0, l=templates.length, t; (i<l) && (t=templates[i]); i++) {
PolyfilledHTMLTemplateElement.decorate(t);
}
};
// auto-bootstrapping for main document
document.addEventListener('DOMContentLoaded', function() {
PolyfilledHTMLTemplateElement.bootstrap(document);
});
// Patch document.createElement to ensure newly created templates have content
Document.prototype.createElement = function createElement() {
var el = capturedCreateElement.apply(this, arguments);
if (el.localName === 'template') {
PolyfilledHTMLTemplateElement.decorate(el);
}
return el;
};
DOMParser.prototype.parseFromString = function() {
var el = capturedParseFromString.apply(this, arguments);
PolyfilledHTMLTemplateElement.bootstrap(el);
return el;
};
Object.defineProperty(HTMLElement.prototype, 'innerHTML', {
get: function() {
return getInnerHTML(this);
},
set: function(text) {
capturedHTMLElementInnerHTML.set.call(this, text);
PolyfilledHTMLTemplateElement.bootstrap(this);
},
configurable: true,
enumerable: true
});
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#escapingString
var escapeAttrRegExp = /[&\u00A0"]/g;
var escapeDataRegExp = /[&\u00A0<>]/g;
var escapeReplace = function(c) {
switch (c) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
case '"':
return '"';
case '\u00A0':
return ' ';
}
};
var escapeAttr = function(s) {
return s.replace(escapeAttrRegExp, escapeReplace);
};
var escapeData = function(s) {
return s.replace(escapeDataRegExp, escapeReplace);
};
var makeSet = function(arr) {
var set = {};
for (var i = 0; i < arr.length; i++) {
set[arr[i]] = true;
}
return set;
};
// http://www.whatwg.org/specs/web-apps/current-work/#void-elements
var voidElements = makeSet([
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
]);
var plaintextParents = makeSet([
'style',
'script',
'xmp',
'iframe',
'noembed',
'noframes',
'plaintext',
'noscript'
]);
/**
* @param {Node} node
* @param {Node} parentNode
* @param {Function=} callback
*/
var getOuterHTML = function(node, parentNode, callback) {
switch (node.nodeType) {
case Node.ELEMENT_NODE: {
var tagName = node.localName;
var s = '<' + tagName;
var attrs = node.attributes;
for (var i = 0, attr; (attr = attrs[i]); i++) {
s += ' ' + attr.name + '="' + escapeAttr(attr.value) + '"';
}
s += '>';
if (voidElements[tagName]) {
return s;
}
return s + getInnerHTML(node, callback) + '</' + tagName + '>';
}
case Node.TEXT_NODE: {
var data = /** @type {Text} */ (node).data;
if (parentNode && plaintextParents[parentNode.localName]) {
return data;
}
return escapeData(data);
}
case Node.COMMENT_NODE: {
return '<!--' + /** @type {Comment} */ (node).data + '-->';
}
default: {
window.console.error(node);
throw new Error('not implemented');
}
}
};
/**
* @param {Node} node
* @param {Function=} callback
*/
var getInnerHTML = function(node, callback) {
if (node.localName === 'template') {
node = /** @type {HTMLTemplateElement} */ (node).content;
}
var s = '';
var c$ = callback ? callback(node) : capturedChildNodes.get.call(node);
for (var i=0, l=c$.length, child; (i<l) && (child=c$[i]); i++) {
s += getOuterHTML(child, node, callback);
}
return s;
};
}
// make cloning/importing work!
if (needsTemplate || needsCloning) {
PolyfilledHTMLTemplateElement._cloneNode = function _cloneNode(template, deep) {
var clone = capturedCloneNode.call(template, false);
// NOTE: decorate doesn't auto-fix children because they are already
// decorated so they need special clone fixup.
if (this.decorate) {
this.decorate(clone);
}
if (deep) {
// NOTE: use native clone node to make sure CE's wrapped
// cloneNode does not cause elements to upgrade.
capturedAppendChild.call(clone.content, capturedCloneNode.call(template.content, true));
// now ensure nested templates are cloned correctly.
fixClonedDom(clone.content, template.content);
}
return clone;
};
// Given a source and cloned subtree, find <template>'s in the cloned
// subtree and replace them with cloned <template>'s from source.
// We must do this because only the source templates have proper .content.
var fixClonedDom = function fixClonedDom(clone, source) {
// do nothing if cloned node is not an element
if (!source.querySelectorAll) return;
// these two lists should be coincident
var s$ = QSA(source, TEMPLATE_TAG);
if (s$.length === 0) {
return;
}
var t$ = QSA(clone, TEMPLATE_TAG);
for (var i=0, l=t$.length, t, s; i<l; i++) {
s = s$[i];
t = t$[i];
if (PolyfilledHTMLTemplateElement && PolyfilledHTMLTemplateElement.decorate) {
PolyfilledHTMLTemplateElement.decorate(s);
}
capturedReplaceChild.call(t.parentNode, cloneNode.call(s, true), t);
}
};
// make sure scripts inside of a cloned template are executable
var fixClonedScripts = function fixClonedScripts(fragment) {
var scripts = QSA(fragment, scriptSelector);
for (var ns, s, i = 0; i < scripts.length; i++) {
s = scripts[i];
ns = capturedCreateElement.call(document, 'script');
ns.textContent = s.textContent;
var attrs = s.attributes;
for (var ai = 0, a; ai < attrs.length; ai++) {
a = attrs[ai];
ns.setAttribute(a.name, a.value);
}
capturedReplaceChild.call(s.parentNode, ns, s);
}
};
// override all cloning to fix the cloned subtree to contain properly
// cloned templates.
var cloneNode = Node.prototype.cloneNode = function cloneNode(deep) {
var dom;
// workaround for Edge bug cloning documentFragments
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8619646/
if (!needsDocFrag && brokenDocFragment && this instanceof DocumentFragment) {
if (!deep) {
return this.ownerDocument.createDocumentFragment();
} else {
dom = importNode.call(this.ownerDocument, this, true);
}
} else if (this.nodeType === Node.ELEMENT_NODE &&
this.localName === TEMPLATE_TAG &&
this.namespaceURI == document.documentElement.namespaceURI) {
dom = PolyfilledHTMLTemplateElement._cloneNode(this, deep);
} else {
dom = capturedCloneNode.call(this, deep);
}
// template.content is cloned iff `deep`.
if (deep) {
fixClonedDom(dom, this);
}
return dom;
};
// NOTE: we are cloning instead of importing <template>'s.
// However, the ownerDocument of the cloned template will be correct!
// This is because the native import node creates the right document owned
// subtree and `fixClonedDom` inserts cloned templates into this subtree,
// thus updating the owner doc.
var importNode = Document.prototype.importNode = function importNode(element, deep) {
deep = deep || false;
if (element.localName === TEMPLATE_TAG) {
return PolyfilledHTMLTemplateElement._cloneNode(element, deep);
} else {
var dom = capturedImportNode.call(this, element, deep);
if (deep) {
fixClonedDom(dom, element);
fixClonedScripts(dom);
}
return dom;
}
};
}
if (needsTemplate) {
window.HTMLTemplateElement = PolyfilledHTMLTemplateElement;
}
})();
var ApplyThisPrototype = (function() {
return function ApplyThisPrototype(event, target) {
if ((typeof target === 'object') && (target !== null)) {
var proto = Object.getPrototypeOf(target);
var property;
for (property in proto) {
if (!(property in event)) {
var descriptor = Object.getOwnPropertyDescriptor(proto, property);
if (descriptor) {
Object.defineProperty(event, property, descriptor);
}
}
}
for (property in target) {
if (!(property in event)) {
event[property] = target[property];
}
}
}
}
})();
(function(ApplyThisPrototype) {
/**
* Polyfill CustomEvent
*/
try {
var event = new window.CustomEvent('event', { bubbles: true, cancelable: true });
} catch (error) {
var CustomEventOriginal = window.CustomEvent || window.Event;
var CustomEvent = function(eventName, params) {
params = params || {};
var event = document.createEvent('CustomEvent');
event.initCustomEvent(
eventName,
(params.bubbles === void 0) ? false : params.bubbles,
(params.cancelable === void 0) ? false : params.cancelable,
(params.detail === void 0) ? {} : params.detail
);
ApplyThisPrototype(event, this);
return event;
};
CustomEvent.prototype = CustomEventOriginal.prototype;
window.CustomEvent = CustomEvent;
}
})(ApplyThisPrototype);
var EventListenerInterceptor = (function() {
if(typeof EventTarget === 'undefined') {
window.EventTarget = Node;
}
/**
* Event listener interceptor
*/
var EventListenerInterceptor = {
interceptors: [] // { target: EventTarget, interceptors: [{ add: Function, remove: Function }, ...] }
};
/**
* Returns if exists a previously registered listener from a target and the normalized arguments
* @param target
* @param normalizedArguments
* @return {*}
*/
EventListenerInterceptor.getRegisteredEventListener = function(target, normalizedArguments) {
var key = normalizedArguments.type + '-' + (normalizedArguments.options.capture ? '1' : '0');
if(
(target.__eventListeners !== void 0) &&
(target.__eventListeners[key] !== void 0)
) {
var map = target.__eventListeners[key];
for(var i = 0; i < map.length; i++) {
if(map[i].listener === normalizedArguments.listener) {
return map[i];
}
}
}
return null;
};
/**
* Registers a listener on a target with some options
* @param target
* @param normalizedArguments
*/
EventListenerInterceptor.registerEventListener = function(target, normalizedArguments) {
var key = normalizedArguments.type + '-' + (normalizedArguments.options.capture ? '1' : '0');
if(target.__eventListeners === void 0) {
target.__eventListeners = {};
}
if(target.__eventListeners[key] === void 0) {
target.__eventListeners[key] = [];
}
target.__eventListeners[key].push(normalizedArguments);
};
/**
* Unregisters a listener on a target with some options
* @param target
* @param normalizedArguments
*/
EventListenerInterceptor.unregisterEventListener = function(target, normalizedArguments) {
var key = normalizedArguments.type + '-' + (normalizedArguments.options.capture ? '1' : '0');
if(
(target.__eventListeners !== void 0) &&
(target.__eventListeners[key] !== void 0)
) {
var map = target.__eventListeners[key];
for(var i = 0; i < map.length; i++) {
if(map[i].listener === normalizedArguments.listener) {
map.splice(i, 1);
}
}
if(map.length === 0) {
delete target.__eventListeners[key];
}
}
};
EventListenerInterceptor.normalizeListenerCallback = function(listener) {
if((typeof listener === 'function') || (listener === null) || (listener === void 0)) {
return listener;
} else if((typeof listener === 'object') && (typeof listener.handleEvent === 'function')) {
return listener.handleEvent;
} else {
// to support Symbol
return function(event) {
listener(event);
};
}
};
EventListenerInterceptor.normalizeListenerOptions = function(options) {
switch(typeof options) {
case 'boolean':
options = { capture: options };
break;
case 'undefined':
options = { capture: false };
break;
case 'object':
if (options === null) {
options = { capture: false };
}
break;
default:
throw new Error('Unsupported options type for addEventListener');
}
options.once = Boolean(options.once);
options.passive = Boolean(options.passive);
options.capture = Boolean(options.capture);
return options;
};
EventListenerInterceptor.normalizeListenerArguments = function(type, listener, options) {
return {
type: type,
listener: this.normalizeListenerCallback(listener),
options: this.normalizeListenerOptions(options)
};
};
EventListenerInterceptor.intercept = function(target, interceptors) {
// get an interceptor with this target or null
var interceptor = null;
for (var i = 0; i < this.interceptors.length; i++) {
if(this.interceptors[i].target === target) {
interceptor = this.interceptors[i];
}
}
// if no interceptor already set
if (interceptor === null) {
interceptor = { target: target, interceptors: [interceptors] };
this.interceptors.push(interceptor);
this.interceptAddEventListener(target, interceptor);
this.interceptRemoveEventListener(target, interceptor);
} else { // if an interceptor already set, simply add interceptors to the list
interceptor.interceptors.push(interceptors);
}
// var release = function() {
// target.prototype.addEventListener = addEventListener;
// target.prototype.removeEventListener = removeEventListener;
// };
// this.interceptors.push(release);
// return release;
};
EventListenerInterceptor.interceptAddEventListener = function(target, interceptor) {
var _this = this;
var addEventListener = target.prototype.addEventListener;
target.prototype.addEventListener = function(type, listener, options) {
var normalizedArguments = _this.normalizeListenerArguments(type, listener, options);
var registeredEventListener = _this.getRegisteredEventListener(this, normalizedArguments);
if (!registeredEventListener) {
normalizedArguments.polyfilled = {
type: normalizedArguments.type,
listener: normalizedArguments.listener,
options: {
capture: normalizedArguments.options.capture,
once: normalizedArguments.options.once,
passive: normalizedArguments.options.passive
}
};
for (var i = 0; i < interceptor.interceptors.length; i++) {
var interceptors = interceptor.interceptors[i];
if (typeof interceptors.add === 'function') {
interceptors.add(normalizedArguments);
}
}
// console.log('normalizedArguments', normalizedArguments.polyfilled);
_this.registerEventListener(this, normalizedArguments);
addEventListener.call(
this,
normalizedArguments.polyfilled.type,
normalizedArguments.polyfilled.listener,
normalizedArguments.polyfilled.options
);
}
};
return function() {
target.prototype.addEventListener = addEventListener;
};
};
EventListenerInterceptor.interceptRemoveEventListener = function(target, interceptor) {
var _this = this;
var removeEventListener = target.prototype.removeEventListener;
target.prototype.removeEventListener = function(type, listener, options) {
var normalizedArguments = _this.normalizeListenerArguments(type, listener, options);
var registeredEventListener = _this.getRegisteredEventListener(this, normalizedArguments);
if (registeredEventListener) {
_this.unregisterEventListener(this, normalizedArguments);
removeEventListener.call(
this,
registeredEventListener.polyfilled.type,
registeredEventListener.polyfilled.listener,
registeredEventListener.polyfilled.options
);
} else {
removeEventListener.call(this, type, listener, options);
}
};
return function() {
target.prototype.removeEventListener = removeEventListener;
};
};
EventListenerInterceptor.interceptAll = function(interceptors) {
this.intercept(EventTarget, interceptors);
if(!(window instanceof EventTarget)) {
this.intercept(Window, interceptors);
}
};
EventListenerInterceptor.releaseAll = function() {
for(var i = 0, l = this.interceptors.length; i < l; i++) {
this.interceptors();
}
};
EventListenerInterceptor.error = function(error) {
// throw error;
console.error(error);
};
return EventListenerInterceptor;
})();
(function(EventListenerInterceptor) {
/**
* Event listener options support
*/
EventListenerInterceptor.detectSupportedOptions = function() {
var _this = this;
this.supportedOptions = {
once: false,
passive: false,
capture: false,
all: false,
some: false
};
document.createDocumentFragment().addEventListener('test', function() {}, {
get once() {
_this.supportedOptions.once = true;
return false;
},
get passive() {
_this.supportedOptions.passive = true;
return false;
},
get capture() {
_this.supportedOptions.capture = true;
return false;
}
});
// useful shortcuts to detect if options are all/some supported
this.supportedOptions.all = this.supportedOptions.once && this.supportedOptions.passive && this.supportedOptions.capture;
this.supportedOptions.some = this.supportedOptions.once || this.supportedOptions.passive || this.supportedOptions.capture;
};
EventListenerInterceptor.polyfillListenerOptions = function() {
this.detectSupportedOptions();
if (!this.supportedOptions.all) {
var _this = this;
this.interceptAll({
add: function(normalizedArguments) {
// console.log('intercepted', normalizedArguments);
var once = normalizedArguments.options.once && !_this.supportedOptions.once;
var passive = normalizedArguments.options.passive && !_this.supportedOptions.passive;
if (once || passive) {
var listener = normalizedArguments.polyfilled.listener;
normalizedArguments.polyfilled.listener = function(event) {
if(once) {
this.removeEventListener(normalizedArguments.type, normalizedArguments.listener, normalizedArguments.options);
}
if(passive) {
event.preventDefault = function() {
throw new Error('Unable to preventDefault inside passive event listener invocation.');
};
}
return listener.call(this, event);
};
}
if (!_this.supportedOptions.some) {
normalizedArguments.polyfilled.options = normalizedArguments.options.capture;
}
}
});
}
};
EventListenerInterceptor.polyfillListenerOptions();
// var onclick = function() {
// console.log('click');
// };
// document.body.addEventListener('click', onclick, false);
// document.body.addEventListener('click', onclick, { once: true });
// document.body.addEventListener('click', onclick, { once: true });
// document.body.addEventListener('click', onclick, false);
// document.body.addEventListener('click', onclick, false);
})(EventListenerInterceptor);
// For the IE11 build.
SVGElement.prototype.contains = SVGElement.prototype.contains || HTMLElement.prototype.contains // .childElementCount polyfill
// from https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/childElementCount#Polyfill_for_IE8_IE9_Safari
;
(function (constructor) {
if (constructor && constructor.prototype && constructor.prototype.childElementCount == null) {
Object.defineProperty(constructor.prototype, 'childElementCount', {
get: function get() {
var i = 0,
count = 0,
node,
nodes = this.childNodes;
while (node = nodes[i++]) {
if (node.nodeType === 1) count++;
}
return count;
}
});
}
})(window.Node || window.Element);
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line no-undef
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
check(typeof self == 'object' && self) ||
check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
// eslint-disable-next-line no-new-func
(function () { return this; })() || Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
// Detect IE8's incomplete defineProperty implementation
var descriptors = !fails(function () {
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = {}.toString;
var classofRaw = function (it) {
return toString.call(it).slice(8, -1);
};
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var hasOwnProperty = {}.hasOwnProperty;
var has = function (it, key) {
return hasOwnProperty.call(it, key);
};
var document$1 = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document$1) && isObject(document$1.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document$1.createElement(it) : {};
};
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydes