You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
openNG/public/js/bundle.js.old

24515 lines
728 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(1);
var riot = __webpack_require__(3);
__webpack_require__(4).enable("*");
__webpack_require__(8);
$(function () {
riot.mount("*");
});
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {"use strict";
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; };
/*!
* jQuery JavaScript Library v3.2.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2017-03-20T18:59Z
*/
(function (global, factory) {
"use strict";
if (( false ? "undefined" : _typeof(module)) === "object" && _typeof(module.exports) === "object") {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ? factory(global, true) : function (w) {
if (!w.document) {
throw new Error("jQuery requires a window with a document");
}
return factory(w);
};
} else {
factory(global);
}
// Pass this if window is not defined yet
})(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var _slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call(Object);
var support = {};
function DOMEval(code, doc) {
doc = doc || document;
var script = doc.createElement("script");
script.text = code;
doc.head.appendChild(script).parentNode.removeChild(script);
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var version = "3.2.1",
// Define a local copy of jQuery
jQuery = function jQuery(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init(selector, context);
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function fcamelCase(all, letter) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function toArray() {
return _slice.call(this);
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function get(num) {
// Return all the elements in a clean array
if (num == null) {
return _slice.call(this);
}
// Return just the one element from the set
return num < 0 ? this[num + this.length] : this[num];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function pushStack(elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function each(callback) {
return jQuery.each(this, callback);
},
map: function map(callback) {
return this.pushStack(jQuery.map(this, function (elem, i) {
return callback.call(elem, i, elem);
}));
},
slice: function slice() {
return this.pushStack(_slice.apply(this, arguments));
},
first: function first() {
return this.eq(0);
},
last: function last() {
return this.eq(-1);
},
eq: function eq(i) {
var len = this.length,
j = +i + (i < 0 ? len : 0);
return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
},
end: function end() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function () {
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
// Skip the boolean and the target
target = arguments[i] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = jQuery.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
// Assume jQuery is ready without the ready module
isReady: true,
error: function error(msg) {
throw new Error(msg);
},
noop: function noop() {},
isFunction: function isFunction(obj) {
return jQuery.type(obj) === "function";
},
isWindow: function isWindow(obj) {
return obj != null && obj === obj.window;
},
isNumeric: function isNumeric(obj) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type(obj);
return (type === "number" || type === "string") &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN(obj - parseFloat(obj));
},
isPlainObject: function isPlainObject(obj) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if (!obj || toString.call(obj) !== "[object Object]") {
return false;
}
proto = getProto(obj);
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if (!proto) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
},
isEmptyObject: function isEmptyObject(obj) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for (name in obj) {
return false;
}
return true;
},
type: function type(obj) {
if (obj == null) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
},
// Evaluates a script in a global context
globalEval: function globalEval(code) {
DOMEval(code);
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function camelCase(string) {
return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
},
each: function each(obj, callback) {
var length,
i = 0;
if (isArrayLike(obj)) {
length = obj.length;
for (; i < length; i++) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (i in obj) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function trim(text) {
return text == null ? "" : (text + "").replace(rtrim, "");
},
// results is for internal usage only
makeArray: function makeArray(arr, results) {
var ret = results || [];
if (arr != null) {
if (isArrayLike(Object(arr))) {
jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
} else {
push.call(ret, arr);
}
}
return ret;
},
inArray: function inArray(elem, arr, i) {
return arr == null ? -1 : indexOf.call(arr, elem, i);
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function merge(first, second) {
var len = +second.length,
j = 0,
i = first.length;
for (; j < len; j++) {
first[i++] = second[j];
}
first.length = i;
return first;
},
grep: function grep(elems, callback, invert) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for (; i < length; i++) {
callbackInverse = !callback(elems[i], i);
if (callbackInverse !== callbackExpect) {
matches.push(elems[i]);
}
}
return matches;
},
// arg is for internal usage only
map: function map(elems, callback, arg) {
var length,
value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if (isArrayLike(elems)) {
length = elems.length;
for (; i < length; i++) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
// Go through every key on the object,
} else {
for (i in elems) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
}
// Flatten any nested arrays
return concat.apply([], ret);
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function proxy(fn, context) {
var tmp, args, proxy;
if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if (!jQuery.isFunction(fn)) {
return undefined;
}
// Simulated bind
args = _slice.call(arguments, 2);
proxy = function proxy() {
return fn.apply(context || this, args.concat(_slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
if (typeof Symbol === "function") {
jQuery.fn[Symbol.iterator] = arr[Symbol.iterator];
}
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function (i, name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
function isArrayLike(obj) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type(obj);
if (type === "function" || jQuery.isWindow(obj)) {
return false;
}
return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.3
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-08-08
*/
function (window) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function sortOrder(a, b) {
if (a === b) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = {}.hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function indexOf(list, elem) {
var i = 0,
len = list.length;
for (; i < len; i++) {
if (list[i] === elem) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" + ")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp(whitespace + "+", "g"),
rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
rattributeQuotes = new RegExp("=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g"),
rpseudo = new RegExp(pseudos),
ridentifier = new RegExp("^" + identifier + "$"),
matchExpr = {
"ID": new RegExp("^#(" + identifier + ")"),
"CLASS": new RegExp("^\\.(" + identifier + ")"),
"TAG": new RegExp("^(" + identifier + "|[*])"),
"ATTR": new RegExp("^" + attributes),
"PSEUDO": new RegExp("^" + pseudos),
"CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
"bool": new RegExp("^(?:" + booleans + ")$", "i"),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"),
funescape = function funescape(_, escaped, escapedWhitespace) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ? escaped : high < 0 ?
// BMP codepoint
String.fromCharCode(high + 0x10000) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function fcssescape(ch, asCodePoint) {
if (asCodePoint) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if (ch === "\0") {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function unloadHandler() {
setDocument();
},
disabledAncestor = addCombinator(function (elem) {
return elem.disabled === true && ("form" in elem || "label" in elem);
}, { dir: "parentNode", next: "legend" });
// Optimize for push.apply( _, NodeList )
try {
push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
// Support: Android<4.0
// Detect silently failing push.apply
arr[preferredDoc.childNodes.length].nodeType;
} catch (e) {
push = { apply: arr.length ?
// Leverage slice if possible
function (target, els) {
push_native.apply(target, slice.call(els));
} :
// Support: IE<9
// Otherwise append directly
function (target, els) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while (target[j++] = els[i++]) {}
target.length = j - 1;
}
};
}
function Sizzle(selector, context, results, seed) {
var m,
i,
elem,
nid,
match,
groups,
newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if (!seed) {
if ((context ? context.ownerDocument || context : preferredDoc) !== document) {
setDocument(context);
}
context = context || document;
if (documentIsHTML) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {
// ID selector
if (m = match[1]) {
// Document context
if (nodeType === 9) {
if (elem = context.getElementById(m)) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if (elem.id === m) {
results.push(elem);
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if (newContext && (elem = newContext.getElementById(m)) && contains(context, elem) && elem.id === m) {
results.push(elem);
return results;
}
}
// Type selector
} else if (match[2]) {
push.apply(results, context.getElementsByTagName(selector));
return results;
// Class selector
} else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {
push.apply(results, context.getElementsByClassName(m));
return results;
}
}
// Take advantage of querySelectorAll
if (support.qsa && !compilerCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
if (nodeType !== 1) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if (context.nodeName.toLowerCase() !== "object") {
// Capture the context ID, setting it first if necessary
if (nid = context.getAttribute("id")) {
nid = nid.replace(rcssescape, fcssescape);
} else {
context.setAttribute("id", nid = expando);
}
// Prefix every selector in the list
groups = tokenize(selector);
i = groups.length;
while (i--) {
groups[i] = "#" + nid + " " + toSelector(groups[i]);
}
newSelector = groups.join(",");
// Expand context for sibling selectors
newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
}
if (newSelector) {
try {
push.apply(results, newContext.querySelectorAll(newSelector));
return results;
} catch (qsaError) {} finally {
if (nid === expando) {
context.removeAttribute("id");
}
}
}
}
}
}
// All others
return select(selector.replace(rtrim, "$1"), context, results, seed);
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache(key, value) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if (keys.push(key + " ") > Expr.cacheLength) {
// Only keep the most recent entries
delete cache[keys.shift()];
}
return cache[key + " "] = value;
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction(fn) {
fn[expando] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert(fn) {
var el = document.createElement("fieldset");
try {
return !!fn(el);
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if (el.parentNode) {
el.parentNode.removeChild(el);
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle(attrs, handler) {
var arr = attrs.split("|"),
i = arr.length;
while (i--) {
Expr.attrHandle[arr[i]] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck(a, b) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if (diff) {
return diff;
}
// Check if b follows a
if (cur) {
while (cur = cur.nextSibling) {
if (cur === b) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo(disabled) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function (elem) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ("form" in elem) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if (elem.parentNode && elem.disabled === false) {
// Option elements defer to a parent optgroup if present
if ("label" in elem) {
if ("label" in elem.parentNode) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled && disabledAncestor(elem) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ("label" in elem) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo(fn) {
return markFunction(function (argument) {
argument = +argument;
return markFunction(function (seed, matches) {
var j,
matchIndexes = fn([], seed.length, argument),
i = matchIndexes.length;
// Match elements found at the specified indexes
while (i--) {
if (seed[j = matchIndexes[i]]) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext(context) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function (elem) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function (node) {
var hasCompare,
subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if (doc === document || doc.nodeType !== 9 || !doc.documentElement) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML(document);
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if (preferredDoc !== document && (subWindow = document.defaultView) && subWindow.top !== subWindow) {
// Support: IE 11, Edge
if (subWindow.addEventListener) {
subWindow.addEventListener("unload", unloadHandler, false);
// Support: IE 9 - 10 only
} else if (subWindow.attachEvent) {
subWindow.attachEvent("onunload", unloadHandler);
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function (el) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function (el) {
el.appendChild(document.createComment(""));
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test(document.getElementsByClassName);
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function (el) {
docElem.appendChild(el).id = expando;
return !document.getElementsByName || !document.getElementsByName(expando).length;
});
// ID filter and find
if (support.getById) {
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
return elem.getAttribute("id") === attrId;
};
};
Expr.find["ID"] = function (id, context) {
if (typeof context.getElementById !== "undefined" && documentIsHTML) {
var elem = context.getElementById(id);
return elem ? [elem] : [];
}
};
} else {
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find["ID"] = function (id, context) {
if (typeof context.getElementById !== "undefined" && documentIsHTML) {
var node,
i,
elems,
elem = context.getElementById(id);
if (elem) {
// Verify the id attribute
node = elem.getAttributeNode("id");
if (node && node.value === id) {
return [elem];
}
// Fall back on getElementsByName
elems = context.getElementsByName(id);
i = 0;
while (elem = elems[i++]) {
node = elem.getAttributeNode("id");
if (node && node.value === id) {
return [elem];
}
}
}
return [];
}
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ? function (tag, context) {
if (typeof context.getElementsByTagName !== "undefined") {
return context.getElementsByTagName(tag);
// DocumentFragment nodes don't have gEBTN
} else if (support.qsa) {
return context.querySelectorAll(tag);
}
} : function (tag, context) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName(tag);
// Filter out possible comments
if (tag === "*") {
while (elem = results[i++]) {
if (elem.nodeType === 1) {
tmp.push(elem);
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function (className, context) {
if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
return context.getElementsByClassName(className);
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if (support.qsa = rnative.test(document.querySelectorAll)) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function (el) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if (el.querySelectorAll("[msallowcapture^='']").length) {
rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if (!el.querySelectorAll("[selected]").length) {
rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if (!el.querySelectorAll(":checked").length) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if (!el.querySelectorAll("a#" + expando + "+*").length) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function (el) {
el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute("type", "hidden");
el.appendChild(input).setAttribute("name", "D");
// Support: IE8
// Enforce case-sensitivity of name attribute
if (el.querySelectorAll("[name=d]").length) {
rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if (el.querySelectorAll(":enabled").length !== 2) {
rbuggyQSA.push(":enabled", ":disabled");
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild(el).disabled = true;
if (el.querySelectorAll(":disabled").length !== 2) {
rbuggyQSA.push(":enabled", ":disabled");
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if (support.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) {
assert(function (el) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call(el, "*");
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call(el, "[s!='']:x");
rbuggyMatches.push("!=", pseudos);
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test(docElem.compareDocumentPosition);
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
} : function (a, b) {
if (b) {
while (b = b.parentNode) {
if (b === a) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ? function (a, b) {
// Flag for duplicate removal
if (a === b) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if (compare) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
// Choose the first element that is related to our preferred document
if (a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
return -1;
}
if (b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
return 1;
}
// Maintain original order
return sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
}
return compare & 4 ? -1 : 1;
} : function (a, b) {
// Exit early if the nodes are identical
if (a === b) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [a],
bp = [b];
// Parentless nodes are either documents or disconnected
if (!aup || !bup) {
return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
// If the nodes are siblings, we can do a quick check
} else if (aup === bup) {
return siblingCheck(a, b);
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while (cur = cur.parentNode) {
ap.unshift(cur);
}
cur = b;
while (cur = cur.parentNode) {
bp.unshift(cur);
}
// Walk down the tree looking for a discrepancy
while (ap[i] === bp[i]) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck(ap[i], bp[i]) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
};
return document;
};
Sizzle.matches = function (expr, elements) {
return Sizzle(expr, null, null, elements);
};
Sizzle.matchesSelector = function (elem, expr) {
// Set document vars if needed
if ((elem.ownerDocument || elem) !== document) {
setDocument(elem);
}
// Make sure that attribute selectors are quoted
expr = expr.replace(rattributeQuotes, "='$1']");
if (support.matchesSelector && documentIsHTML && !compilerCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
try {
var ret = matches.call(elem, expr);
// IE 9's matchesSelector returns false on disconnected nodes
if (ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11) {
return ret;
}
} catch (e) {}
}
return Sizzle(expr, document, null, [elem]).length > 0;
};
Sizzle.contains = function (context, elem) {
// Set document vars if needed
if ((context.ownerDocument || context) !== document) {
setDocument(context);
}
return contains(context, elem);
};
Sizzle.attr = function (elem, name) {
// Set document vars if needed
if ((elem.ownerDocument || elem) !== document) {
setDocument(elem);
}
var fn = Expr.attrHandle[name.toLowerCase()],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
};
Sizzle.escape = function (sel) {
return (sel + "").replace(rcssescape, fcssescape);
};
Sizzle.error = function (msg) {
throw new Error("Syntax error, unrecognized expression: " + msg);
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function (results) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice(0);
results.sort(sortOrder);
if (hasDuplicate) {
while (elem = results[i++]) {
if (elem === results[i]) {
j = duplicates.push(i);
}
}
while (j--) {
results.splice(duplicates[j], 1);
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function (elem) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if (!nodeType) {
// If no nodeType, this is expected to be an array
while (node = elem[i++]) {
// Do not traverse comment nodes
ret += getText(node);
}
} else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if (typeof elem.textContent === "string") {
return elem.textContent;
} else {
// Traverse its children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText(elem);
}
}
} else if (nodeType === 3 || nodeType === 4) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function ATTR(match) {
match[1] = match[1].replace(runescape, funescape);
// Move the given value to match[3] whether quoted or unquoted
match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape);
if (match[2] === "~=") {
match[3] = " " + match[3] + " ";
}
return match.slice(0, 4);
},
"CHILD": function CHILD(match) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if (match[1].slice(0, 3) === "nth") {
// nth-* requires argument
if (!match[3]) {
Sizzle.error(match[0]);
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
match[5] = +(match[7] + match[8] || match[3] === "odd");
// other types prohibit arguments
} else if (match[3]) {
Sizzle.error(match[0]);
}
return match;
},
"PSEUDO": function PSEUDO(match) {
var excess,
unquoted = !match[6] && match[2];
if (matchExpr["CHILD"].test(match[0])) {
return null;
}
// Accept quoted arguments as-is
if (match[3]) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if (unquoted && rpseudo.test(unquoted) && (
// Get excess from tokenize (recursively)
excess = tokenize(unquoted, true)) && (
// advance to the next closing parenthesis
excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
// excess is a negative index
match[0] = match[0].slice(0, excess);
match[2] = unquoted.slice(0, excess);
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice(0, 3);
}
},
filter: {
"TAG": function TAG(nodeNameSelector) {
var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
return nodeNameSelector === "*" ? function () {
return true;
} : function (elem) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function CLASS(className) {
var pattern = classCache[className + " "];
return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function (elem) {
return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
});
},
"ATTR": function ATTR(name, operator, check) {
return function (elem) {
var result = Sizzle.attr(elem, name);
if (result == null) {
return operator === "!=";
}
if (!operator) {
return true;
}
result += "";
return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false;
};
},
"CHILD": function CHILD(type, what, argument, first, last) {
var simple = type.slice(0, 3) !== "nth",
forward = type.slice(-4) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function (elem) {
return !!elem.parentNode;
} : function (elem, context, xml) {
var cache,
uniqueCache,
outerCache,
node,
nodeIndex,
start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if (parent) {
// :(first|last|only)-(child|of-type)
if (simple) {
while (dir) {
node = elem;
while (node = node[dir]) {
if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [forward ? parent.firstChild : parent.lastChild];
// non-xml :nth-child(...) stores cache data on `parent`
if (forward && useCache) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[expando] || (node[expando] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
cache = uniqueCache[type] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = nodeIndex && cache[2];
node = nodeIndex && parent.childNodes[nodeIndex];
while (node = ++nodeIndex && node && node[dir] || (
// Fallback to seeking `elem` from the start
diff = nodeIndex = 0) || start.pop()) {
// When found, cache indexes on `parent` and break
if (node.nodeType === 1 && ++diff && node === elem) {
uniqueCache[type] = [dirruns, nodeIndex, diff];
break;
}
}
} else {
// Use previously-cached element index if available
if (useCache) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[expando] || (node[expando] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
cache = uniqueCache[type] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if (diff === false) {
// Use the same loop as above to seek `elem` from the start
while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
// Cache the index of each encountered element
if (useCache) {
outerCache = node[expando] || (node[expando] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
uniqueCache[type] = [dirruns, diff];
}
if (node === elem) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || diff % first === 0 && diff / first >= 0;
}
};
},
"PSEUDO": function PSEUDO(pseudo, argument) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if (fn[expando]) {
return fn(argument);
}
// But maintain support for old signatures
if (fn.length > 1) {
args = [pseudo, pseudo, "", argument];
return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
var idx,
matched = fn(seed, argument),
i = matched.length;
while (i--) {
idx = indexOf(seed, matched[i]);
seed[idx] = !(matches[idx] = matched[i]);
}
}) : function (elem) {
return fn(elem, 0, args);
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function (selector) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile(selector.replace(rtrim, "$1"));
return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
var elem,
unmatched = matcher(seed, null, xml, []),
i = seed.length;
// Match elements unmatched by `matcher`
while (i--) {
if (elem = unmatched[i]) {
seed[i] = !(matches[i] = elem);
}
}
}) : function (elem, context, xml) {
input[0] = elem;
matcher(input, null, xml, results);
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function (selector) {
return function (elem) {
return Sizzle(selector, elem).length > 0;
};
}),
"contains": markFunction(function (text) {
text = text.replace(runescape, funescape);
return function (elem) {
return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction(function (lang) {
// lang value must be a valid identifier
if (!ridentifier.test(lang || "")) {
Sizzle.error("unsupported lang: " + lang);
}
lang = lang.replace(runescape, funescape).toLowerCase();
return function (elem) {
var elemLang;
do {
if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
}
} while ((elem = elem.parentNode) && elem.nodeType === 1);
return false;
};
}),
// Miscellaneous
"target": function target(elem) {
var hash = window.location && window.location.hash;
return hash && hash.slice(1) === elem.id;
},
"root": function root(elem) {
return elem === docElem;
},
"focus": function focus(elem) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": createDisabledPseudo(false),
"disabled": createDisabledPseudo(true),
"checked": function checked(elem) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
},
"selected": function selected(elem) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if (elem.parentNode) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function empty(elem) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType < 6) {
return false;
}
}
return true;
},
"parent": function parent(elem) {
return !Expr.pseudos["empty"](elem);
},
// Element/input types
"header": function header(elem) {
return rheader.test(elem.nodeName);
},
"input": function input(elem) {
return rinputs.test(elem.nodeName);
},
"button": function button(elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function text(elem) {
var attr;
return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && (
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
(attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
},
// Position-in-collection
"first": createPositionalPseudo(function () {
return [0];
}),
"last": createPositionalPseudo(function (matchIndexes, length) {
return [length - 1];
}),
"eq": createPositionalPseudo(function (matchIndexes, length, argument) {
return [argument < 0 ? argument + length : argument];
}),
"even": createPositionalPseudo(function (matchIndexes, length) {
var i = 0;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function (matchIndexes, length) {
var i = 1;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; --i >= 0;) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; ++i < length;) {
matchIndexes.push(i);
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) {
Expr.pseudos[i] = createInputPseudo(i);
}
for (i in { submit: true, reset: true }) {
Expr.pseudos[i] = createButtonPseudo(i);
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function (selector, parseOnly) {
var matched,
match,
tokens,
type,
soFar,
groups,
preFilters,
cached = tokenCache[selector + " "];
if (cached) {
return parseOnly ? 0 : cached.slice(0);
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while (soFar) {
// Comma and first run
if (!matched || (match = rcomma.exec(soFar))) {
if (match) {
// Don't consume trailing commas as valid
soFar = soFar.slice(match[0].length) || soFar;
}
groups.push(tokens = []);
}
matched = false;
// Combinators
if (match = rcombinators.exec(soFar)) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace(rtrim, " ")
});
soFar = soFar.slice(matched.length);
}
// Filters
for (type in Expr.filter) {
if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice(matched.length);
}
}
if (!matched) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) :
// Cache the tokens
tokenCache(selector, groups).slice(0);
};
function toSelector(tokens) {
var i = 0,
len = tokens.length,
selector = "";
for (; i < len; i++) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator(matcher, combinator, base) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function (elem, context, xml) {
while (elem = elem[dir]) {
if (elem.nodeType === 1 || checkNonElements) {
return matcher(elem, context, xml);
}
}
return false;
} :
// Check against all ancestor/preceding elements
function (elem, context, xml) {
var oldCache,
uniqueCache,
outerCache,
newCache = [dirruns, doneName];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if (xml) {
while (elem = elem[dir]) {
if (elem.nodeType === 1 || checkNonElements) {
if (matcher(elem, context, xml)) {
return true;
}
}
}
} else {
while (elem = elem[dir]) {
if (elem.nodeType === 1 || checkNonElements) {
outerCache = elem[expando] || (elem[expando] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});
if (skip && skip === elem.nodeName.toLowerCase()) {
elem = elem[dir] || elem;
} else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
// Assign to newCache so results back-propagate to previous elements
return newCache[2] = oldCache[2];
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[key] = newCache;
// A match means we're done; a fail means we have to keep checking
if (newCache[2] = matcher(elem, context, xml)) {
return true;
}
}
}
}
}
return false;
};
}
function elementMatcher(matchers) {
return matchers.length > 1 ? function (elem, context, xml) {
var i = matchers.length;
while (i--) {
if (!matchers[i](elem, context, xml)) {
return false;
}
}
return true;
} : matchers[0];
}
function multipleContexts(selector, contexts, results) {
var i = 0,
len = contexts.length;
for (; i < len; i++) {
Sizzle(selector, contexts[i], results);
}
return results;
}
function condense(unmatched, map, filter, context, xml) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for (; i < len; i++) {
if (elem = unmatched[i]) {
if (!filter || filter(elem, context, xml)) {
newUnmatched.push(elem);
if (mapped) {
map.push(i);
}
}
}
}
return newUnmatched;
}
function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
if (postFilter && !postFilter[expando]) {
postFilter = setMatcher(postFilter);
}
if (postFinder && !postFinder[expando]) {
postFinder = setMatcher(postFinder, postSelector);
}
return markFunction(function (seed, results, context, xml) {
var temp,
i,
elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || (seed ? preFilter : preexisting || postFilter) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results : matcherIn;
// Find primary matches
if (matcher) {
matcher(matcherIn, matcherOut, context, xml);
}
// Apply postFilter
if (postFilter) {
temp = condense(matcherOut, postMap);
postFilter(temp, [], context, xml);
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while (i--) {
if (elem = temp[i]) {
matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
}
}
}
if (seed) {
if (postFinder || preFilter) {
if (postFinder) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while (i--) {
if (elem = matcherOut[i]) {
// Restore matcherIn since elem is not yet a final match
temp.push(matcherIn[i] = elem);
}
}
postFinder(null, matcherOut = [], temp, xml);
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while (i--) {
if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf(seed, elem) : preMap[i]) > -1) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
if (postFinder) {
postFinder(null, results, matcherOut, xml);
} else {
push.apply(results, matcherOut);
}
}
});
}
function matcherFromTokens(tokens) {
var checkContext,
matcher,
j,
len = tokens.length,
leadingRelative = Expr.relative[tokens[0].type],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator(function (elem) {
return elem === checkContext;
}, implicitRelative, true),
matchAnyContext = addCombinator(function (elem) {
return indexOf(checkContext, elem) > -1;
}, implicitRelative, true),
matchers = [function (elem, context, xml) {
var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
}];
for (; i < len; i++) {
if (matcher = Expr.relative[tokens[i].type]) {
matchers = [addCombinator(elementMatcher(matchers), matcher)];
} else {
matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
// Return special upon seeing a positional matcher
if (matcher[expando]) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for (; j < len; j++) {
if (Expr.relative[tokens[j].type]) {
break;
}
}
return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === " " ? "*" : "" })).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
}
matchers.push(matcher);
}
}
return elementMatcher(matchers);
}
function matcherFromGroupMatchers(elementMatchers, setMatchers) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function superMatcher(seed, context, xml, results, outermost) {
var elem,
j,
matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]("*", outermost),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1,
len = elems.length;
if (outermost) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for (; i !== len && (elem = elems[i]) != null; i++) {
if (byElement && elem) {
j = 0;
if (!context && elem.ownerDocument !== document) {
setDocument(elem);
xml = !documentIsHTML;
}
while (matcher = elementMatchers[j++]) {
if (matcher(elem, context || document, xml)) {
results.push(elem);
break;
}
}
if (outermost) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if (bySet) {
// They will have gone through all possible matchers
if (elem = !matcher && elem) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if (seed) {
unmatched.push(elem);
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if (bySet && i !== matchedCount) {
j = 0;
while (matcher = setMatchers[j++]) {
matcher(unmatched, setMatched, context, xml);
}
if (seed) {
// Reintegrate element matches to eliminate the need for sorting
if (matchedCount > 0) {
while (i--) {
if (!(unmatched[i] || setMatched[i])) {
setMatched[i] = pop.call(results);
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense(setMatched);
}
// Add matches to results
push.apply(results, setMatched);
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
Sizzle.uniqueSort(results);
}
}
// Override manipulation of globals by nested matchers
if (outermost) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ? markFunction(superMatcher) : superMatcher;
}
compile = Sizzle.compile = function (selector, match /* Internal Use Only */) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[selector + " "];
if (!cached) {
// Generate a function of recursive functions that can be used to check each element
if (!match) {
match = tokenize(selector);
}
i = match.length;
while (i--) {
cached = matcherFromTokens(match[i]);
if (cached[expando]) {
setMatchers.push(cached);
} else {
elementMatchers.push(cached);
}
}
// Cache the compiled function
cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function (selector, context, results, seed) {
var i,
tokens,
token,
type,
find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize(selector = compiled.selector || selector);
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if (match.length === 1) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice(0);
if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0];
if (!context) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if (compiled) {
context = context.parentNode;
}
selector = selector.slice(tokens.shift().value.length);
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
while (i--) {
token = tokens[i];
// Abort if we hit a combinator
if (Expr.relative[type = token.type]) {
break;
}
if (find = Expr.find[type]) {
// Search, expanding context for leading sibling combinators
if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
// If seed is empty or no tokens remain, we can return early
tokens.splice(i, 1);
selector = seed.length && toSelector(tokens);
if (!selector) {
push.apply(results, seed);
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
(compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function (el) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition(document.createElement("fieldset")) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if (!assert(function (el) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute("href") === "#";
})) {
addHandle("type|href|height|width", function (elem, name, isXML) {
if (!isXML) {
return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if (!support.attributes || !assert(function (el) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute("value", "");
return el.firstChild.getAttribute("value") === "";
})) {
addHandle("value", function (elem, name, isXML) {
if (!isXML && elem.nodeName.toLowerCase() === "input") {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if (!assert(function (el) {
return el.getAttribute("disabled") == null;
})) {
addHandle(booleans, function (elem, name, isXML) {
var val;
if (!isXML) {
return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
}
});
}
return Sizzle;
}(window);
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
// Deprecated
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function dir(elem, _dir, until) {
var matched = [],
truncate = until !== undefined;
while ((elem = elem[_dir]) && elem.nodeType !== 9) {
if (elem.nodeType === 1) {
if (truncate && jQuery(elem).is(until)) {
break;
}
matched.push(elem);
}
}
return matched;
};
var _siblings = function _siblings(n, elem) {
var matched = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
matched.push(n);
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
};
var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow(elements, qualifier, not) {
if (jQuery.isFunction(qualifier)) {
return jQuery.grep(elements, function (elem, i) {
return !!qualifier.call(elem, i, elem) !== not;
});
}
// Single element
if (qualifier.nodeType) {
return jQuery.grep(elements, function (elem) {
return elem === qualifier !== not;
});
}
// Arraylike of elements (jQuery, arguments, Array)
if (typeof qualifier !== "string") {
return jQuery.grep(elements, function (elem) {
return indexOf.call(qualifier, elem) > -1 !== not;
});
}
// Simple selector that can be filtered directly, removing non-Elements
if (risSimple.test(qualifier)) {
return jQuery.filter(qualifier, elements, not);
}
// Complex selector, compare the two sets, removing non-Elements
qualifier = jQuery.filter(qualifier, elements);
return jQuery.grep(elements, function (elem) {
return indexOf.call(qualifier, elem) > -1 !== not && elem.nodeType === 1;
});
}
jQuery.filter = function (expr, elems, not) {
var elem = elems[0];
if (not) {
expr = ":not(" + expr + ")";
}
if (elems.length === 1 && elem.nodeType === 1) {
return jQuery.find.matchesSelector(elem, expr) ? [elem] : [];
}
return jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function find(selector) {
var i,
ret,
len = this.length,
self = this;
if (typeof selector !== "string") {
return this.pushStack(jQuery(selector).filter(function () {
for (i = 0; i < len; i++) {
if (jQuery.contains(self[i], this)) {
return true;
}
}
}));
}
ret = this.pushStack([]);
for (i = 0; i < len; i++) {
jQuery.find(selector, self[i], ret);
}
return len > 1 ? jQuery.uniqueSort(ret) : ret;
},
filter: function filter(selector) {
return this.pushStack(winnow(this, selector || [], false));
},
not: function not(selector) {
return this.pushStack(winnow(this, selector || [], true));
},
is: function is(selector) {
return !!winnow(this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function (selector, context, root) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if (typeof selector === "string") {
if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [null, selector, null];
} else {
match = rquickExpr.exec(selector);
}
// Match html or make sure no context is specified for #id
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1]) {
context = context instanceof jQuery ? context[0] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge(this, jQuery.parseHTML(match[1], context && context.nodeType ? context.ownerDocument || context : document, true));
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for (match in context) {
// Properties of context are called as methods if possible
if (jQuery.isFunction(this[match])) {
this[match](context[match]);
// ...and otherwise set as attributes
} else {
this.attr(match, context[match]);
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById(match[2]);
if (elem) {
// Inject the element directly into the jQuery object
this[0] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if (!context || context.jquery) {
return (context || root).find(selector);
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor(context).find(selector);
}
// HANDLE: $(DOMElement)
} else if (selector.nodeType) {
this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if (jQuery.isFunction(selector)) {
return root.ready !== undefined ? root.ready(selector) :
// Execute immediately if ready is not present
selector(jQuery);
}
return jQuery.makeArray(selector, this);
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery(document);
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
has: function has(target) {
var targets = jQuery(target, this),
l = targets.length;
return this.filter(function () {
var i = 0;
for (; i < l; i++) {
if (jQuery.contains(this, targets[i])) {
return true;
}
}
});
},
closest: function closest(selectors, context) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery(selectors);
// Positional selectors never match, since there's no _selection_ context
if (!rneedsContext.test(selectors)) {
for (; i < l; i++) {
for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
// Always skip document fragments
if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) {
matched.push(cur);
break;
}
}
}
}
return this.pushStack(matched.length > 1 ? jQuery.uniqueSort(matched) : matched);
},
// Determine the position of an element within the set
index: function index(elem) {
// No argument, return index in parent
if (!elem) {
return this[0] && this[0].parentNode ? this.first().prevAll().length : -1;
}
// Index in selector
if (typeof elem === "string") {
return indexOf.call(jQuery(elem), this[0]);
}
// Locate the position of the desired element
return indexOf.call(this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem);
},
add: function add(selector, context) {
return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(), jQuery(selector, context))));
},
addBack: function addBack(selector) {
return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector));
}
});
function sibling(cur, dir) {
while ((cur = cur[dir]) && cur.nodeType !== 1) {}
return cur;
}
jQuery.each({
parent: function parent(elem) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function parents(elem) {
return dir(elem, "parentNode");
},
parentsUntil: function parentsUntil(elem, i, until) {
return dir(elem, "parentNode", until);
},
next: function next(elem) {
return sibling(elem, "nextSibling");
},
prev: function prev(elem) {
return sibling(elem, "previousSibling");
},
nextAll: function nextAll(elem) {
return dir(elem, "nextSibling");
},
prevAll: function prevAll(elem) {
return dir(elem, "previousSibling");
},
nextUntil: function nextUntil(elem, i, until) {
return dir(elem, "nextSibling", until);
},
prevUntil: function prevUntil(elem, i, until) {
return dir(elem, "previousSibling", until);
},
siblings: function siblings(elem) {
return _siblings((elem.parentNode || {}).firstChild, elem);
},
children: function children(elem) {
return _siblings(elem.firstChild);
},
contents: function contents(elem) {
if (nodeName(elem, "iframe")) {
return elem.contentDocument;
}
// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
// Treat the template element as a regular one in browsers that
// don't support it.
if (nodeName(elem, "template")) {
elem = elem.content || elem;
}
return jQuery.merge([], elem.childNodes);
}
}, function (name, fn) {
jQuery.fn[name] = function (until, selector) {
var matched = jQuery.map(this, fn, until);
if (name.slice(-5) !== "Until") {
selector = until;
}
if (selector && typeof selector === "string") {
matched = jQuery.filter(selector, matched);
}
if (this.length > 1) {
// Remove duplicates
if (!guaranteedUnique[name]) {
jQuery.uniqueSort(matched);
}
// Reverse order for parents* and prev-derivatives
if (rparentsprev.test(name)) {
matched.reverse();
}
}
return this.pushStack(matched);
};
});
var rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
// Convert String-formatted options into Object-formatted ones
function createOptions(options) {
var object = {};
jQuery.each(options.match(rnothtmlwhite) || [], function (_, flag) {
object[flag] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function (options) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ? createOptions(options) : jQuery.extend({}, options);
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
_fired,
// Flag to prevent firing
_locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function fire() {
// Enforce single-firing
_locked = _locked || options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
_fired = firing = true;
for (; queue.length; firingIndex = -1) {
memory = queue.shift();
while (++firingIndex < list.length) {
// Run callback and check for early termination
if (list[firingIndex].apply(memory[0], memory[1]) === false && options.stopOnFalse) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if (!options.memory) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if (_locked) {
// Keep an empty list if we have data for future add calls
if (memory) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function add() {
if (list) {
// If we have memory from a past run, we should fire after adding
if (memory && !firing) {
firingIndex = list.length - 1;
queue.push(memory);
}
(function add(args) {
jQuery.each(args, function (_, arg) {
if (jQuery.isFunction(arg)) {
if (!options.unique || !self.has(arg)) {
list.push(arg);
}
} else if (arg && arg.length && jQuery.type(arg) !== "string") {
// Inspect recursively
add(arg);
}
});
})(arguments);
if (memory && !firing) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function remove() {
jQuery.each(arguments, function (_, arg) {
var index;
while ((index = jQuery.inArray(arg, list, index)) > -1) {
list.splice(index, 1);
// Handle firing indexes
if (index <= firingIndex) {
firingIndex--;
}
}
});
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function has(fn) {
return fn ? jQuery.inArray(fn, list) > -1 : list.length > 0;
},
// Remove all callbacks from the list
empty: function empty() {
if (list) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function disable() {
_locked = queue = [];
list = memory = "";
return this;
},
disabled: function disabled() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function lock() {
_locked = queue = [];
if (!memory && !firing) {
list = memory = "";
}
return this;
},
locked: function locked() {
return !!_locked;
},
// Call all callbacks with the given context and arguments
fireWith: function fireWith(context, args) {
if (!_locked) {
args = args || [];
args = [context, args.slice ? args.slice() : args];
queue.push(args);
if (!firing) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function fire() {
self.fireWith(this, arguments);
return this;
},
// To know if the callbacks have already been called at least once
fired: function fired() {
return !!_fired;
}
};
return self;
};
function Identity(v) {
return v;
}
function Thrower(ex) {
throw ex;
}
function adoptValue(value, resolve, reject, noValue) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if (value && jQuery.isFunction(method = value.promise)) {
method.call(value).done(resolve).fail(reject);
// Other thenables
} else if (value && jQuery.isFunction(method = value.then)) {
method.call(value, resolve, reject);
// Other non-thenables
} else {
// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
// * false: [ value ].slice( 0 ) => resolve( value )
// * true: [ value ].slice( 1 ) => resolve()
resolve.apply(undefined, [value].slice(noValue));
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch (value) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.apply(undefined, [value]);
}
}
jQuery.extend({
Deferred: function Deferred(func) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
["notify", "progress", jQuery.Callbacks("memory"), jQuery.Callbacks("memory"), 2], ["resolve", "done", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 0, "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 1, "rejected"]],
_state = "pending",
_promise = {
state: function state() {
return _state;
},
always: function always() {
deferred.done(arguments).fail(arguments);
return this;
},
"catch": function _catch(fn) {
return _promise.then(null, fn);
},
// Keep pipe for back-compat
pipe: function pipe() /* fnDone, fnFail, fnProgress */{
var fns = arguments;
return jQuery.Deferred(function (newDefer) {
jQuery.each(tuples, function (i, tuple) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction(fns[tuple[4]]) && fns[tuple[4]];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[tuple[1]](function () {
var returned = fn && fn.apply(this, arguments);
if (returned && jQuery.isFunction(returned.promise)) {
returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject);
} else {
newDefer[tuple[0] + "With"](this, fn ? [returned] : arguments);
}
});
});
fns = null;
}).promise();
},
then: function then(onFulfilled, onRejected, onProgress) {
var maxDepth = 0;
function resolve(depth, deferred, handler, special) {
return function () {
var that = this,
args = arguments,
mightThrow = function mightThrow() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if (depth < maxDepth) {
return;
}
returned = handler.apply(that, args);
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if (returned === deferred.promise()) {
throw new TypeError("Thenable self-resolution");
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned && (
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
(typeof returned === "undefined" ? "undefined" : _typeof(returned)) === "object" || typeof returned === "function") && returned.then;
// Handle a returned thenable
if (jQuery.isFunction(then)) {
// Special processors (notify) just wait for resolution
if (special) {
then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special));
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special), resolve(maxDepth, deferred, Identity, deferred.notifyWith));
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if (handler !== Identity) {
that = undefined;
args = [returned];
}
// Process the value(s)
// Default process is resolve
(special || deferred.resolveWith)(that, args);
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ? mightThrow : function () {
try {
mightThrow();
} catch (e) {
if (jQuery.Deferred.exceptionHook) {
jQuery.Deferred.exceptionHook(e, process.stackTrace);
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if (depth + 1 >= maxDepth) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if (handler !== Thrower) {
that = undefined;
args = [e];
}
deferred.rejectWith(that, args);
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if (depth) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if (jQuery.Deferred.getStackHook) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout(process);
}
};
}
return jQuery.Deferred(function (newDefer) {
// progress_handlers.add( ... )
tuples[0][3].add(resolve(0, newDefer, jQuery.isFunction(onProgress) ? onProgress : Identity, newDefer.notifyWith));
// fulfilled_handlers.add( ... )
tuples[1][3].add(resolve(0, newDefer, jQuery.isFunction(onFulfilled) ? onFulfilled : Identity));
// rejected_handlers.add( ... )
tuples[2][3].add(resolve(0, newDefer, jQuery.isFunction(onRejected) ? onRejected : Thrower));
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function promise(obj) {
return obj != null ? jQuery.extend(obj, _promise) : _promise;
}
},
deferred = {};
// Add list-specific methods
jQuery.each(tuples, function (i, tuple) {
var list = tuple[2],
stateString = tuple[5];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
_promise[tuple[1]] = list.add;
// Handle state
if (stateString) {
list.add(function () {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
_state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[3 - i][2].disable,
// progress_callbacks.lock
tuples[0][2].lock);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add(tuple[3].fire);
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[tuple[0]] = function () {
deferred[tuple[0] + "With"](this === deferred ? undefined : this, arguments);
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[tuple[0] + "With"] = list.fireWith;
});
// Make the deferred a promise
_promise.promise(deferred);
// Call given func if any
if (func) {
func.call(deferred, deferred);
}
// All done!
return deferred;
},
// Deferred helper
when: function when(singleValue) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array(i),
resolveValues = _slice.call(arguments),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function updateFunc(i) {
return function (value) {
resolveContexts[i] = this;
resolveValues[i] = arguments.length > 1 ? _slice.call(arguments) : value;
if (! --remaining) {
master.resolveWith(resolveContexts, resolveValues);
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if (remaining <= 1) {
adoptValue(singleValue, master.done(updateFunc(i)).resolve, master.reject, !remaining);
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if (master.state() === "pending" || jQuery.isFunction(resolveValues[i] && resolveValues[i].then)) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while (i--) {
adoptValue(resolveValues[i], updateFunc(i), master.reject);
}
return master.promise();
}
});
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function (error, stack) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if (window.console && window.console.warn && error && rerrorNames.test(error.name)) {
window.console.warn("jQuery.Deferred exception: " + error.message, error.stack, stack);
}
};
jQuery.readyException = function (error) {
window.setTimeout(function () {
throw error;
});
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function (fn) {
readyList.then(fn)
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch(function (error) {
jQuery.readyException(error);
});
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function ready(wait) {
// Abort if there are pending holds or we're already ready
if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if (wait !== true && --jQuery.readyWait > 0) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith(document, [jQuery]);
}
});
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener("DOMContentLoaded", completed);
window.removeEventListener("load", completed);
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if (document.readyState === "complete" || document.readyState !== "loading" && !document.documentElement.doScroll) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout(jQuery.ready);
} else {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", completed);
// A fallback to window.onload, that will always work
window.addEventListener("load", completed);
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function access(elems, fn, key, value, chainable, emptyGet, raw) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if (jQuery.type(key) === "object") {
chainable = true;
for (i in key) {
access(elems, fn, i, key[i], true, emptyGet, raw);
}
// Sets one value
} else if (value !== undefined) {
chainable = true;
if (!jQuery.isFunction(value)) {
raw = true;
}
if (bulk) {
// Bulk operations run against the entire set
if (raw) {
fn.call(elems, value);
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function fn(elem, key, value) {
return bulk.call(jQuery(elem), value);
};
}
}
if (fn) {
for (; i < len; i++) {
fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
}
}
}
if (chainable) {
return elems;
}
// Gets
if (bulk) {
return fn.call(elems);
}
return len ? fn(elems[0], key) : emptyGet;
};
var acceptData = function acceptData(owner) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType;
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function cache(owner) {
// Check if the owner object already has a cache
var value = owner[this.expando];
// If not, create one
if (!value) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if (acceptData(owner)) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if (owner.nodeType) {
owner[this.expando] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty(owner, this.expando, {
value: value,
configurable: true
});
}
}
}
return value;
},
set: function set(owner, data, value) {
var prop,
cache = this.cache(owner);
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if (typeof data === "string") {
cache[jQuery.camelCase(data)] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for (prop in data) {
cache[jQuery.camelCase(prop)] = data[prop];
}
}
return cache;
},
get: function get(owner, key) {
return key === undefined ? this.cache(owner) :
// Always use camelCase key (gh-2257)
owner[this.expando] && owner[this.expando][jQuery.camelCase(key)];
},
access: function access(owner, key, value) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if (key === undefined || key && typeof key === "string" && value === undefined) {
return this.get(owner, key);
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set(owner, key, value);
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function remove(owner, key) {
var i,
cache = owner[this.expando];
if (cache === undefined) {
return;
}
if (key !== undefined) {
// Support array or space separated string of keys
if (Array.isArray(key)) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map(jQuery.camelCase);
} else {
key = jQuery.camelCase(key);
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ? [key] : key.match(rnothtmlwhite) || [];
}
i = key.length;
while (i--) {
delete cache[key[i]];
}
}
// Remove the expando if there's no more data
if (key === undefined || jQuery.isEmptyObject(cache)) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if (owner.nodeType) {
owner[this.expando] = undefined;
} else {
delete owner[this.expando];
}
}
},
hasData: function hasData(owner) {
var cache = owner[this.expando];
return cache !== undefined && !jQuery.isEmptyObject(cache);
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function getData(data) {
if (data === "true") {
return true;
}
if (data === "false") {
return false;
}
if (data === "null") {
return null;
}
// Only convert to a number if it doesn't change the string
if (data === +data + "") {
return +data;
}
if (rbrace.test(data)) {
return JSON.parse(data);
}
return data;
}
function dataAttr(elem, key, data) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if (data === undefined && elem.nodeType === 1) {
name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase();
data = elem.getAttribute(name);
if (typeof data === "string") {
try {
data = getData(data);
} catch (e) {}
// Make sure we set the data so it isn't changed later
dataUser.set(elem, key, data);
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function hasData(elem) {
return dataUser.hasData(elem) || dataPriv.hasData(elem);
},
data: function data(elem, name, _data) {
return dataUser.access(elem, name, _data);
},
removeData: function removeData(elem, name) {
dataUser.remove(elem, name);
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function _data(elem, name, data) {
return dataPriv.access(elem, name, data);
},
_removeData: function _removeData(elem, name) {
dataPriv.remove(elem, name);
}
});
jQuery.fn.extend({
data: function data(key, value) {
var i,
name,
data,
elem = this[0],
attrs = elem && elem.attributes;
// Gets all values
if (key === undefined) {
if (this.length) {
data = dataUser.get(elem);
if (elem.nodeType === 1 && !dataPriv.get(elem, "hasDataAttrs")) {
i = attrs.length;
while (i--) {
// Support: IE 11 only
// The attrs elements can be null (#14894)
if (attrs[i]) {
name = attrs[i].name;
if (name.indexOf("data-") === 0) {
name = jQuery.camelCase(name.slice(5));
dataAttr(elem, name, data[name]);
}
}
}
dataPriv.set(elem, "hasDataAttrs", true);
}
}
return data;
}
// Sets multiple values
if ((typeof key === "undefined" ? "undefined" : _typeof(key)) === "object") {
return this.each(function () {
dataUser.set(this, key);
});
}
return access(this, function (value) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if (elem && value === undefined) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get(elem, key);
if (data !== undefined) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr(elem, key);
if (data !== undefined) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function () {
// We always store the camelCased key
dataUser.set(this, key, value);
});
}, null, value, arguments.length > 1, null, true);
},
removeData: function removeData(key) {
return this.each(function () {
dataUser.remove(this, key);
});
}
});
jQuery.extend({
queue: function queue(elem, type, data) {
var queue;
if (elem) {
type = (type || "fx") + "queue";
queue = dataPriv.get(elem, type);
// Speed up dequeue by getting out quickly if this is just a lookup
if (data) {
if (!queue || Array.isArray(data)) {
queue = dataPriv.access(elem, type, jQuery.makeArray(data));
} else {
queue.push(data);
}
}
return queue || [];
}
},
dequeue: function dequeue(elem, type) {
type = type || "fx";
var queue = jQuery.queue(elem, type),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks(elem, type),
next = function next() {
jQuery.dequeue(elem, type);
};
// If the fx queue is dequeued, always remove the progress sentinel
if (fn === "inprogress") {
fn = queue.shift();
startLength--;
}
if (fn) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if (type === "fx") {
queue.unshift("inprogress");
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call(elem, next, hooks);
}
if (!startLength && hooks) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function _queueHooks(elem, type) {
var key = type + "queueHooks";
return dataPriv.get(elem, key) || dataPriv.access(elem, key, {
empty: jQuery.Callbacks("once memory").add(function () {
dataPriv.remove(elem, [type + "queue", key]);
})
});
}
});
jQuery.fn.extend({
queue: function queue(type, data) {
var setter = 2;
if (typeof type !== "string") {
data = type;
type = "fx";
setter--;
}
if (arguments.length < setter) {
return jQuery.queue(this[0], type);
}
return data === undefined ? this : this.each(function () {
var queue = jQuery.queue(this, type, data);
// Ensure a hooks for this queue
jQuery._queueHooks(this, type);
if (type === "fx" && queue[0] !== "inprogress") {
jQuery.dequeue(this, type);
}
});
},
dequeue: function dequeue(type) {
return this.each(function () {
jQuery.dequeue(this, type);
});
},
clearQueue: function clearQueue(type) {
return this.queue(type || "fx", []);
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function promise(type, obj) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function resolve() {
if (! --count) {
defer.resolveWith(elements, [elements]);
}
};
if (typeof type !== "string") {
obj = type;
type = undefined;
}
type = type || "fx";
while (i--) {
tmp = dataPriv.get(elements[i], type + "queueHooks");
if (tmp && tmp.empty) {
count++;
tmp.empty.add(resolve);
}
}
resolve();
return defer.promise(obj);
}
});
var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
var rcssNum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i");
var cssExpand = ["Top", "Right", "Bottom", "Left"];
var isHiddenWithinTree = function isHiddenWithinTree(elem, el) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" || elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains(elem.ownerDocument, elem) && jQuery.css(elem, "display") === "none";
};
var swap = function swap(elem, options, callback, args) {
var ret,
name,
old = {};
// Remember the old values, and insert the new ones
for (name in options) {
old[name] = elem.style[name];
elem.style[name] = options[name];
}
ret = callback.apply(elem, args || []);
// Revert the old values
for (name in options) {
elem.style[name] = old[name];
}
return ret;
};
function adjustCSS(elem, prop, valueParts, tween) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ? function () {
return tween.cur();
} : function () {
return jQuery.css(elem, prop, "");
},
initial = currentValue(),
unit = valueParts && valueParts[3] || (jQuery.cssNumber[prop] ? "" : "px"),
// Starting value computation is required for potential unit mismatches
initialInUnit = (jQuery.cssNumber[prop] || unit !== "px" && +initial) && rcssNum.exec(jQuery.css(elem, prop));
if (initialInUnit && initialInUnit[3] !== unit) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[3];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style(elem, prop, initialInUnit + unit);
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (scale !== (scale = currentValue() / initial) && scale !== 1 && --maxIterations);
}
if (valueParts) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2];
if (tween) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay(elem) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[nodeName];
if (display) {
return display;
}
temp = doc.body.appendChild(doc.createElement(nodeName));
display = jQuery.css(temp, "display");
temp.parentNode.removeChild(temp);
if (display === "none") {
display = "block";
}
defaultDisplayMap[nodeName] = display;
return display;
}
function showHide(elements, show) {
var display,
elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for (; index < length; index++) {
elem = elements[index];
if (!elem.style) {
continue;
}
display = elem.style.display;
if (show) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if (display === "none") {
values[index] = dataPriv.get(elem, "display") || null;
if (!values[index]) {
elem.style.display = "";
}
}
if (elem.style.display === "" && isHiddenWithinTree(elem)) {
values[index] = getDefaultDisplay(elem);
}
} else {
if (display !== "none") {
values[index] = "none";
// Remember what we're overwriting
dataPriv.set(elem, "display", display);
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for (index = 0; index < length; index++) {
if (values[index] != null) {
elements[index].style.display = values[index];
}
}
return elements;
}
jQuery.fn.extend({
show: function show() {
return showHide(this, true);
},
hide: function hide() {
return showHide(this);
},
toggle: function toggle(state) {
if (typeof state === "boolean") {
return state ? this.show() : this.hide();
}
return this.each(function () {
if (isHiddenWithinTree(this)) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
}
});
var rcheckableType = /^(?:checkbox|radio)$/i;
var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i;
var rscriptType = /^$|\/(?:java|ecma)script/i;
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [1, "<select multiple='multiple'>", "</select>"],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [1, "<table>", "</table>"],
col: [2, "<table><colgroup>", "</colgroup></table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
_default: [0, "", ""]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll(context, tag) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
if (typeof context.getElementsByTagName !== "undefined") {
ret = context.getElementsByTagName(tag || "*");
} else if (typeof context.querySelectorAll !== "undefined") {
ret = context.querySelectorAll(tag || "*");
} else {
ret = [];
}
if (tag === undefined || tag && nodeName(context, tag)) {
return jQuery.merge([context], ret);
}
return ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval(elems, refElements) {
var i = 0,
l = elems.length;
for (; i < l; i++) {
dataPriv.set(elems[i], "globalEval", !refElements || dataPriv.get(refElements[i], "globalEval"));
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment(elems, context, scripts, selection, ignored) {
var elem,
tmp,
tag,
wrap,
contains,
j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for (; i < l; i++) {
elem = elems[i];
if (elem || elem === 0) {
// Add nodes directly
if (jQuery.type(elem) === "object") {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(nodes, elem.nodeType ? [elem] : elem);
// Convert non-html into a text node
} else if (!rhtml.test(elem)) {
nodes.push(context.createTextNode(elem));
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild(context.createElement("div"));
// Deserialize a standard representation
tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + jQuery.htmlPrefilter(elem) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while (j--) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(nodes, tmp.childNodes);
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while (elem = nodes[i++]) {
// Skip elements already in the context collection (trac-4087)
if (selection && jQuery.inArray(elem, selection) > -1) {
if (ignored) {
ignored.push(elem);
}
continue;
}
contains = jQuery.contains(elem.ownerDocument, elem);
// Append to fragment
tmp = getAll(fragment.appendChild(elem), "script");
// Preserve script evaluation history
if (contains) {
setGlobalEval(tmp);
}
// Capture executables
if (scripts) {
j = 0;
while (elem = tmp[j++]) {
if (rscriptType.test(elem.type || "")) {
scripts.push(elem);
}
}
}
}
return fragment;
}
(function () {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild(document.createElement("div")),
input = document.createElement("input");
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute("type", "radio");
input.setAttribute("checked", "checked");
input.setAttribute("name", "t");
div.appendChild(input);
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
})();
var documentElement = document.documentElement;
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch (err) {}
}
function _on(elem, types, selector, data, fn, one) {
var origFn, type;
// Types can be a map of types/handlers
if ((typeof types === "undefined" ? "undefined" : _typeof(types)) === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for (type in types) {
_on(elem, type, selector, data, types[type], one);
}
return elem;
}
if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return elem;
}
if (one === 1) {
origFn = fn;
fn = function fn(event) {
// Can use an empty set, since event contains the info
jQuery().off(event);
return origFn.apply(this, arguments);
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
}
return elem.each(function () {
jQuery.event.add(this, types, fn, data, selector);
});
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function add(elem, types, handler, data, selector) {
var handleObjIn,
eventHandle,
tmp,
events,
t,
handleObj,
special,
handlers,
type,
namespaces,
origType,
elemData = dataPriv.get(elem);
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if (!elemData) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if (handler.handler) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if (selector) {
jQuery.find.matchesSelector(documentElement, selector);
}
// Make sure that the handler has a unique ID, used to find/remove it later
if (!handler.guid) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if (!(events = elemData.events)) {
events = elemData.events = {};
}
if (!(eventHandle = elemData.handle)) {
eventHandle = elemData.handle = function (e) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply(elem, arguments) : undefined;
};
}
// Handle multiple events separated by a space
types = (types || "").match(rnothtmlwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = (tmp[2] || "").split(".").sort();
// There *must* be a type, no attaching namespace-only handlers
if (!type) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[type] || {};
// If selector defined, determine special event api type, otherwise given type
type = (selector ? special.delegateType : special.bindType) || type;
// Update special based on newly reset type
special = jQuery.event.special[type] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test(selector),
namespace: namespaces.join(".")
}, handleObjIn);
// Init the event handler queue if we're the first
if (!(handlers = events[type])) {
handlers = events[type] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle);
}
}
}
if (special.add) {
special.add.call(elem, handleObj);
if (!handleObj.handler.guid) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if (selector) {
handlers.splice(handlers.delegateCount++, 0, handleObj);
} else {
handlers.push(handleObj);
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[type] = true;
}
},
// Detach an event or set of events from an element
remove: function remove(elem, types, handler, selector, mappedTypes) {
var j,
origCount,
tmp,
events,
t,
handleObj,
special,
handlers,
type,
namespaces,
origType,
elemData = dataPriv.hasData(elem) && dataPriv.get(elem);
if (!elemData || !(events = elemData.events)) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = (types || "").match(rnothtmlwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = (tmp[2] || "").split(".").sort();
// Unbind all events (on this namespace, if provided) for the element
if (!type) {
for (type in events) {
jQuery.event.remove(elem, type + types[t], handler, selector, true);
}
continue;
}
special = jQuery.event.special[type] || {};
type = (selector ? special.delegateType : special.bindType) || type;
handlers = events[type] || [];
tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
// Remove matching events
origCount = j = handlers.length;
while (j--) {
handleObj = handlers[j];
if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
handlers.splice(j, 1);
if (handleObj.selector) {
handlers.delegateCount--;
}
if (special.remove) {
special.remove.call(elem, handleObj);
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if (origCount && !handlers.length) {
if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
jQuery.removeEvent(elem, type, elemData.handle);
}
delete events[type];
}
}
// Remove data and the expando if it's no longer used
if (jQuery.isEmptyObject(events)) {
dataPriv.remove(elem, "handle events");
}
},
dispatch: function dispatch(nativeEvent) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix(nativeEvent);
var i,
j,
ret,
matched,
handleObj,
handlerQueue,
args = new Array(arguments.length),
handlers = (dataPriv.get(this, "events") || {})[event.type] || [],
special = jQuery.event.special[event.type] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
for (i = 1; i < arguments.length; i++) {
args[i] = arguments[i];
}
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if (special.preDispatch && special.preDispatch.call(this, event) === false) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call(this, event, handlers);
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
event.currentTarget = matched.elem;
j = 0;
while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if (!event.rnamespace || event.rnamespace.test(handleObj.namespace)) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);
if (ret !== undefined) {
if ((event.result = ret) === false) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if (special.postDispatch) {
special.postDispatch.call(this, event);
}
return event.result;
},
handlers: function handlers(event, _handlers) {
var i,
handleObj,
sel,
matchedHandlers,
matchedSelectors,
handlerQueue = [],
delegateCount = _handlers.delegateCount,
cur = event.target;
// Find delegate handlers
if (delegateCount &&
// Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType &&
// Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!(event.type === "click" && event.button >= 1)) {
for (; cur !== this; cur = cur.parentNode || this) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if (cur.nodeType === 1 && !(event.type === "click" && cur.disabled === true)) {
matchedHandlers = [];
matchedSelectors = {};
for (i = 0; i < delegateCount; i++) {
handleObj = _handlers[i];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if (matchedSelectors[sel] === undefined) {
matchedSelectors[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) > -1 : jQuery.find(sel, this, null, [cur]).length;
}
if (matchedSelectors[sel]) {
matchedHandlers.push(handleObj);
}
}
if (matchedHandlers.length) {
handlerQueue.push({ elem: cur, handlers: matchedHandlers });
}
}
}
}
// Add the remaining (directly-bound) handlers
cur = this;
if (delegateCount < _handlers.length) {
handlerQueue.push({ elem: cur, handlers: _handlers.slice(delegateCount) });
}
return handlerQueue;
},
addProp: function addProp(name, hook) {
Object.defineProperty(jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction(hook) ? function () {
if (this.originalEvent) {
return hook(this.originalEvent);
}
} : function () {
if (this.originalEvent) {
return this.originalEvent[name];
}
},
set: function set(value) {
Object.defineProperty(this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
});
}
});
},
fix: function fix(originalEvent) {
return originalEvent[jQuery.expando] ? originalEvent : new jQuery.Event(originalEvent);
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function trigger() {
if (this !== safeActiveElement() && this.focus) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function trigger() {
if (this === safeActiveElement() && this.blur) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function trigger() {
if (this.type === "checkbox" && this.click && nodeName(this, "input")) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function _default(event) {
return nodeName(event.target, "a");
}
},
beforeunload: {
postDispatch: function postDispatch(event) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if (event.result !== undefined && event.originalEvent) {
event.originalEvent.returnValue = event.result;
}
}
}
}
};
jQuery.removeEvent = function (elem, type, handle) {
// This "if" is needed for plain objects
if (elem.removeEventListener) {
elem.removeEventListener(type, handle);
}
};
jQuery.Event = function (src, props) {
// Allow instantiation without the 'new' keyword
if (!(this instanceof jQuery.Event)) {
return new jQuery.Event(src, props);
}
// Event object
if (src && src.type) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined &&
// Support: Android <=2.3 only
src.returnValue === false ? returnTrue : returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = src.target && src.target.nodeType === 3 ? src.target.parentNode : src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if (props) {
jQuery.extend(this, props);
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[jQuery.expando] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function preventDefault() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (e && !this.isSimulated) {
e.preventDefault();
}
},
stopPropagation: function stopPropagation() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (e && !this.isSimulated) {
e.stopPropagation();
}
},
stopImmediatePropagation: function stopImmediatePropagation() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if (e && !this.isSimulated) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each({
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function which(event) {
var button = event.button;
// Add which for key events
if (event.which == null && rkeyEvent.test(event.type)) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if (!event.which && button !== undefined && rmouseEvent.test(event.type)) {
if (button & 1) {
return 1;
}
if (button & 2) {
return 3;
}
if (button & 4) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp);
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function (orig, fix) {
jQuery.event.special[orig] = {
delegateType: fix,
bindType: fix,
handle: function handle(event) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || related !== target && !jQuery.contains(target, related)) {
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = fix;
}
return ret;
}
};
});
jQuery.fn.extend({
on: function on(types, selector, data, fn) {
return _on(this, types, selector, data, fn);
},
one: function one(types, selector, data, fn) {
return _on(this, types, selector, data, fn, 1);
},
off: function off(types, selector, fn) {
var handleObj, type;
if (types && types.preventDefault && types.handleObj) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
return this;
}
if ((typeof types === "undefined" ? "undefined" : _typeof(types)) === "object") {
// ( types-object [, selector] )
for (type in types) {
this.off(type, selector, types[type]);
}
return this;
}
if (selector === false || typeof selector === "function") {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if (fn === false) {
fn = returnFalse;
}
return this.each(function () {
jQuery.event.remove(this, types, fn, selector);
});
}
});
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// Prefer a tbody over its parent table for containing new rows
function manipulationTarget(elem, content) {
if (nodeName(elem, "table") && nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) {
return jQuery(">tbody", elem)[0] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript(elem) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript(elem) {
var match = rscriptTypeMasked.exec(elem.type);
if (match) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
function cloneCopyEvent(src, dest) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if (dest.nodeType !== 1) {
return;
}
// 1. Copy private data: events, handlers, etc.
if (dataPriv.hasData(src)) {
pdataOld = dataPriv.access(src);
pdataCur = dataPriv.set(dest, pdataOld);
events = pdataOld.events;
if (events) {
delete pdataCur.handle;
pdataCur.events = {};
for (type in events) {
for (i = 0, l = events[type].length; i < l; i++) {
jQuery.event.add(dest, type, events[type][i]);
}
}
}
}
// 2. Copy user data
if (dataUser.hasData(src)) {
udataOld = dataUser.access(src);
udataCur = jQuery.extend({}, udataOld);
dataUser.set(dest, udataCur);
}
}
// Fix IE bugs, see support tests
function fixInput(src, dest) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if (nodeName === "input" && rcheckableType.test(src.type)) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if (nodeName === "input" || nodeName === "textarea") {
dest.defaultValue = src.defaultValue;
}
}
function domManip(collection, args, callback, ignored) {
// Flatten any nested arrays
args = concat.apply([], args);
var fragment,
first,
scripts,
hasScripts,
node,
doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction(value);
// We can't cloneNode fragments that contain checked, in WebKit
if (isFunction || l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value)) {
return collection.each(function (index) {
var self = collection.eq(index);
if (isFunction) {
args[0] = value.call(this, index, self.html());
}
domManip(self, args, callback, ignored);
});
}
if (l) {
fragment = buildFragment(args, collection[0].ownerDocument, false, collection, ignored);
first = fragment.firstChild;
if (fragment.childNodes.length === 1) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if (first || ignored) {
scripts = jQuery.map(getAll(fragment, "script"), disableScript);
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for (; i < l; i++) {
node = fragment;
if (i !== iNoClone) {
node = jQuery.clone(node, true, true);
// Keep references to cloned scripts for later restoration
if (hasScripts) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(scripts, getAll(node, "script"));
}
}
callback.call(collection[i], node, i);
}
if (hasScripts) {
doc = scripts[scripts.length - 1].ownerDocument;
// Reenable scripts
jQuery.map(scripts, restoreScript);
// Evaluate executable scripts on first document insertion
for (i = 0; i < hasScripts; i++) {
node = scripts[i];
if (rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery.contains(doc, node)) {
if (node.src) {
// Optional AJAX dependency, but won't run scripts if not present
if (jQuery._evalUrl) {
jQuery._evalUrl(node.src);
}
} else {
DOMEval(node.textContent.replace(rcleanScript, ""), doc);
}
}
}
}
}
}
return collection;
}
function _remove(elem, selector, keepData) {
var node,
nodes = selector ? jQuery.filter(selector, elem) : elem,
i = 0;
for (; (node = nodes[i]) != null; i++) {
if (!keepData && node.nodeType === 1) {
jQuery.cleanData(getAll(node));
}
if (node.parentNode) {
if (keepData && jQuery.contains(node.ownerDocument, node)) {
setGlobalEval(getAll(node, "script"));
}
node.parentNode.removeChild(node);
}
}
return elem;
}
jQuery.extend({
htmlPrefilter: function htmlPrefilter(html) {
return html.replace(rxhtmlTag, "<$1></$2>");
},
clone: function clone(elem, dataAndEvents, deepDataAndEvents) {
var i,
l,
srcElements,
destElements,
clone = elem.cloneNode(true),
inPage = jQuery.contains(elem.ownerDocument, elem);
// Fix IE cloning issues
if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll(clone);
srcElements = getAll(elem);
for (i = 0, l = srcElements.length; i < l; i++) {
fixInput(srcElements[i], destElements[i]);
}
}
// Copy the events from the original to the clone
if (dataAndEvents) {
if (deepDataAndEvents) {
srcElements = srcElements || getAll(elem);
destElements = destElements || getAll(clone);
for (i = 0, l = srcElements.length; i < l; i++) {
cloneCopyEvent(srcElements[i], destElements[i]);
}
} else {
cloneCopyEvent(elem, clone);
}
}
// Preserve script evaluation history
destElements = getAll(clone, "script");
if (destElements.length > 0) {
setGlobalEval(destElements, !inPage && getAll(elem, "script"));
}
// Return the cloned set
return clone;
},
cleanData: function cleanData(elems) {
var data,
elem,
type,
special = jQuery.event.special,
i = 0;
for (; (elem = elems[i]) !== undefined; i++) {
if (acceptData(elem)) {
if (data = elem[dataPriv.expando]) {
if (data.events) {
for (type in data.events) {
if (special[type]) {
jQuery.event.remove(elem, type);
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent(elem, type, data.handle);
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[dataPriv.expando] = undefined;
}
if (elem[dataUser.expando]) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[dataUser.expando] = undefined;
}
}
}
}
});
jQuery.fn.extend({
detach: function detach(selector) {
return _remove(this, selector, true);
},
remove: function remove(selector) {
return _remove(this, selector);
},
text: function text(value) {
return access(this, function (value) {
return value === undefined ? jQuery.text(this) : this.empty().each(function () {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.textContent = value;
}
});
}, null, value, arguments.length);
},
append: function append() {
return domManip(this, arguments, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
var target = manipulationTarget(this, elem);
target.appendChild(elem);
}
});
},
prepend: function prepend() {
return domManip(this, arguments, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
var target = manipulationTarget(this, elem);
target.insertBefore(elem, target.firstChild);
}
});
},
before: function before() {
return domManip(this, arguments, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this);
}
});
},
after: function after() {
return domManip(this, arguments, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this.nextSibling);
}
});
},
empty: function empty() {
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
if (elem.nodeType === 1) {
// Prevent memory leaks
jQuery.cleanData(getAll(elem, false));
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function clone(dataAndEvents, deepDataAndEvents) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function () {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
},
html: function html(value) {
return access(this, function (value) {
var elem = this[0] || {},
i = 0,
l = this.length;
if (value === undefined && elem.nodeType === 1) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if (typeof value === "string" && !rnoInnerhtml.test(value) && !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) {
value = jQuery.htmlPrefilter(value);
try {
for (; i < l; i++) {
elem = this[i] || {};
// Remove element nodes and prevent memory leaks
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch (e) {}
}
if (elem) {
this.empty().append(value);
}
}, null, value, arguments.length);
},
replaceWith: function replaceWith() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip(this, arguments, function (elem) {
var parent = this.parentNode;
if (jQuery.inArray(this, ignored) < 0) {
jQuery.cleanData(getAll(this));
if (parent) {
parent.replaceChild(elem, this);
}
}
// Force callback invocation
}, ignored);
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function (name, original) {
jQuery.fn[name] = function (selector) {
var elems,
ret = [],
insert = jQuery(selector),
last = insert.length - 1,
i = 0;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
});
var rmargin = /^margin/;
var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");
var getStyles = function getStyles(elem) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if (!view || !view.opener) {
view = window;
}
return view.getComputedStyle(elem);
};
(function () {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if (!div) {
return;
}
div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild(container);
var divStyle = window.getComputedStyle(div);
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild(container);
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal,
boxSizingReliableVal,
pixelMarginRightVal,
reliableMarginLeftVal,
container = document.createElement("div"),
div = document.createElement("div");
// Finish early in limited (non-browser) environments
if (!div.style) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode(true).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute";
container.appendChild(div);
jQuery.extend(support, {
pixelPosition: function pixelPosition() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function boxSizingReliable() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function pixelMarginRight() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function reliableMarginLeft() {
computeStyleTests();
return reliableMarginLeftVal;
}
});
})();
function curCSS(elem, name, computed) {
var width,
minWidth,
maxWidth,
ret,
// Support: Firefox 51+
// Retrieving style before computed somehow
// fixes an issue with getting wrong values
// on detached elements
style = elem.style;
computed = computed || getStyles(elem);
// getPropertyValue is needed for:
// .css('filter') (IE 9 only, #12537)
// .css('--customProperty) (#3144)
if (computed) {
ret = computed.getPropertyValue(name) || computed[name];
if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {
ret = jQuery.style(elem, name);
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if (!support.pixelMarginRight() && rnumnonpx.test(ret) && rmargin.test(name)) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" : ret;
}
function addGetHookIf(conditionFn, hookFn) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function get() {
if (conditionFn()) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply(this, arguments);
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rcustomProp = /^--/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = ["Webkit", "Moz", "ms"],
emptyStyle = document.createElement("div").style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName(name) {
// Shortcut for names that are not vendor prefixed
if (name in emptyStyle) {
return name;
}
// Check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
i = cssPrefixes.length;
while (i--) {
name = cssPrefixes[i] + capName;
if (name in emptyStyle) {
return name;
}
}
}
// Return a property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName(name) {
var ret = jQuery.cssProps[name];
if (!ret) {
ret = jQuery.cssProps[name] = vendorPropName(name) || name;
}
return ret;
}
function setPositiveNumber(elem, value, subtract) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec(value);
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") : value;
}
function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
var i,
val = 0;
// If we already have the right measurement, avoid augmentation
if (extra === (isBorderBox ? "border" : "content")) {
i = 4;
// Otherwise initialize for horizontal or vertical properties
} else {
i = name === "width" ? 1 : 0;
}
for (; i < 4; i += 2) {
// Both box models exclude margin, so add it if we want it
if (extra === "margin") {
val += jQuery.css(elem, extra + cssExpand[i], true, styles);
}
if (isBorderBox) {
// border-box includes padding, so remove it if we want content
if (extra === "content") {
val -= jQuery.css(elem, "padding" + cssExpand[i], true, styles);
}
// At this point, extra isn't border nor margin, so remove border
if (extra !== "margin") {
val -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css(elem, "padding" + cssExpand[i], true, styles);
// At this point, extra isn't content nor padding, so add border
if (extra !== "padding") {
val += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
}
}
}
return val;
}
function getWidthOrHeight(elem, name, extra) {
// Start with computed style
var valueIsBorderBox,
styles = getStyles(elem),
val = curCSS(elem, name, styles),
isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box";
// Computed unit is not pixels. Stop here and return.
if (rnumnonpx.test(val)) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && (support.boxSizingReliable() || val === elem.style[name]);
// Fall back to offsetWidth/Height when value is "auto"
// This happens for inline elements with no explicit setting (gh-3571)
if (val === "auto") {
val = elem["offset" + name[0].toUpperCase() + name.slice(1)];
}
// Normalize "", auto, and prepare for extra
val = parseFloat(val) || 0;
// Use the active box-sizing model to add/subtract irrelevant styles
return val + augmentWidthOrHeight(elem, name, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function get(elem, computed) {
if (computed) {
// We should always get a number back from opacity
var ret = curCSS(elem, "opacity");
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function style(elem, name, value, extra) {
// Don't set styles on text and comment nodes
if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
return;
}
// Make sure that we're working with the right name
var ret,
type,
hooks,
origName = jQuery.camelCase(name),
isCustomProp = rcustomProp.test(name),
style = elem.style;
// Make sure that we're working with the right name. We don't
// want to query the value if it is a CSS custom property
// since they are user-defined.
if (!isCustomProp) {
name = finalPropName(origName);
}
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
// Check if we're setting a value
if (value !== undefined) {
type = typeof value === "undefined" ? "undefined" : _typeof(value);
// Convert "+=" or "-=" to relative numbers (#7345)
if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) {
value = adjustCSS(elem, name, ret);
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if (value == null || value !== value) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if (type === "number") {
value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px");
}
// background-* props affect original clone's values
if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
style[name] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {
if (isCustomProp) {
style.setProperty(name, value);
} else {
style[name] = value;
}
}
} else {
// If a hook was provided get the non-computed value from there
if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
return ret;
}
// Otherwise just get the value from the style object
return style[name];
}
},
css: function css(elem, name, extra, styles) {
var val,
num,
hooks,
origName = jQuery.camelCase(name),
isCustomProp = rcustomProp.test(name);
// Make sure that we're working with the right name. We don't
// want to modify the value if it is a CSS custom property
// since they are user-defined.
if (!isCustomProp) {
name = finalPropName(origName);
}
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
// If a hook was provided get the computed value from there
if (hooks && "get" in hooks) {
val = hooks.get(elem, true, extra);
}
// Otherwise, if a way to get the computed value exists, use that
if (val === undefined) {
val = curCSS(elem, name, styles);
}
// Convert "normal" to computed value
if (val === "normal" && name in cssNormalTransform) {
val = cssNormalTransform[name];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if (extra === "" || extra) {
num = parseFloat(val);
return extra === true || isFinite(num) ? num || 0 : val;
}
return val;
}
});
jQuery.each(["height", "width"], function (i, name) {
jQuery.cssHooks[name] = {
get: function get(elem, computed, extra) {
if (computed) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test(jQuery.css(elem, "display")) && (
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
!elem.getClientRects().length || !elem.getBoundingClientRect().width) ? swap(elem, cssShow, function () {
return getWidthOrHeight(elem, name, extra);
}) : getWidthOrHeight(elem, name, extra);
}
},
set: function set(elem, value, extra) {
var matches,
styles = extra && getStyles(elem),
subtract = extra && augmentWidthOrHeight(elem, name, extra, jQuery.css(elem, "boxSizing", false, styles) === "border-box", styles);
// Convert to pixels if value adjustment is needed
if (subtract && (matches = rcssNum.exec(value)) && (matches[3] || "px") !== "px") {
elem.style[name] = value;
value = jQuery.css(elem, name);
}
return setPositiveNumber(elem, value, subtract);
}
};
});
jQuery.cssHooks.marginLeft = addGetHookIf(support.reliableMarginLeft, function (elem, computed) {
if (computed) {
return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap(elem, { marginLeft: 0 }, function () {
return elem.getBoundingClientRect().left;
})) + "px";
}
});
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function (prefix, suffix) {
jQuery.cssHooks[prefix + suffix] = {
expand: function expand(value) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [value];
for (; i < 4; i++) {
expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0];
}
return expanded;
}
};
if (!rmargin.test(prefix)) {
jQuery.cssHooks[prefix + suffix].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function css(name, value) {
return access(this, function (elem, name, value) {
var styles,
len,
map = {},
i = 0;
if (Array.isArray(name)) {
styles = getStyles(elem);
len = name.length;
for (; i < len; i++) {
map[name[i]] = jQuery.css(elem, name[i], false, styles);
}
return map;
}
return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name);
}, name, value, arguments.length > 1);
}
});
function Tween(elem, options, prop, end, easing) {
return new Tween.prototype.init(elem, options, prop, end, easing);
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function init(elem, options, prop, end, easing, unit) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px");
},
cur: function cur() {
var hooks = Tween.propHooks[this.prop];
return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this);
},
run: function run(percent) {
var eased,
hooks = Tween.propHooks[this.prop];
if (this.options.duration) {
this.pos = eased = jQuery.easing[this.easing](percent, this.options.duration * percent, 0, 1, this.options.duration);
} else {
this.pos = eased = percent;
}
this.now = (this.end - this.start) * eased + this.start;
if (this.options.step) {
this.options.step.call(this.elem, this.now, this);
}
if (hooks && hooks.set) {
hooks.set(this);
} else {
Tween.propHooks._default.set(this);
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function get(tween) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if (tween.elem.nodeType !== 1 || tween.elem[tween.prop] != null && tween.elem.style[tween.prop] == null) {
return tween.elem[tween.prop];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css(tween.elem, tween.prop, "");
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function set(tween) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if (jQuery.fx.step[tween.prop]) {
jQuery.fx.step[tween.prop](tween);
} else if (tween.elem.nodeType === 1 && (tween.elem.style[jQuery.cssProps[tween.prop]] != null || jQuery.cssHooks[tween.prop])) {
jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
} else {
tween.elem[tween.prop] = tween.now;
}
}
}
};
// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function set(tween) {
if (tween.elem.nodeType && tween.elem.parentNode) {
tween.elem[tween.prop] = tween.now;
}
}
};
jQuery.easing = {
linear: function linear(p) {
return p;
},
swing: function swing(p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var fxNow,
inProgress,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function schedule() {
if (inProgress) {
if (document.hidden === false && window.requestAnimationFrame) {
window.requestAnimationFrame(schedule);
} else {
window.setTimeout(schedule, jQuery.fx.interval);
}
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout(function () {
fxNow = undefined;
});
return fxNow = jQuery.now();
}
// Generate parameters to create a standard animation
function genFx(type, includeWidth) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for (; i < 4; i += 2 - includeWidth) {
which = cssExpand[i];
attrs["margin" + which] = attrs["padding" + which] = type;
}
if (includeWidth) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween(value, prop, animation) {
var tween,
collection = (Animation.tweeners[prop] || []).concat(Animation.tweeners["*"]),
index = 0,
length = collection.length;
for (; index < length; index++) {
if (tween = collection[index].call(animation, prop, value)) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter(elem, props, opts) {
var prop,
value,
toggle,
hooks,
oldfire,
propTween,
restoreDisplay,
display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree(elem),
dataShow = dataPriv.get(elem, "fxshow");
// Queue-skipping animations hijack the fx hooks
if (!opts.queue) {
hooks = jQuery._queueHooks(elem, "fx");
if (hooks.unqueued == null) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function () {
if (!hooks.unqueued) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function () {
// Ensure the complete handler is called before this completes
anim.always(function () {
hooks.unqueued--;
if (!jQuery.queue(elem, "fx").length) {
hooks.empty.fire();
}
});
});
}
// Detect show/hide animations
for (prop in props) {
value = props[prop];
if (rfxtypes.test(value)) {
delete props[prop];
toggle = toggle || value === "toggle";
if (value === (hidden ? "hide" : "show")) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if (value === "show" && dataShow && dataShow[prop] !== undefined) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject(props);
if (!propTween && jQuery.isEmptyObject(orig)) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if (isBox && elem.nodeType === 1) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [style.overflow, style.overflowX, style.overflowY];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if (restoreDisplay == null) {
restoreDisplay = dataPriv.get(elem, "display");
}
display = jQuery.css(elem, "display");
if (display === "none") {
if (restoreDisplay) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide([elem], true);
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css(elem, "display");
showHide([elem]);
}
}
// Animate inline elements as inline-block
if (display === "inline" || display === "inline-block" && restoreDisplay != null) {
if (jQuery.css(elem, "float") === "none") {
// Restore the original display value at the end of pure show/hide animations
if (!propTween) {
anim.done(function () {
style.display = restoreDisplay;
});
if (restoreDisplay == null) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if (opts.overflow) {
style.overflow = "hidden";
anim.always(function () {
style.overflow = opts.overflow[0];
style.overflowX = opts.overflow[1];
style.overflowY = opts.overflow[2];
});
}
// Implement show/hide animations
propTween = false;
for (prop in orig) {
// General show/hide setup for this element animation
if (!propTween) {
if (dataShow) {
if ("hidden" in dataShow) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access(elem, "fxshow", { display: restoreDisplay });
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if (toggle) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if (hidden) {
showHide([elem], true);
}
/* eslint-disable no-loop-func */
anim.done(function () {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if (!hidden) {
showHide([elem]);
}
dataPriv.remove(elem, "fxshow");
for (prop in orig) {
jQuery.style(elem, prop, orig[prop]);
}
});
}
// Per-property setup
propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim);
if (!(prop in dataShow)) {
dataShow[prop] = propTween.start;
if (hidden) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
function propFilter(props, specialEasing) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for (index in props) {
name = jQuery.camelCase(index);
easing = specialEasing[name];
value = props[index];
if (Array.isArray(value)) {
easing = value[1];
value = props[index] = value[0];
}
if (index !== name) {
props[name] = value;
delete props[index];
}
hooks = jQuery.cssHooks[name];
if (hooks && "expand" in hooks) {
value = hooks.expand(value);
delete props[name];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for (index in value) {
if (!(index in props)) {
props[index] = value[index];
specialEasing[index] = easing;
}
}
} else {
specialEasing[name] = easing;
}
}
}
function Animation(elem, properties, options) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always(function () {
// Don't match elem in the :animated selector
delete tick.elem;
}),
tick = function tick() {
if (stopped) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
// Support: Android 2.3 only
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for (; index < length; index++) {
animation.tweens[index].run(percent);
}
deferred.notifyWith(elem, [animation, percent, remaining]);
// If there's more to do, yield
if (percent < 1 && length) {
return remaining;
}
// If this was an empty animation, synthesize a final progress notification
if (!length) {
deferred.notifyWith(elem, [animation, 1, 0]);
}
// Resolve the animation and report its conclusion
deferred.resolveWith(elem, [animation]);
return false;
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend({}, properties),
opts: jQuery.extend(true, {
specialEasing: {},
easing: jQuery.easing._default
}, options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function createTween(prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing);
animation.tweens.push(tween);
return tween;
},
stop: function stop(gotoEnd) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) {
return this;
}
stopped = true;
for (; index < length; index++) {
animation.tweens[index].run(1);
}
// Resolve when we played the last frame; otherwise, reject
if (gotoEnd) {
deferred.notifyWith(elem, [animation, 1, 0]);
deferred.resolveWith(elem, [animation, gotoEnd]);
} else {
deferred.rejectWith(elem, [animation, gotoEnd]);
}
return this;
}
}),
props = animation.props;
propFilter(props, animation.opts.specialEasing);
for (; index < length; index++) {
result = Animation.prefilters[index].call(animation, elem, props, animation.opts);
if (result) {
if (jQuery.isFunction(result.stop)) {
jQuery._queueHooks(animation.elem, animation.opts.queue).stop = jQuery.proxy(result.stop, result);
}
return result;
}
}
jQuery.map(props, createTween, animation);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
// Attach callbacks from options
animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);
jQuery.fx.timer(jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
}));
return animation;
}
jQuery.Animation = jQuery.extend(Animation, {
tweeners: {
"*": [function (prop, value) {
var tween = this.createTween(prop, value);
adjustCSS(tween.elem, prop, rcssNum.exec(value), tween);
return tween;
}]
},
tweener: function tweener(props, callback) {
if (jQuery.isFunction(props)) {
callback = props;
props = ["*"];
} else {
props = props.match(rnothtmlwhite);
}
var prop,
index = 0,
length = props.length;
for (; index < length; index++) {
prop = props[index];
Animation.tweeners[prop] = Animation.tweeners[prop] || [];
Animation.tweeners[prop].unshift(callback);
}
},
prefilters: [defaultPrefilter],
prefilter: function prefilter(callback, prepend) {
if (prepend) {
Animation.prefilters.unshift(callback);
} else {
Animation.prefilters.push(callback);
}
}
});
jQuery.speed = function (speed, easing, fn) {
var opt = speed && (typeof speed === "undefined" ? "undefined" : _typeof(speed)) === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing || jQuery.isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
// Go to the end state if fx are off
if (jQuery.fx.off) {
opt.duration = 0;
} else {
if (typeof opt.duration !== "number") {
if (opt.duration in jQuery.fx.speeds) {
opt.duration = jQuery.fx.speeds[opt.duration];
} else {
opt.duration = jQuery.fx.speeds._default;
}
}
}
// Normalize opt.queue - true/undefined/null -> "fx"
if (opt.queue == null || opt.queue === true) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function () {
if (jQuery.isFunction(opt.old)) {
opt.old.call(this);
}
if (opt.queue) {
jQuery.dequeue(this, opt.queue);
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function fadeTo(speed, to, easing, callback) {
// Show any hidden elements after setting opacity to 0
return this.filter(isHiddenWithinTree).css("opacity", 0).show()
// Animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback);
},
animate: function animate(prop, speed, easing, callback) {
var empty = jQuery.isEmptyObject(prop),
optall = jQuery.speed(speed, easing, callback),
doAnimation = function doAnimation() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({}, prop), optall);
// Empty animations, or finishing resolves immediately
if (empty || dataPriv.get(this, "finish")) {
anim.stop(true);
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
},
stop: function stop(type, clearQueue, gotoEnd) {
var stopQueue = function stopQueue(hooks) {
var stop = hooks.stop;
delete hooks.stop;
stop(gotoEnd);
};
if (typeof type !== "string") {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if (clearQueue && type !== false) {
this.queue(type || "fx", []);
}
return this.each(function () {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get(this);
if (index) {
if (data[index] && data[index].stop) {
stopQueue(data[index]);
}
} else {
for (index in data) {
if (data[index] && data[index].stop && rrun.test(index)) {
stopQueue(data[index]);
}
}
}
for (index = timers.length; index--;) {
if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
timers[index].anim.stop(gotoEnd);
dequeue = false;
timers.splice(index, 1);
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if (dequeue || !gotoEnd) {
jQuery.dequeue(this, type);
}
});
},
finish: function finish(type) {
if (type !== false) {
type = type || "fx";
}
return this.each(function () {
var index,
data = dataPriv.get(this),
queue = data[type + "queue"],
hooks = data[type + "queueHooks"],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue(this, type, []);
if (hooks && hooks.stop) {
hooks.stop.call(this, true);
}
// Look for any active animations, and finish them
for (index = timers.length; index--;) {
if (timers[index].elem === this && timers[index].queue === type) {
timers[index].anim.stop(true);
timers.splice(index, 1);
}
}
// Look for any animations in the old queue and finish them
for (index = 0; index < length; index++) {
if (queue[index] && queue[index].finish) {
queue[index].finish.call(this);
}
}
// Turn off finishing flag
delete data.finish;
});
}
});
jQuery.each(["toggle", "show", "hide"], function (i, name) {
var cssFn = jQuery.fn[name];
jQuery.fn[name] = function (speed, easing, callback) {
return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback);
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function (name, props) {
jQuery.fn[name] = function (speed, easing, callback) {
return this.animate(props, speed, easing, callback);
};
});
jQuery.timers = [];
jQuery.fx.tick = function () {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for (; i < timers.length; i++) {
timer = timers[i];
// Run the timer and safely remove it when done (allowing for external removal)
if (!timer() && timers[i] === timer) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function (timer) {
jQuery.timers.push(timer);
jQuery.fx.start();
};
jQuery.fx.interval = 13;
jQuery.fx.start = function () {
if (inProgress) {
return;
}
inProgress = true;
schedule();
};
jQuery.fx.stop = function () {
inProgress = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function (time, type) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue(type, function (next, hooks) {
var timeout = window.setTimeout(next, time);
hooks.stop = function () {
window.clearTimeout(timeout);
};
});
};
(function () {
var input = document.createElement("input"),
select = document.createElement("select"),
opt = select.appendChild(document.createElement("option"));
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement("input");
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function attr(name, value) {
return access(this, jQuery.attr, name, value, arguments.length > 1);
},
removeAttr: function removeAttr(name) {
return this.each(function () {
jQuery.removeAttr(this, name);
});
}
});
jQuery.extend({
attr: function attr(elem, name, value) {
var ret,
hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if (nType === 3 || nType === 8 || nType === 2) {
return;
}
// Fallback to prop when attributes are not supported
if (typeof elem.getAttribute === "undefined") {
return jQuery.prop(elem, name, value);
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
hooks = jQuery.attrHooks[name.toLowerCase()] || (jQuery.expr.match.bool.test(name) ? boolHook : undefined);
}
if (value !== undefined) {
if (value === null) {
jQuery.removeAttr(elem, name);
return;
}
if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
}
elem.setAttribute(name, value + "");
return value;
}
if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
}
ret = jQuery.find.attr(elem, name);
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function set(elem, value) {
if (!support.radioValue && value === "radio" && nodeName(elem, "input")) {
var val = elem.value;
elem.setAttribute("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function removeAttr(elem, value) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match(rnothtmlwhite);
if (attrNames && elem.nodeType === 1) {
while (name = attrNames[i++]) {
elem.removeAttribute(name);
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function set(elem, value, name) {
if (value === false) {
// Remove boolean attributes when set to false
jQuery.removeAttr(elem, name);
} else {
elem.setAttribute(name, name);
}
return name;
}
};
jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function (i, name) {
var getter = attrHandle[name] || jQuery.find.attr;
attrHandle[name] = function (elem, name, isXML) {
var ret,
handle,
lowercaseName = name.toLowerCase();
if (!isXML) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[lowercaseName];
attrHandle[lowercaseName] = ret;
ret = getter(elem, name, isXML) != null ? lowercaseName : null;
attrHandle[lowercaseName] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function prop(name, value) {
return access(this, jQuery.prop, name, value, arguments.length > 1);
},
removeProp: function removeProp(name) {
return this.each(function () {
delete this[jQuery.propFix[name] || name];
});
}
});
jQuery.extend({
prop: function prop(elem, name, value) {
var ret,
hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if (nType === 3 || nType === 8 || nType === 2) {
return;
}
if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
// Fix name and attach hooks
name = jQuery.propFix[name] || name;
hooks = jQuery.propHooks[name];
}
if (value !== undefined) {
if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
}
return elem[name] = value;
}
if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
}
return elem[name];
},
propHooks: {
tabIndex: {
get: function get(elem) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr(elem, "tabindex");
if (tabindex) {
return parseInt(tabindex, 10);
}
if (rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
});
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if (!support.optSelected) {
jQuery.propHooks.selected = {
get: function get(elem) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if (parent && parent.parentNode) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function set(elem) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if (parent) {
parent.selectedIndex;
if (parent.parentNode) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () {
jQuery.propFix[this.toLowerCase()] = this;
});
// Strip and collapse whitespace according to HTML spec
// https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace
function stripAndCollapse(value) {
var tokens = value.match(rnothtmlwhite) || [];
return tokens.join(" ");
}
function getClass(elem) {
return elem.getAttribute && elem.getAttribute("class") || "";
}
jQuery.fn.extend({
addClass: function addClass(value) {
var classes,
elem,
cur,
curValue,
clazz,
j,
finalValue,
i = 0;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, getClass(this)));
});
}
if (typeof value === "string" && value) {
classes = value.match(rnothtmlwhite) || [];
while (elem = this[i++]) {
curValue = getClass(elem);
cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
if (cur) {
j = 0;
while (clazz = classes[j++]) {
if (cur.indexOf(" " + clazz + " ") < 0) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue) {
elem.setAttribute("class", finalValue);
}
}
}
}
return this;
},
removeClass: function removeClass(value) {
var classes,
elem,
cur,
curValue,
clazz,
j,
finalValue,
i = 0;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).removeClass(value.call(this, j, getClass(this)));
});
}
if (!arguments.length) {
return this.attr("class", "");
}
if (typeof value === "string" && value) {
classes = value.match(rnothtmlwhite) || [];
while (elem = this[i++]) {
curValue = getClass(elem);
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
if (cur) {
j = 0;
while (clazz = classes[j++]) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") > -1) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue) {
elem.setAttribute("class", finalValue);
}
}
}
}
return this;
},
toggleClass: function toggleClass(value, stateVal) {
var type = typeof value === "undefined" ? "undefined" : _typeof(value);
if (typeof stateVal === "boolean" && type === "string") {
return stateVal ? this.addClass(value) : this.removeClass(value);
}
if (jQuery.isFunction(value)) {
return this.each(function (i) {
jQuery(this).toggleClass(value.call(this, i, getClass(this), stateVal), stateVal);
});
}
return this.each(function () {
var className, i, self, classNames;
if (type === "string") {
// Toggle individual class names
i = 0;
self = jQuery(this);
classNames = value.match(rnothtmlwhite) || [];
while (className = classNames[i++]) {
// Check each className given, space separated list
if (self.hasClass(className)) {
self.removeClass(className);
} else {
self.addClass(className);
}
}
// Toggle whole class name
} else if (value === undefined || type === "boolean") {
className = getClass(this);
if (className) {
// Store className if set
dataPriv.set(this, "__className__", className);
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if (this.setAttribute) {
this.setAttribute("class", className || value === false ? "" : dataPriv.get(this, "__className__") || "");
}
}
});
},
hasClass: function hasClass(selector) {
var className,
elem,
i = 0;
className = " " + selector + " ";
while (elem = this[i++]) {
if (elem.nodeType === 1 && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function val(value) {
var hooks,
ret,
isFunction,
elem = this[0];
if (!arguments.length) {
if (elem) {
hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()];
if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if (typeof ret === "string") {
return ret.replace(rreturn, "");
}
// Handle cases where value is null/undef or number
return ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction(value);
return this.each(function (i) {
var val;
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, jQuery(this).val());
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if (val == null) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (Array.isArray(val)) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];
// If set returns undefined, fall back to normal setting
if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function get(elem) {
var val = jQuery.find.attr(elem, "value");
return val != null ? val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse(jQuery.text(elem));
}
},
select: {
get: function get(elem) {
var value,
option,
i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if (index < 0) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for (; i < max; i++) {
option = options[i];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ((option.selected || i === index) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if (one) {
return value;
}
// Multi-Selects return an array
values.push(value);
}
}
return values;
},
set: function set(elem, value) {
var optionSet,
option,
options = elem.options,
values = jQuery.makeArray(value),
i = options.length;
while (i--) {
option = options[i];
/* eslint-disable no-cond-assign */
if (option.selected = jQuery.inArray(jQuery.valHooks.option.get(option), values) > -1) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if (!optionSet) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each(["radio", "checkbox"], function () {
jQuery.valHooks[this] = {
set: function set(elem, value) {
if (Array.isArray(value)) {
return elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1;
}
}
};
if (!support.checkOn) {
jQuery.valHooks[this].get = function (elem) {
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend(jQuery.event, {
trigger: function trigger(event, data, elem, onlyHandlers) {
var i,
cur,
tmp,
bubbleType,
ontype,
handle,
special,
eventPath = [elem || document],
type = hasOwn.call(event, "type") ? event.type : event,
namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if (elem.nodeType === 3 || elem.nodeType === 8) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if (rfocusMorph.test(type + jQuery.event.triggered)) {
return;
}
if (type.indexOf(".") > -1) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[jQuery.expando] ? event : new jQuery.Event(type, (typeof event === "undefined" ? "undefined" : _typeof(event)) === "object" && event);
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.rnamespace = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Clean up the event in case it is being reused
event.result = undefined;
if (!event.target) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ? [event] : jQuery.makeArray(data, [event]);
// Allow special events to draw outside the lines
special = jQuery.event.special[type] || {};
if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
bubbleType = special.delegateType || type;
if (!rfocusMorph.test(bubbleType + type)) {
cur = cur.parentNode;
}
for (; cur; cur = cur.parentNode) {
eventPath.push(cur);
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if (tmp === (elem.ownerDocument || document)) {
eventPath.push(tmp.defaultView || tmp.parentWindow || window);
}
}
// Fire handlers on the event path
i = 0;
while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
event.type = i > 1 ? bubbleType : special.bindType || type;
// jQuery handler
handle = (dataPriv.get(cur, "events") || {})[event.type] && dataPriv.get(cur, "handle");
if (handle) {
handle.apply(cur, data);
}
// Native handler
handle = ontype && cur[ontype];
if (handle && handle.apply && acceptData(cur)) {
event.result = handle.apply(cur, data);
if (event.result === false) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if (!onlyHandlers && !event.isDefaultPrevented()) {
if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && acceptData(elem)) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if (ontype && jQuery.isFunction(elem[type]) && !jQuery.isWindow(elem)) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ontype];
if (tmp) {
elem[ontype] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[type]();
jQuery.event.triggered = undefined;
if (tmp) {
elem[ontype] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function simulate(type, elem, event) {
var e = jQuery.extend(new jQuery.Event(), event, {
type: type,
isSimulated: true
});
jQuery.event.trigger(e, null, elem);
}
});
jQuery.fn.extend({
trigger: function trigger(type, data) {
return this.each(function () {
jQuery.event.trigger(type, data, this);
});
},
triggerHandler: function triggerHandler(type, data) {
var elem = this[0];
if (elem) {
return jQuery.event.trigger(type, data, elem, true);
}
}
});
jQuery.each(("blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu").split(" "), function (i, name) {
// Handle event binding
jQuery.fn[name] = function (data, fn) {
return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
};
});
jQuery.fn.extend({
hover: function hover(fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
}
});
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if (!support.focusin) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function handler(event) {
jQuery.event.simulate(fix, event.target, jQuery.event.fix(event));
};
jQuery.event.special[fix] = {
setup: function setup() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access(doc, fix);
if (!attaches) {
doc.addEventListener(orig, handler, true);
}
dataPriv.access(doc, fix, (attaches || 0) + 1);
},
teardown: function teardown() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access(doc, fix) - 1;
if (!attaches) {
doc.removeEventListener(orig, handler, true);
dataPriv.remove(doc, fix);
} else {
dataPriv.access(doc, fix, attaches);
}
}
};
});
}
var location = window.location;
var nonce = jQuery.now();
var rquery = /\?/;
// Cross-browser xml parsing
jQuery.parseXML = function (data) {
var xml;
if (!data || typeof data !== "string") {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = new window.DOMParser().parseFromString(data, "text/xml");
} catch (e) {
xml = undefined;
}
if (!xml || xml.getElementsByTagName("parsererror").length) {
jQuery.error("Invalid XML: " + data);
}
return xml;
};
var rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams(prefix, obj, traditional, add) {
var name;
if (Array.isArray(obj)) {
// Serialize array item.
jQuery.each(obj, function (i, v) {
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, v);
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + ((typeof v === "undefined" ? "undefined" : _typeof(v)) === "object" && v != null ? i : "") + "]", v, traditional, add);
}
});
} else if (!traditional && jQuery.type(obj) === "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function (a, traditional) {
var prefix,
s = [],
add = function add(key, valueOrFunction) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction;
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
};
// If an array was passed in, assume that it is an array of form elements.
if (Array.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) {
// Serialize the form elements
jQuery.each(a, function () {
add(this.name, this.value);
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in a) {
buildParams(prefix, a[prefix], traditional, add);
}
}
// Return the resulting serialization
return s.join("&");
};
jQuery.fn.extend({
serialize: function serialize() {
return jQuery.param(this.serializeArray());
},
serializeArray: function serializeArray() {
return this.map(function () {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
}).filter(function () {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
}).map(function (i, elem) {
var val = jQuery(this).val();
if (val == null) {
return null;
}
if (Array.isArray(val)) {
return jQuery.map(val, function (val) {
return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
});
}
return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
}).get();
}
});
var r20 = /%20/g,
rhash = /#.*$/,
rantiCache = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*"),
// Anchor tag for parsing the document origin
originAnchor = document.createElement("a");
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports(structure) {
// dataTypeExpression is optional and defaults to "*"
return function (dataTypeExpression, func) {
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || [];
if (jQuery.isFunction(func)) {
// For each dataType in the dataTypeExpression
while (dataType = dataTypes[i++]) {
// Prepend if requested
if (dataType[0] === "+") {
dataType = dataType.slice(1) || "*";
(structure[dataType] = structure[dataType] || []).unshift(func);
// Otherwise append
} else {
(structure[dataType] = structure[dataType] || []).push(func);
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
var inspected = {},
seekingTransport = structure === transports;
function inspect(dataType) {
var selected;
inspected[dataType] = true;
jQuery.each(structure[dataType] || [], function (_, prefilterOrFactory) {
var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {
options.dataTypes.unshift(dataTypeOrTransport);
inspect(dataTypeOrTransport);
return false;
} else if (seekingTransport) {
return !(selected = dataTypeOrTransport);
}
});
return selected;
}
return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target, src) {
var key,
deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for (key in src) {
if (src[key] !== undefined) {
(flatOptions[key] ? target : deep || (deep = {}))[key] = src[key];
}
}
if (deep) {
jQuery.extend(true, target, deep);
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses(s, jqXHR, responses) {
var ct,
type,
finalDataType,
firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while (dataTypes[0] === "*") {
dataTypes.shift();
if (ct === undefined) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if (ct) {
for (type in contents) {
if (contents[type] && contents[type].test(ct)) {
dataTypes.unshift(type);
break;
}
}
}
// Check to see if we have a response for the expected dataType
if (dataTypes[0] in responses) {
finalDataType = dataTypes[0];
} else {
// Try convertible dataTypes
for (type in responses) {
if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
finalDataType = type;
break;
}
if (!firstDataType) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if (finalDataType) {
if (finalDataType !== dataTypes[0]) {
dataTypes.unshift(finalDataType);
}
return responses[finalDataType];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert(s, response, jqXHR, isSuccess) {
var conv2,
current,
conv,
tmp,
prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if (dataTypes[1]) {
for (conv in s.converters) {
converters[conv.toLowerCase()] = s.converters[conv];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while (current) {
if (s.responseFields[current]) {
jqXHR[s.responseFields[current]] = response;
}
// Apply the dataFilter if provided
if (!prev && isSuccess && s.dataFilter) {
response = s.dataFilter(response, s.dataType);
}
prev = current;
current = dataTypes.shift();
if (current) {
// There's only work to do if current dataType is non-auto
if (current === "*") {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if (prev !== "*" && prev !== current) {
// Seek a direct converter
conv = converters[prev + " " + current] || converters["* " + current];
// If none found, seek a pair
if (!conv) {
for (conv2 in converters) {
// If conv2 outputs current
tmp = conv2.split(" ");
if (tmp[1] === current) {
// If prev can be converted to accepted input
conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
if (conv) {
// Condense equivalence converters
if (conv === true) {
conv = converters[conv2];
// Otherwise, insert the intermediate dataType
} else if (converters[conv2] !== true) {
current = tmp[0];
dataTypes.unshift(tmp[1]);
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if (conv !== true) {
// Unless errors are allowed to bubble, catch and return them
if (conv && s.throws) {
response = conv(response);
} else {
try {
response = conv(response);
} catch (e) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test(location.protocol),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function ajaxSetup(target, settings) {
return settings ?
// Building a settings object
ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
// Extending ajaxSettings
ajaxExtend(jQuery.ajaxSettings, target);
},
ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
ajaxTransport: addToPrefiltersOrTransports(transports),
// Main method
ajax: function ajax(url, options) {
// If url is an object, simulate pre-1.5 signature
if ((typeof url === "undefined" ? "undefined" : _typeof(url)) === "object") {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// Create the final options object
s = jQuery.ajaxSetup({}, options),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
_statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function getResponseHeader(key) {
var match;
if (completed) {
if (!responseHeaders) {
responseHeaders = {};
while (match = rheaders.exec(responseHeadersString)) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
}
match = responseHeaders[key.toLowerCase()];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function getAllResponseHeaders() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function setRequestHeader(name, value) {
if (completed == null) {
name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name;
requestHeaders[name] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function overrideMimeType(type) {
if (completed == null) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function statusCode(map) {
var code;
if (map) {
if (completed) {
// Execute the appropriate callbacks
jqXHR.always(map[jqXHR.status]);
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for (code in map) {
_statusCode[code] = [_statusCode[code], map[code]];
}
}
}
return this;
},
// Cancel the request
abort: function abort(statusText) {
var finalText = statusText || strAbort;
if (transport) {
transport.abort(finalText);
}
done(0, finalText);
return this;
}
};
// Attach deferreds
deferred.promise(jqXHR);
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ((url || s.url || location.href) + "").replace(rprotocol, location.protocol + "//");
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""];
// A cross-domain request is in order when the origin doesn't match the current origin.
if (s.crossDomain == null) {
urlAnchor = document.createElement("a");
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host;
} catch (e) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
s.data = jQuery.param(s.data, s.traditional);
}
// Apply prefilters
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
// If request was aborted inside a prefilter, stop there
if (completed) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if (fireGlobals && jQuery.active++ === 0) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test(s.type);
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace(rhash, "");
// More options handling for requests with no content
if (!s.hasContent) {
// Remember the hash so we can put it back
uncached = s.url.slice(cacheURL.length);
// If data is available, append data to url
if (s.data) {
cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add or update anti-cache param if needed
if (s.cache === false) {
cacheURL = cacheURL.replace(rantiCache, "$1");
uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce++ + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if (s.data && s.processData && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0) {
s.data = s.data.replace(r20, "+");
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
if (jQuery.lastModified[cacheURL]) {
jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
}
if (jQuery.etag[cacheURL]) {
jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
}
}
// Set the correct header, if data is being sent
if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
jqXHR.setRequestHeader("Content-Type", s.contentType);
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]);
// Check for headers option
for (i in s.headers) {
jqXHR.setRequestHeader(i, s.headers[i]);
}
// Allow custom headers/mimetypes and early abort
if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || completed)) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add(s.complete);
jqXHR.done(s.success);
jqXHR.fail(s.error);
// Get transport
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
// If no transport, we auto-abort
if (!transport) {
done(-1, "No Transport");
} else {
jqXHR.readyState = 1;
// Send global event
if (fireGlobals) {
globalEventContext.trigger("ajaxSend", [jqXHR, s]);
}
// If request was aborted inside ajaxSend, stop there
if (completed) {
return jqXHR;
}
// Timeout
if (s.async && s.timeout > 0) {
timeoutTimer = window.setTimeout(function () {
jqXHR.abort("timeout");
}, s.timeout);
}
try {
completed = false;
transport.send(requestHeaders, done);
} catch (e) {
// Rethrow post-completion exceptions
if (completed) {
throw e;
}
// Propagate others as results
done(-1, e);
}
}
// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {
var isSuccess,
success,
error,
response,
modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if (completed) {
return;
}
completed = true;
// Clear timeout if it exists
if (timeoutTimer) {
window.clearTimeout(timeoutTimer);
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if (responses) {
response = ajaxHandleResponses(s, jqXHR, responses);
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert(s, response, jqXHR, isSuccess);
// If successful, handle type chaining
if (isSuccess) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
modified = jqXHR.getResponseHeader("Last-Modified");
if (modified) {
jQuery.lastModified[cacheURL] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if (modified) {
jQuery.etag[cacheURL] = modified;
}
}
// if no content
if (status === 204 || s.type === "HEAD") {
statusText = "nocontent";
// if not modified
} else if (status === 304) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if (status || !statusText) {
statusText = "error";
if (status < 0) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = (nativeStatusText || statusText) + "";
// Success/Error
if (isSuccess) {
deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
} else {
deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
}
// Status-dependent callbacks
jqXHR.statusCode(_statusCode);
_statusCode = undefined;
if (fireGlobals) {
globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error]);
}
// Complete
completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
if (fireGlobals) {
globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
// Handle the global AJAX counter
if (! --jQuery.active) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function getJSON(url, data, callback) {
return jQuery.get(url, data, callback, "json");
},
getScript: function getScript(url, callback) {
return jQuery.get(url, undefined, callback, "script");
}
});
jQuery.each(["get", "post"], function (i, method) {
jQuery[method] = function (url, data, callback, type) {
// Shift arguments if data argument was omitted
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax(jQuery.extend({
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject(url) && url));
};
});
jQuery._evalUrl = function (url) {
return jQuery.ajax({
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function wrapAll(html) {
var wrap;
if (this[0]) {
if (jQuery.isFunction(html)) {
html = html.call(this[0]);
}
// The elements to wrap the target around
wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
if (this[0].parentNode) {
wrap.insertBefore(this[0]);
}
wrap.map(function () {
var elem = this;
while (elem.firstElementChild) {
elem = elem.firstElementChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function wrapInner(html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapInner(html.call(this, i));
});
}
return this.each(function () {
var self = jQuery(this),
contents = self.contents();
if (contents.length) {
contents.wrapAll(html);
} else {
self.append(html);
}
});
},
wrap: function wrap(html) {
var isFunction = jQuery.isFunction(html);
return this.each(function (i) {
jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
});
},
unwrap: function unwrap(selector) {
this.parent(selector).not("body").each(function () {
jQuery(this).replaceWith(this.childNodes);
});
return this;
}
});
jQuery.expr.pseudos.hidden = function (elem) {
return !jQuery.expr.pseudos.visible(elem);
};
jQuery.expr.pseudos.visible = function (elem) {
return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
};
jQuery.ajaxSettings.xhr = function () {
try {
return new window.XMLHttpRequest();
} catch (e) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && "withCredentials" in xhrSupported;
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function (options) {
var _callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if (support.cors || xhrSupported && !options.crossDomain) {
return {
send: function send(headers, complete) {
var i,
xhr = options.xhr();
xhr.open(options.type, options.url, options.async, options.username, options.password);
// Apply custom fields if provided
if (options.xhrFields) {
for (i in options.xhrFields) {
xhr[i] = options.xhrFields[i];
}
}
// Override mime type if needed
if (options.mimeType && xhr.overrideMimeType) {
xhr.overrideMimeType(options.mimeType);
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if (!options.crossDomain && !headers["X-Requested-With"]) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for (i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
// Callback
_callback = function callback(type) {
return function () {
if (_callback) {
_callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if (type === "abort") {
xhr.abort();
} else if (type === "error") {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if (typeof xhr.status !== "number") {
complete(0, "error");
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status, xhr.statusText);
}
} else {
complete(xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
(xhr.responseType || "text") !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders());
}
}
};
};
// Listen to events
xhr.onload = _callback();
errorCallback = xhr.onerror = _callback("error");
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if (xhr.onabort !== undefined) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function () {
// Check readyState before timeout as it changes
if (xhr.readyState === 4) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout(function () {
if (_callback) {
errorCallback();
}
});
}
};
}
// Create the abort callback
_callback = _callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send(options.hasContent && options.data || null);
} catch (e) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if (_callback) {
throw e;
}
}
},
abort: function abort() {
if (_callback) {
_callback();
}
}
};
}
});
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter(function (s) {
if (s.crossDomain) {
s.contents.script = false;
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function textScript(text) {
jQuery.globalEval(text);
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter("script", function (s) {
if (s.cache === undefined) {
s.cache = false;
}
if (s.crossDomain) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport("script", function (s) {
// This transport only deals with cross domain requests
if (s.crossDomain) {
var script, _callback2;
return {
send: function send(_, complete) {
script = jQuery("<script>").prop({
charset: s.scriptCharset,
src: s.url
}).on("load error", _callback2 = function callback(evt) {
script.remove();
_callback2 = null;
if (evt) {
complete(evt.type === "error" ? 404 : 200, evt.type);
}
});
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild(script[0]);
},
abort: function abort() {
if (_callback2) {
_callback2();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function jsonpCallback() {
var callback = oldCallbacks.pop() || jQuery.expando + "_" + nonce++;
this[callback] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
var callbackName,
overwritten,
responseContainer,
jsonProp = s.jsonp !== false && (rjsonp.test(s.url) ? "url" : typeof s.data === "string" && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0 && rjsonp.test(s.data) && "data");
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if (jsonProp || s.dataTypes[0] === "jsonp") {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback;
// Insert callback into url or form data
if (jsonProp) {
s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName);
} else if (s.jsonp !== false) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function () {
if (!responseContainer) {
jQuery.error(callbackName + " was not called");
}
return responseContainer[0];
};
// Force json dataType
s.dataTypes[0] = "json";
// Install callback
overwritten = window[callbackName];
window[callbackName] = function () {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function () {
// If previous value didn't exist - remove it
if (overwritten === undefined) {
jQuery(window).removeProp(callbackName);
// Otherwise restore preexisting value
} else {
window[callbackName] = overwritten;
}
// Save back as free
if (s[callbackName]) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push(callbackName);
}
// Call if it was a function and we have a response
if (responseContainer && jQuery.isFunction(overwritten)) {
overwritten(responseContainer[0]);
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = function () {
var body = document.implementation.createHTMLDocument("").body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
}();
// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function (data, context, keepScripts) {
if (typeof data !== "string") {
return [];
}
if (typeof context === "boolean") {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if (!context) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if (support.createHTMLDocument) {
context = document.implementation.createHTMLDocument("");
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement("base");
base.href = document.location.href;
context.head.appendChild(base);
} else {
context = document;
}
}
parsed = rsingleTag.exec(data);
scripts = !keepScripts && [];
// Single tag
if (parsed) {
return [context.createElement(parsed[1])];
}
parsed = buildFragment([data], context, scripts);
if (scripts && scripts.length) {
jQuery(scripts).remove();
}
return jQuery.merge([], parsed.childNodes);
};
/**
* Load a url into a page
*/
jQuery.fn.load = function (url, params, callback) {
var selector,
type,
response,
self = this,
off = url.indexOf(" ");
if (off > -1) {
selector = stripAndCollapse(url.slice(off));
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && (typeof params === "undefined" ? "undefined" : _typeof(params)) === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
}).done(function (responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
}).always(callback && function (jqXHR, status) {
self.each(function () {
callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
});
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (i, type) {
jQuery.fn[type] = function (fn) {
return this.on(type, fn);
};
});
jQuery.expr.pseudos.animated = function (elem) {
return jQuery.grep(jQuery.timers, function (fn) {
return elem === fn.elem;
}).length;
};
jQuery.offset = {
setOffset: function setOffset(elem, options, i) {
var curPosition,
curLeft,
curCSSTop,
curTop,
curOffset,
curCSSLeft,
calculatePosition,
position = jQuery.css(elem, "position"),
curElem = jQuery(elem),
props = {};
// Set position first, in-case top/left are set even on static elem
if (position === "static") {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css(elem, "top");
curCSSLeft = jQuery.css(elem, "left");
calculatePosition = (position === "absolute" || position === "fixed") && (curCSSTop + curCSSLeft).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if (calculatePosition) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat(curCSSTop) || 0;
curLeft = parseFloat(curCSSLeft) || 0;
}
if (jQuery.isFunction(options)) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call(elem, i, jQuery.extend({}, curOffset));
}
if (options.top != null) {
props.top = options.top - curOffset.top + curTop;
}
if (options.left != null) {
props.left = options.left - curOffset.left + curLeft;
}
if ("using" in options) {
options.using.call(elem, props);
} else {
curElem.css(props);
}
}
};
jQuery.fn.extend({
offset: function offset(options) {
// Preserve chaining for setter
if (arguments.length) {
return options === undefined ? this : this.each(function (i) {
jQuery.offset.setOffset(this, options, i);
});
}
var doc,
docElem,
rect,
win,
elem = this[0];
if (!elem) {
return;
}
// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if (!elem.getClientRects().length) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
doc = elem.ownerDocument;
docElem = doc.documentElement;
win = doc.defaultView;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
},
position: function position() {
if (!this[0]) {
return;
}
var offsetParent,
offset,
elem = this[0],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if (jQuery.css(elem, "position") === "fixed") {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if (!nodeName(offsetParent[0], "html")) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset = {
top: parentOffset.top + jQuery.css(offsetParent[0], "borderTopWidth", true),
left: parentOffset.left + jQuery.css(offsetParent[0], "borderLeftWidth", true)
};
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function offsetParent() {
return this.map(function () {
var offsetParent = this.offsetParent;
while (offsetParent && jQuery.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (method, prop) {
var top = "pageYOffset" === prop;
jQuery.fn[method] = function (val) {
return access(this, function (elem, method, val) {
// Coalesce documents and windows
var win;
if (jQuery.isWindow(elem)) {
win = elem;
} else if (elem.nodeType === 9) {
win = elem.defaultView;
}
if (val === undefined) {
return win ? win[prop] : elem[method];
}
if (win) {
win.scrollTo(!top ? val : win.pageXOffset, top ? val : win.pageYOffset);
} else {
elem[method] = val;
}
}, method, val, arguments.length);
};
});
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each(["top", "left"], function (i, prop) {
jQuery.cssHooks[prop] = addGetHookIf(support.pixelPosition, function (elem, computed) {
if (computed) {
computed = curCSS(elem, prop);
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test(computed) ? jQuery(elem).position()[prop] + "px" : computed;
}
});
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each({ Height: "height", Width: "width" }, function (name, type) {
jQuery.each({ padding: "inner" + name, content: type, "": "outer" + name }, function (defaultExtra, funcName) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[funcName] = function (margin, value) {
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf("outer") === 0 ? elem["inner" + name] : elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable);
};
});
});
jQuery.fn.extend({
bind: function bind(types, data, fn) {
return this.on(types, null, data, fn);
},
unbind: function unbind(types, fn) {
return this.off(types, null, fn);
},
delegate: function delegate(selector, types, data, fn) {
return this.on(types, selector, data, fn);
},
undelegate: function undelegate(selector, types, fn) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
}
});
jQuery.holdReady = function (hold) {
if (hold) {
jQuery.readyWait++;
} else {
jQuery.ready(true);
}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return jQuery;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function (deep) {
if (window.$ === jQuery) {
window.$ = _$;
}
if (deep && window.jQuery === jQuery) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if (!noGlobal) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)(module)))
/***/ }),
/* 2 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (module) {
if (!module.webpackPolyfill) {
module.deprecate = function () {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(riot) {'use strict';
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; };
/* Riot v3.4.2, @license MIT */
(function (global, factory) {
( false ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? factory(exports) : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : factory(global.riot = global.riot || {});
})(this, function (exports) {
'use strict';
var __TAGS_CACHE = [];
var __TAG_IMPL = {};
var GLOBAL_MIXIN = '__global_mixin';
var ATTRS_PREFIX = 'riot-';
var REF_DIRECTIVES = ['ref', 'data-ref'];
var IS_DIRECTIVE = 'data-is';
var CONDITIONAL_DIRECTIVE = 'if';
var LOOP_DIRECTIVE = 'each';
var LOOP_NO_REORDER_DIRECTIVE = 'no-reorder';
var SHOW_DIRECTIVE = 'show';
var HIDE_DIRECTIVE = 'hide';
var RIOT_EVENTS_KEY = '__riot-events__';
var T_STRING = 'string';
var T_OBJECT = 'object';
var T_UNDEF = 'undefined';
var T_FUNCTION = 'function';
var XLINK_NS = 'http://www.w3.org/1999/xlink';
var XLINK_REGEX = /^xlink:(\w+)/;
var WIN = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === T_UNDEF ? undefined : window;
var RE_SPECIAL_TAGS = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?|opt(?:ion|group))$/;
var RE_SPECIAL_TAGS_NO_OPTION = /^(?:t(?:body|head|foot|[rhd])|caption|col(?:group)?)$/;
var RE_EVENTS_PREFIX = /^on/;
var RE_RESERVED_NAMES = /^(?:_(?:item|id|parent)|update|root|(?:un)?mount|mixin|is(?:Mounted|Loop)|tags|refs|parent|opts|trigger|o(?:n|ff|ne))$/;
var RE_HTML_ATTRS = /([-\w]+) ?= ?(?:"([^"]*)|'([^']*)|({[^}]*}))/g;
var CASE_SENSITIVE_ATTRIBUTES = { 'viewbox': 'viewBox' };
var RE_BOOL_ATTRS = /^(?:disabled|checked|readonly|required|allowfullscreen|auto(?:focus|play)|compact|controls|default|formnovalidate|hidden|ismap|itemscope|loop|multiple|muted|no(?:resize|shade|validate|wrap)?|open|reversed|seamless|selected|sortable|truespeed|typemustmatch)$/;
var IE_VERSION = (WIN && WIN.document || {}).documentMode | 0;
/**
* Check Check if the passed argument is undefined
* @param { String } value -
* @returns { Boolean } -
*/
function isBoolAttr(value) {
return RE_BOOL_ATTRS.test(value);
}
/**
* Check if passed argument is a function
* @param { * } value -
* @returns { Boolean } -
*/
function isFunction(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === T_FUNCTION;
}
/**
* Check if passed argument is an object, exclude null
* NOTE: use isObject(x) && !isArray(x) to excludes arrays.
* @param { * } value -
* @returns { Boolean } -
*/
function isObject(value) {
return value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === T_OBJECT; // typeof null is 'object'
}
/**
* Check if passed argument is undefined
* @param { * } value -
* @returns { Boolean } -
*/
function isUndefined(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === T_UNDEF;
}
/**
* Check if passed argument is a string
* @param { * } value -
* @returns { Boolean } -
*/
function isString(value) {
return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === T_STRING;
}
/**
* Check if passed argument is empty. Different from falsy, because we dont consider 0 or false to be blank
* @param { * } value -
* @returns { Boolean } -
*/
function isBlank(value) {
return isUndefined(value) || value === null || value === '';
}
/**
* Check if passed argument is a kind of array
* @param { * } value -
* @returns { Boolean } -
*/
function isArray(value) {
return Array.isArray(value) || value instanceof Array;
}
/**
* Check whether object's property could be overridden
* @param { Object } obj - source object
* @param { String } key - object property
* @returns { Boolean } -
*/
function isWritable(obj, key) {
var descriptor = Object.getOwnPropertyDescriptor(obj, key);
return isUndefined(obj[key]) || descriptor && descriptor.writable;
}
/**
* Check if passed argument is a reserved name
* @param { String } value -
* @returns { Boolean } -
*/
function isReservedName(value) {
return RE_RESERVED_NAMES.test(value);
}
var check = Object.freeze({
isBoolAttr: isBoolAttr,
isFunction: isFunction,
isObject: isObject,
isUndefined: isUndefined,
isString: isString,
isBlank: isBlank,
isArray: isArray,
isWritable: isWritable,
isReservedName: isReservedName
});
/**
* Shorter and fast way to select multiple nodes in the DOM
* @param { String } selector - DOM selector
* @param { Object } ctx - DOM node where the targets of our search will is located
* @returns { Object } dom nodes found
*/
function $$(selector, ctx) {
return (ctx || document).querySelectorAll(selector);
}
/**
* Shorter and fast way to select a single node in the DOM
* @param { String } selector - unique dom selector
* @param { Object } ctx - DOM node where the target of our search will is located
* @returns { Object } dom node found
*/
function $(selector, ctx) {
return (ctx || document).querySelector(selector);
}
/**
* Create a document fragment
* @returns { Object } document fragment
*/
function createFrag() {
return document.createDocumentFragment();
}
/**
* Create a document text node
* @returns { Object } create a text node to use as placeholder
*/
function createDOMPlaceholder() {
return document.createTextNode('');
}
/**
* Create a generic DOM node
* @param { String } name - name of the DOM node we want to create
* @returns { Object } DOM node just created
*/
function mkEl(name) {
return document.createElement(name);
}
/**
* Set the inner html of any DOM node SVGs included
* @param { Object } container - DOM node where we'll inject new html
* @param { String } html - html to inject
*/
/* istanbul ignore next */
function setInnerHTML(container, html) {
if (!isUndefined(container.innerHTML)) {
container.innerHTML = html;
}
// some browsers do not support innerHTML on the SVGs tags
else {
var doc = new DOMParser().parseFromString(html, 'application/xml');
var node = container.ownerDocument.importNode(doc.documentElement, true);
container.appendChild(node);
}
}
/**
* Toggle the visibility of any DOM node
* @param { Object } dom - DOM node we want to hide
* @param { Boolean } show - do we want to show it?
*/
function toggleVisibility(dom, show) {
dom.style.display = show ? '' : 'none';
dom['hidden'] = show ? false : true;
}
/**
* Remove any DOM attribute from a node
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to remove
*/
function remAttr(dom, name) {
dom.removeAttribute(name);
}
/**
* Convert a style object to a string
* @param { Object } style - style object we need to parse
* @returns { String } resulting css string
* @example
* styleObjectToString({ color: 'red', height: '10px'}) // => 'color: red; height: 10px'
*/
function styleObjectToString(style) {
return Object.keys(style).reduce(function (acc, prop) {
return acc + " " + prop + ": " + style[prop] + ";";
}, '');
}
/**
* Get the value of any DOM attribute on a node
* @param { Object } dom - DOM node we want to parse
* @param { String } name - name of the attribute we want to get
* @returns { String | undefined } name of the node attribute whether it exists
*/
function getAttr(dom, name) {
return dom.getAttribute(name);
}
/**
* Set any DOM attribute
* @param { Object } dom - DOM node we want to update
* @param { String } name - name of the property we want to set
* @param { String } val - value of the property we want to set
*/
function setAttr(dom, name, val) {
var xlink = XLINK_REGEX.exec(name);
if (xlink && xlink[1]) {
dom.setAttributeNS(XLINK_NS, xlink[1], val);
} else {
dom.setAttribute(name, val);
}
}
/**
* Insert safely a tag to fix #1962 #1649
* @param { HTMLElement } root - children container
* @param { HTMLElement } curr - node to insert
* @param { HTMLElement } next - node that should preceed the current node inserted
*/
function safeInsert(root, curr, next) {
root.insertBefore(curr, next.parentNode && next);
}
/**
* Minimize risk: only zero or one _space_ between attr & value
* @param { String } html - html string we want to parse
* @param { Function } fn - callback function to apply on any attribute found
*/
function walkAttrs(html, fn) {
if (!html) {
return;
}
var m;
while (m = RE_HTML_ATTRS.exec(html)) {
fn(m[1].toLowerCase(), m[2] || m[3] || m[4]);
}
}
/**
* Walk down recursively all the children tags starting dom node
* @param { Object } dom - starting node where we will start the recursion
* @param { Function } fn - callback to transform the child node just found
* @param { Object } context - fn can optionally return an object, which is passed to children
*/
function walkNodes(dom, fn, context) {
if (dom) {
var res = fn(dom, context);
var next;
// stop the recursion
if (res === false) {
return;
}
dom = dom.firstChild;
while (dom) {
next = dom.nextSibling;
walkNodes(dom, fn, res);
dom = next;
}
}
}
var dom = Object.freeze({
$$: $$,
$: $,
createFrag: createFrag,
createDOMPlaceholder: createDOMPlaceholder,
mkEl: mkEl,
setInnerHTML: setInnerHTML,
toggleVisibility: toggleVisibility,
remAttr: remAttr,
styleObjectToString: styleObjectToString,
getAttr: getAttr,
setAttr: setAttr,
safeInsert: safeInsert,
walkAttrs: walkAttrs,
walkNodes: walkNodes
});
var styleNode;
var cssTextProp;
var byName = {};
var remainder = [];
var needsInject = false;
// skip the following code on the server
if (WIN) {
styleNode = function () {
// create a new style element with the correct type
var newNode = mkEl('style');
setAttr(newNode, 'type', 'text/css');
// replace any user node or insert the new one into the head
var userNode = $('style[type=riot]');
/* istanbul ignore next */
if (userNode) {
if (userNode.id) {
newNode.id = userNode.id;
}
userNode.parentNode.replaceChild(newNode, userNode);
} else {
document.getElementsByTagName('head')[0].appendChild(newNode);
}
return newNode;
}();
cssTextProp = styleNode.styleSheet;
}
/**
* Object that will be used to inject and manage the css of every tag instance
*/
var styleManager = {
styleNode: styleNode,
/**
* Save a tag style to be later injected into DOM
* @param { String } css - css string
* @param { String } name - if it's passed we will map the css to a tagname
*/
add: function add(css, name) {
if (name) {
byName[name] = css;
} else {
remainder.push(css);
}
needsInject = true;
},
/**
* Inject all previously saved tag styles into DOM
* innerHTML seems slow: http://jsperf.com/riot-insert-style
*/
inject: function inject() {
if (!WIN || !needsInject) {
return;
}
needsInject = false;
var style = Object.keys(byName).map(function (k) {
return byName[k];
}).concat(remainder).join('\n');
/* istanbul ignore next */
if (cssTextProp) {
cssTextProp.cssText = style;
} else {
styleNode.innerHTML = style;
}
}
};
/**
* The riot template engine
* @version v3.0.3
*/
/**
* riot.util.brackets
*
* - `brackets ` - Returns a string or regex based on its parameter
* - `brackets.set` - Change the current riot brackets
*
* @module
*/
/* global riot */
/* istanbul ignore next */
var brackets = function (UNDEF) {
var REGLOB = 'g',
R_MLCOMMS = /\/\*[^*]*\*+(?:[^*\/][^*]*\*+)*\//g,
R_STRINGS = /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]*)*'|`[^`\\]*(?:\\[\S\s][^`\\]*)*`/g,
S_QBLOCKS = R_STRINGS.source + '|' + /(?:\breturn\s+|(?:[$\w\)\]]|\+\+|--)\s*(\/)(?![*\/]))/.source + '|' + /\/(?=[^*\/])[^[\/\\]*(?:(?:\[(?:\\.|[^\]\\]*)*\]|\\.)[^[\/\\]*)*?(\/)[gim]*/.source,
UNSUPPORTED = RegExp('[\\' + 'x00-\\x1F<>a-zA-Z0-9\'",;\\\\]'),
NEED_ESCAPE = /(?=[[\]()*+?.^$|])/g,
FINDBRACES = {
'(': RegExp('([()])|' + S_QBLOCKS, REGLOB),
'[': RegExp('([[\\]])|' + S_QBLOCKS, REGLOB),
'{': RegExp('([{}])|' + S_QBLOCKS, REGLOB)
},
DEFAULT = '{ }';
var _pairs = ['{', '}', '{', '}', /{[^}]*}/, /\\([{}])/g, /\\({)|{/g, RegExp('\\\\(})|([[({])|(})|' + S_QBLOCKS, REGLOB), DEFAULT, /^\s*{\^?\s*([$\w]+)(?:\s*,\s*(\S+))?\s+in\s+(\S.*)\s*}/, /(^|[^\\]){=[\S\s]*?}/];
var cachedBrackets = UNDEF,
_regex,
_cache = [],
_settings;
function _loopback(re) {
return re;
}
function _rewrite(re, bp) {
if (!bp) {
bp = _cache;
}
return new RegExp(re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : '');
}
function _create(pair) {
if (pair === DEFAULT) {
return _pairs;
}
var arr = pair.split(' ');
if (arr.length !== 2 || UNSUPPORTED.test(pair)) {
throw new Error('Unsupported brackets "' + pair + '"');
}
arr = arr.concat(pair.replace(NEED_ESCAPE, '\\').split(' '));
arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr);
arr[5] = _rewrite(pair.length > 3 ? /\\({|})/g : _pairs[5], arr);
arr[6] = _rewrite(_pairs[6], arr);
arr[7] = RegExp('\\\\(' + arr[3] + ')|([[({])|(' + arr[3] + ')|' + S_QBLOCKS, REGLOB);
arr[8] = pair;
return arr;
}
function _brackets(reOrIdx) {
return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx];
}
_brackets.split = function split(str, tmpl, _bp) {
// istanbul ignore next: _bp is for the compiler
if (!_bp) {
_bp = _cache;
}
var parts = [],
match,
isexpr,
start,
pos,
re = _bp[6];
isexpr = start = re.lastIndex = 0;
while (match = re.exec(str)) {
pos = match.index;
if (isexpr) {
if (match[2]) {
re.lastIndex = skipBraces(str, match[2], re.lastIndex);
continue;
}
if (!match[3]) {
continue;
}
}
if (!match[1]) {
unescapeStr(str.slice(start, pos));
start = re.lastIndex;
re = _bp[6 + (isexpr ^= 1)];
re.lastIndex = start;
}
}
if (str && start < str.length) {
unescapeStr(str.slice(start));
}
return parts;
function unescapeStr(s) {
if (tmpl || isexpr) {
parts.push(s && s.replace(_bp[5], '$1'));
} else {
parts.push(s);
}
}
function skipBraces(s, ch, ix) {
var match,
recch = FINDBRACES[ch];
recch.lastIndex = ix;
ix = 1;
while (match = recch.exec(s)) {
if (match[1] && !(match[1] === ch ? ++ix : --ix)) {
break;
}
}
return ix ? s.length : recch.lastIndex;
}
};
_brackets.hasExpr = function hasExpr(str) {
return _cache[4].test(str);
};
_brackets.loopKeys = function loopKeys(expr) {
var m = expr.match(_cache[9]);
return m ? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] } : { val: expr.trim() };
};
_brackets.array = function array(pair) {
return pair ? _create(pair) : _cache;
};
function _reset(pair) {
if ((pair || (pair = DEFAULT)) !== _cache[8]) {
_cache = _create(pair);
_regex = pair === DEFAULT ? _loopback : _rewrite;
_cache[9] = _regex(_pairs[9]);
}
cachedBrackets = pair;
}
function _setSettings(o) {
var b;
o = o || {};
b = o.brackets;
Object.defineProperty(o, 'brackets', {
set: _reset,
get: function get() {
return cachedBrackets;
},
enumerable: true
});
_settings = o;
_reset(b);
}
Object.defineProperty(_brackets, 'settings', {
set: _setSettings,
get: function get() {
return _settings;
}
});
/* istanbul ignore next: in the browser riot is always in the scope */
_brackets.settings = typeof riot !== 'undefined' && riot.settings || {};
_brackets.set = _reset;
_brackets.R_STRINGS = R_STRINGS;
_brackets.R_MLCOMMS = R_MLCOMMS;
_brackets.S_QBLOCKS = S_QBLOCKS;
return _brackets;
}();
/**
* @module tmpl
*
* tmpl - Root function, returns the template value, render with data
* tmpl.hasExpr - Test the existence of a expression inside a string
* tmpl.loopKeys - Get the keys for an 'each' loop (used by `_each`)
*/
/* istanbul ignore next */
var tmpl = function () {
var _cache = {};
function _tmpl(str, data) {
if (!str) {
return str;
}
return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr);
}
_tmpl.hasExpr = brackets.hasExpr;
_tmpl.loopKeys = brackets.loopKeys;
// istanbul ignore next
_tmpl.clearCache = function () {
_cache = {};
};
_tmpl.errorHandler = null;
function _logErr(err, ctx) {
err.riotData = {
tagName: ctx && ctx.__ && ctx.__.tagName,
_riot_id: ctx && ctx._riot_id //eslint-disable-line camelcase
};
if (_tmpl.errorHandler) {
_tmpl.errorHandler(err);
} else if (typeof console !== 'undefined' && typeof console.error === 'function') {
if (err.riotData.tagName) {
console.error('Riot template error thrown in the <%s> tag', err.riotData.tagName);
}
console.error(err);
}
}
function _create(str) {
var expr = _getTmpl(str);
if (expr.slice(0, 11) !== 'try{return ') {
expr = 'return ' + expr;
}
return new Function('E', expr + ';'); // eslint-disable-line no-new-func
}
var CH_IDEXPR = String.fromCharCode(0x2057),
RE_CSNAME = /^(?:(-?[_A-Za-z\xA0-\xFF][-\w\xA0-\xFF]*)|\u2057(\d+)~):/,
RE_QBLOCK = RegExp(brackets.S_QBLOCKS, 'g'),
RE_DQUOTE = /\u2057/g,
RE_QBMARK = /\u2057(\d+)~/g;
function _getTmpl(str) {
var qstr = [],
expr,
parts = brackets.split(str.replace(RE_DQUOTE, '"'), 1);
if (parts.length > 2 || parts[0]) {
var i,
j,
list = [];
for (i = j = 0; i < parts.length; ++i) {
expr = parts[i];
if (expr && (expr = i & 1 ? _parseExpr(expr, 1, qstr) : '"' + expr.replace(/\\/g, '\\\\').replace(/\r\n?|\n/g, '\\n').replace(/"/g, '\\"') + '"')) {
list[j++] = expr;
}
}
expr = j < 2 ? list[0] : '[' + list.join(',') + '].join("")';
} else {
expr = _parseExpr(parts[1], 0, qstr);
}
if (qstr[0]) {
expr = expr.replace(RE_QBMARK, function (_, pos) {
return qstr[pos].replace(/\r/g, '\\r').replace(/\n/g, '\\n');
});
}
return expr;
}
var RE_BREND = {
'(': /[()]/g,
'[': /[[\]]/g,
'{': /[{}]/g
};
function _parseExpr(expr, asText, qstr) {
expr = expr.replace(RE_QBLOCK, function (s, div) {
return s.length > 2 && !div ? CH_IDEXPR + (qstr.push(s) - 1) + '~' : s;
}).replace(/\s+/g, ' ').trim().replace(/\ ?([[\({},?\.:])\ ?/g, '$1');
if (expr) {
var list = [],
cnt = 0,
match;
while (expr && (match = expr.match(RE_CSNAME)) && !match.index) {
var key,
jsb,
re = /,|([[{(])|$/g;
expr = RegExp.rightContext;
key = match[2] ? qstr[match[2]].slice(1, -1).trim().replace(/\s+/g, ' ') : match[1];
while (jsb = (match = re.exec(expr))[1]) {
skipBraces(jsb, re);
}
jsb = expr.slice(0, match.index);
expr = RegExp.rightContext;
list[cnt++] = _wrapExpr(jsb, 1, key);
}
expr = !cnt ? _wrapExpr(expr, asText) : cnt > 1 ? '[' + list.join(',') + '].join(" ").trim()' : list[0];
}
return expr;
function skipBraces(ch, re) {
var mm,
lv = 1,
ir = RE_BREND[ch];
ir.lastIndex = re.lastIndex;
while (mm = ir.exec(expr)) {
if (mm[0] === ch) {
++lv;
} else if (! --lv) {
break;
}
}
re.lastIndex = lv ? expr.length : ir.lastIndex;
}
}
// istanbul ignore next: not both
var // eslint-disable-next-line max-len
JS_CONTEXT = '"in this?this:' + ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' ? 'global' : 'window') + ').',
JS_VARNAME = /[,{][\$\w]+(?=:)|(^ *|[^$\w\.{])(?!(?:typeof|true|false|null|undefined|in|instanceof|is(?:Finite|NaN)|void|NaN|new|Date|RegExp|Math)(?![$\w]))([$_A-Za-z][$\w]*)/g,
JS_NOPROPS = /^(?=(\.[$\w]+))\1(?:[^.[(]|$)/;
function _wrapExpr(expr, asText, key) {
var tb;
expr = expr.replace(JS_VARNAME, function (match, p, mvar, pos, s) {
if (mvar) {
pos = tb ? 0 : pos + match.length;
if (mvar !== 'this' && mvar !== 'global' && mvar !== 'window') {
match = p + '("' + mvar + JS_CONTEXT + mvar;
if (pos) {
tb = (s = s[pos]) === '.' || s === '(' || s === '[';
}
} else if (pos) {
tb = !JS_NOPROPS.test(s.slice(pos));
}
}
return match;
});
if (tb) {
expr = 'try{return ' + expr + '}catch(e){E(e,this)}';
}
if (key) {
expr = (tb ? 'function(){' + expr + '}.call(this)' : '(' + expr + ')') + '?"' + key + '":""';
} else if (asText) {
expr = 'function(v){' + (tb ? expr.replace('return ', 'v=') : 'v=(' + expr + ')') + ';return v||v===0?v:""}.call(this)';
}
return expr;
}
_tmpl.version = brackets.version = 'v3.0.3';
return _tmpl;
}();
/* istanbul ignore next */
var observable$1 = function observable$1(el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {};
/**
* Private variables
*/
var callbacks = {},
slice = Array.prototype.slice;
/**
* Public Api
*/
// extend the el object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given `event` ands
* execute the `callback` each time an event is triggered.
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function value(event, fn) {
if (typeof fn == 'function') {
(callbacks[event] = callbacks[event] || []).push(fn);
}
return el;
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given `event` listeners
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function value(event, fn) {
if (event == '*' && !fn) {
callbacks = {};
} else {
if (fn) {
var arr = callbacks[event];
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) {
arr.splice(i--, 1);
}
}
} else {
delete callbacks[event];
}
}
return el;
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given `event` and
* execute the `callback` at most once
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function value(event, fn) {
function on() {
el.off(event, on);
fn.apply(el, arguments);
}
return el.on(event, on);
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to
* the given `event`
* @param { String } event - event id
* @returns { Object } el
*/
trigger: {
value: function value(event) {
var arguments$1 = arguments;
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns,
fn,
i;
for (i = 0; i < arglen; i++) {
args[i] = arguments$1[i + 1]; // skip first argument
}
fns = slice.call(callbacks[event] || [], 0);
for (i = 0; fn = fns[i]; ++i) {
fn.apply(el, args);
}
if (callbacks['*'] && event != '*') {
el.trigger.apply(el, ['*', event].concat(args));
}
return el;
},
enumerable: false,
writable: false,
configurable: false
}
});
return el;
};
/**
* Specialized function for looping an array-like collection with `each={}`
* @param { Array } list - collection of items
* @param {Function} fn - callback function
* @returns { Array } the array looped
*/
function each(list, fn) {
var len = list ? list.length : 0;
var i = 0;
for (; i < len; ++i) {
fn(list[i], i);
}
return list;
}
/**
* Check whether an array contains an item
* @param { Array } array - target array
* @param { * } item - item to test
* @returns { Boolean } -
*/
function contains(array, item) {
return array.indexOf(item) !== -1;
}
/**
* Convert a string containing dashes to camel case
* @param { String } str - input string
* @returns { String } my-string -> myString
*/
function toCamel(str) {
return str.replace(/-(\w)/g, function (_, c) {
return c.toUpperCase();
});
}
/**
* Faster String startsWith alternative
* @param { String } str - source string
* @param { String } value - test string
* @returns { Boolean } -
*/
function startsWith(str, value) {
return str.slice(0, value.length) === value;
}
/**
* Helper function to set an immutable property
* @param { Object } el - object where the new property will be set
* @param { String } key - object key where the new property will be stored
* @param { * } value - value of the new property
* @param { Object } options - set the propery overriding the default options
* @returns { Object } - the initial object
*/
function defineProperty(el, key, value, options) {
Object.defineProperty(el, key, extend({
value: value,
enumerable: false,
writable: false,
configurable: true
}, options));
return el;
}
/**
* Extend any object with other properties
* @param { Object } src - source object
* @returns { Object } the resulting extended object
*
* var obj = { foo: 'baz' }
* extend(obj, {bar: 'bar', foo: 'bar'})
* console.log(obj) => {bar: 'bar', foo: 'bar'}
*
*/
function extend(src) {
var obj,
args = arguments;
for (var i = 1; i < args.length; ++i) {
if (obj = args[i]) {
for (var key in obj) {
// check if this property of the source object could be overridden
if (isWritable(src, key)) {
src[key] = obj[key];
}
}
}
}
return src;
}
var misc = Object.freeze({
each: each,
contains: contains,
toCamel: toCamel,
startsWith: startsWith,
defineProperty: defineProperty,
extend: extend
});
var settings$1 = extend(Object.create(brackets.settings), {
skipAnonymousTags: true
});
/**
* Trigger DOM events
* @param { HTMLElement } dom - dom element target of the event
* @param { Function } handler - user function
* @param { Object } e - event object
*/
function handleEvent(dom, handler, e) {
var ptag = this.__.parent,
item = this.__.item;
if (!item) {
while (ptag && !item) {
item = ptag.__.item;
ptag = ptag.__.parent;
}
}
// override the event properties
/* istanbul ignore next */
if (isWritable(e, 'currentTarget')) {
e.currentTarget = dom;
}
/* istanbul ignore next */
if (isWritable(e, 'target')) {
e.target = e.srcElement;
}
/* istanbul ignore next */
if (isWritable(e, 'which')) {
e.which = e.charCode || e.keyCode;
}
e.item = item;
handler.call(this, e);
if (!e.preventUpdate) {
var p = getImmediateCustomParentTag(this);
// fixes #2083
if (p.isMounted) {
p.update();
}
}
}
/**
* Attach an event to a DOM node
* @param { String } name - event name
* @param { Function } handler - event callback
* @param { Object } dom - dom node
* @param { Tag } tag - tag instance
*/
function setEventHandler(name, handler, dom, tag) {
var eventName,
cb = handleEvent.bind(tag, dom, handler);
// normalize event name
eventName = name.replace(RE_EVENTS_PREFIX, '');
// cache the listener into the listeners array
if (!contains(tag.__.listeners, dom)) {
tag.__.listeners.push(dom);
}
if (!dom[RIOT_EVENTS_KEY]) {
dom[RIOT_EVENTS_KEY] = {};
}
if (dom[RIOT_EVENTS_KEY][name]) {
dom.removeEventListener(eventName, dom[RIOT_EVENTS_KEY][name]);
}
dom[RIOT_EVENTS_KEY][name] = cb;
dom.addEventListener(eventName, cb, false);
}
/**
* Update dynamically created data-is tags with changing expressions
* @param { Object } expr - expression tag and expression info
* @param { Tag } parent - parent for tag creation
* @param { String } tagName - tag implementation we want to use
*/
function updateDataIs(expr, parent, tagName) {
var conf, isVirtual, head, ref;
if (expr.tag && expr.tagName === tagName) {
expr.tag.update();
return;
}
isVirtual = expr.dom.tagName === 'VIRTUAL';
// sync _parent to accommodate changing tagnames
if (expr.tag) {
// need placeholder before unmount
if (isVirtual) {
head = expr.tag.__.head;
ref = createDOMPlaceholder();
head.parentNode.insertBefore(ref, head);
}
expr.tag.unmount(true);
}
expr.impl = __TAG_IMPL[tagName];
conf = { root: expr.dom, parent: parent, hasImpl: true, tagName: tagName };
expr.tag = initChildTag(expr.impl, conf, expr.dom.innerHTML, parent);
each(expr.attrs, function (a) {
return setAttr(expr.tag.root, a.name, a.value);
});
expr.tagName = tagName;
expr.tag.mount();
if (isVirtual) {
makeReplaceVirtual(expr.tag, ref || expr.tag.root);
} // root exist first time, after use placeholder
// parent is the placeholder tag, not the dynamic tag so clean up
parent.__.onUnmount = function () {
var delName = expr.tag.opts.dataIs,
tags = expr.tag.parent.tags,
_tags = expr.tag.__.parent.tags;
arrayishRemove(tags, delName, expr.tag);
arrayishRemove(_tags, delName, expr.tag);
expr.tag.unmount();
};
}
/**
* Nomalize any attribute removing the "riot-" prefix
* @param { String } attrName - original attribute name
* @returns { String } valid html attribute name
*/
function normalizeAttrName(attrName) {
if (!attrName) {
return null;
}
attrName = attrName.replace(ATTRS_PREFIX, '');
if (CASE_SENSITIVE_ATTRIBUTES[attrName]) {
attrName = CASE_SENSITIVE_ATTRIBUTES[attrName];
}
return attrName;
}
/**
* Update on single tag expression
* @this Tag
* @param { Object } expr - expression logic
* @returns { undefined }
*/
function updateExpression(expr) {
if (this.root && getAttr(this.root, 'virtualized')) {
return;
}
var dom = expr.dom,
// remove the riot- prefix
attrName = normalizeAttrName(expr.attr),
isToggle = contains([SHOW_DIRECTIVE, HIDE_DIRECTIVE], attrName),
isVirtual = expr.root && expr.root.tagName === 'VIRTUAL',
parent = dom && (expr.parent || dom.parentNode),
// detect the style attributes
isStyleAttr = attrName === 'style',
isClassAttr = attrName === 'class',
isObj,
value;
// if it's a tag we could totally skip the rest
if (expr._riot_id) {
if (expr.isMounted) {
expr.update();
// if it hasn't been mounted yet, do that now.
} else {
expr.mount();
if (isVirtual) {
makeReplaceVirtual(expr, expr.root);
}
}
return;
}
// if this expression has the update method it means it can handle the DOM changes by itself
if (expr.update) {
return expr.update();
}
// ...it seems to be a simple expression so we try to calculat its value
value = tmpl(expr.expr, this);
isObj = isObject(value);
// convert the style/class objects to strings
if (isObj) {
isObj = !isClassAttr && !isStyleAttr;
if (isClassAttr) {
value = tmpl(JSON.stringify(value), this);
} else if (isStyleAttr) {
value = styleObjectToString(value);
}
}
// remove original attribute
if (expr.attr && (!expr.isAttrRemoved || !value)) {
remAttr(dom, expr.attr);
expr.isAttrRemoved = true;
}
// for the boolean attributes we don't need the value
// we can convert it to checked=true to checked=checked
if (expr.bool) {
value = value ? attrName : false;
}
if (expr.isRtag) {
return updateDataIs(expr, this, value);
}
if (expr.wasParsedOnce && expr.value === value) {
return;
}
// update the expression value
expr.value = value;
expr.wasParsedOnce = true;
// if the value is an object we can not do much more with it
if (isObj && !isToggle) {
return;
}
// avoid to render undefined/null values
if (isBlank(value)) {
value = '';
}
// textarea and text nodes have no attribute name
if (!attrName) {
// about #815 w/o replace: the browser converts the value to a string,
// the comparison by "==" does too, but not in the server
value += '';
// test for parent avoids error with invalid assignment to nodeValue
if (parent) {
// cache the parent node because somehow it will become null on IE
// on the next iteration
expr.parent = parent;
if (parent.tagName === 'TEXTAREA') {
parent.value = value; // #1113
if (!IE_VERSION) {
dom.nodeValue = value;
} // #1625 IE throws here, nodeValue
} // will be available on 'updated'
else {
dom.nodeValue = value;
}
}
return;
}
// event handler
if (isFunction(value)) {
setEventHandler(attrName, value, dom, this);
// show / hide
} else if (isToggle) {
toggleVisibility(dom, attrName === HIDE_DIRECTIVE ? !value : value);
// handle attributes
} else {
if (expr.bool) {
dom[attrName] = value;
}
if (attrName === 'value' && dom.value !== value) {
dom.value = value;
}
if (!isBlank(value) && value !== false) {
setAttr(dom, attrName, value);
}
// make sure that in case of style changes
// the element stays hidden
if (isStyleAttr && dom.hidden) {
toggleVisibility(dom, false);
}
}
}
/**
* Update all the expressions in a Tag instance
* @this Tag
* @param { Array } expressions - expression that must be re evaluated
*/
function updateAllExpressions(expressions) {
each(expressions, updateExpression.bind(this));
}
var IfExpr = {
init: function init(dom, tag, expr) {
remAttr(dom, CONDITIONAL_DIRECTIVE);
this.tag = tag;
this.expr = expr;
this.stub = document.createTextNode('');
this.pristine = dom;
var p = dom.parentNode;
p.insertBefore(this.stub, dom);
p.removeChild(dom);
return this;
},
update: function update() {
this.value = tmpl(this.expr, this.tag);
if (this.value && !this.current) {
// insert
this.current = this.pristine.cloneNode(true);
this.stub.parentNode.insertBefore(this.current, this.stub);
this.expressions = [];
parseExpressions.apply(this.tag, [this.current, this.expressions, true]);
} else if (!this.value && this.current) {
// remove
unmountAll(this.expressions);
if (this.current._tag) {
this.current._tag.unmount();
} else if (this.current.parentNode) {
this.current.parentNode.removeChild(this.current);
}
this.current = null;
this.expressions = [];
}
if (this.value) {
updateAllExpressions.call(this.tag, this.expressions);
}
},
unmount: function unmount() {
unmountAll(this.expressions || []);
delete this.pristine;
delete this.parentNode;
delete this.stub;
}
};
var RefExpr = {
init: function init(dom, parent, attrName, attrValue) {
this.dom = dom;
this.attr = attrName;
this.rawValue = attrValue;
this.parent = parent;
this.hasExp = tmpl.hasExpr(attrValue);
return this;
},
update: function update() {
var old = this.value;
var customParent = this.parent && getImmediateCustomParentTag(this.parent);
// if the referenced element is a custom tag, then we set the tag itself, rather than DOM
var tagOrDom = this.tag || this.dom;
this.value = this.hasExp ? tmpl(this.rawValue, this.parent) : this.rawValue;
// the name changed, so we need to remove it from the old key (if present)
if (!isBlank(old) && customParent) {
arrayishRemove(customParent.refs, old, tagOrDom);
}
if (isBlank(this.value)) {
// if the value is blank, we remove it
remAttr(this.dom, this.attr);
} else {
// add it to the refs of parent tag (this behavior was changed >=3.0)
if (customParent) {
arrayishAdd(customParent.refs, this.value, tagOrDom,
// use an array if it's a looped node and the ref is not an expression
null, this.parent.__.index);
}
// set the actual DOM attr
setAttr(this.dom, this.attr, this.value);
}
},
unmount: function unmount() {
var tagOrDom = this.tag || this.dom;
var customParent = this.parent && getImmediateCustomParentTag(this.parent);
if (!isBlank(this.value) && customParent) {
arrayishRemove(customParent.refs, this.value, tagOrDom);
}
delete this.dom;
delete this.parent;
}
};
/**
* Convert the item looped into an object used to extend the child tag properties
* @param { Object } expr - object containing the keys used to extend the children tags
* @param { * } key - value to assign to the new object returned
* @param { * } val - value containing the position of the item in the array
* @param { Object } base - prototype object for the new item
* @returns { Object } - new object containing the values of the original item
*
* The variables 'key' and 'val' are arbitrary.
* They depend on the collection type looped (Array, Object)
* and on the expression used on the each tag
*
*/
function mkitem(expr, key, val, base) {
var item = base ? Object.create(base) : {};
item[expr.key] = key;
if (expr.pos) {
item[expr.pos] = val;
}
return item;
}
/**
* Unmount the redundant tags
* @param { Array } items - array containing the current items to loop
* @param { Array } tags - array containing all the children tags
*/
function unmountRedundant(items, tags) {
var i = tags.length,
j = items.length;
while (i > j) {
i--;
remove.apply(tags[i], [tags, i]);
}
}
/**
* Remove a child tag
* @this Tag
* @param { Array } tags - tags collection
* @param { Number } i - index of the tag to remove
*/
function remove(tags, i) {
tags.splice(i, 1);
this.unmount();
arrayishRemove(this.parent, this, this.__.tagName, true);
}
/**
* Move the nested custom tags in non custom loop tags
* @this Tag
* @param { Number } i - current position of the loop tag
*/
function moveNestedTags(i) {
var this$1 = this;
each(Object.keys(this.tags), function (tagName) {
moveChildTag.apply(this$1.tags[tagName], [tagName, i]);
});
}
/**
* Move a child tag
* @this Tag
* @param { HTMLElement } root - dom node containing all the loop children
* @param { Tag } nextTag - instance of the next tag preceding the one we want to move
* @param { Boolean } isVirtual - is it a virtual tag?
*/
function move(root, nextTag, isVirtual) {
if (isVirtual) {
moveVirtual.apply(this, [root, nextTag]);
} else {
safeInsert(root, this.root, nextTag.root);
}
}
/**
* Insert and mount a child tag
* @this Tag
* @param { HTMLElement } root - dom node containing all the loop children
* @param { Tag } nextTag - instance of the next tag preceding the one we want to insert
* @param { Boolean } isVirtual - is it a virtual tag?
*/
function insert(root, nextTag, isVirtual) {
if (isVirtual) {
makeVirtual.apply(this, [root, nextTag]);
} else {
safeInsert(root, this.root, nextTag.root);
}
}
/**
* Append a new tag into the DOM
* @this Tag
* @param { HTMLElement } root - dom node containing all the loop children
* @param { Boolean } isVirtual - is it a virtual tag?
*/
function append(root, isVirtual) {
if (isVirtual) {
makeVirtual.call(this, root);
} else {
root.appendChild(this.root);
}
}
/**
* Manage tags having the 'each'
* @param { HTMLElement } dom - DOM node we need to loop
* @param { Tag } parent - parent tag instance where the dom node is contained
* @param { String } expr - string contained in the 'each' attribute
* @returns { Object } expression object for this each loop
*/
function _each(dom, parent, expr) {
// remove the each property from the original tag
remAttr(dom, LOOP_DIRECTIVE);
var mustReorder = _typeof(getAttr(dom, LOOP_NO_REORDER_DIRECTIVE)) !== T_STRING || remAttr(dom, LOOP_NO_REORDER_DIRECTIVE),
tagName = getTagName(dom),
impl = __TAG_IMPL[tagName],
parentNode = dom.parentNode,
placeholder = createDOMPlaceholder(),
child = getTag(dom),
ifExpr = getAttr(dom, CONDITIONAL_DIRECTIVE),
tags = [],
oldItems = [],
hasKeys,
isLoop = true,
isAnonymous = !__TAG_IMPL[tagName],
isVirtual = dom.tagName === 'VIRTUAL';
// parse the each expression
expr = tmpl.loopKeys(expr);
expr.isLoop = true;
if (ifExpr) {
remAttr(dom, CONDITIONAL_DIRECTIVE);
}
// insert a marked where the loop tags will be injected
parentNode.insertBefore(placeholder, dom);
parentNode.removeChild(dom);
expr.update = function updateEach() {
// get the new items collection
expr.value = tmpl(expr.val, parent);
var frag = createFrag(),
items = expr.value,
isObject$$1 = !isArray(items) && !isString(items),
root = placeholder.parentNode;
// object loop. any changes cause full redraw
if (isObject$$1) {
hasKeys = items || false;
items = hasKeys ? Object.keys(items).map(function (key) {
return mkitem(expr, items[key], key);
}) : [];
} else {
hasKeys = false;
}
if (ifExpr) {
items = items.filter(function (item, i) {
if (expr.key && !isObject$$1) {
return !!tmpl(ifExpr, mkitem(expr, item, i, parent));
}
return !!tmpl(ifExpr, extend(Object.create(parent), item));
});
}
// loop all the new items
each(items, function (item, i) {
// reorder only if the items are objects
var doReorder = mustReorder && (typeof item === 'undefined' ? 'undefined' : _typeof(item)) === T_OBJECT && !hasKeys,
oldPos = oldItems.indexOf(item),
isNew = oldPos === -1,
pos = !isNew && doReorder ? oldPos : i,
// does a tag exist in this position?
tag = tags[pos],
mustAppend = i >= oldItems.length,
mustCreate = doReorder && isNew || !doReorder && !tag;
item = !hasKeys && expr.key ? mkitem(expr, item, i) : item;
// new tag
if (mustCreate) {
tag = new Tag$1(impl, {
parent: parent,
isLoop: isLoop,
isAnonymous: isAnonymous,
tagName: tagName,
root: dom.cloneNode(isAnonymous),
item: item,
index: i
}, dom.innerHTML);
// mount the tag
tag.mount();
if (mustAppend) {
append.apply(tag, [frag || root, isVirtual]);
} else {
insert.apply(tag, [root, tags[i], isVirtual]);
}
if (!mustAppend) {
oldItems.splice(i, 0, item);
}
tags.splice(i, 0, tag);
if (child) {
arrayishAdd(parent.tags, tagName, tag, true);
}
} else if (pos !== i && doReorder) {
// move
if (contains(items, oldItems[pos])) {
move.apply(tag, [root, tags[i], isVirtual]);
// move the old tag instance
tags.splice(i, 0, tags.splice(pos, 1)[0]);
// move the old item
oldItems.splice(i, 0, oldItems.splice(pos, 1)[0]);
}
// update the position attribute if it exists
if (expr.pos) {
tag[expr.pos] = i;
}
// if the loop tags are not custom
// we need to move all their custom tags into the right position
if (!child && tag.tags) {
moveNestedTags.call(tag, i);
}
}
// cache the original item to use it in the events bound to this node
// and its children
tag.__.item = item;
tag.__.index = i;
tag.__.parent = parent;
if (!mustCreate) {
tag.update(item);
}
});
// remove the redundant tags
unmountRedundant(items, tags);
// clone the items array
oldItems = items.slice();
root.insertBefore(frag, placeholder);
};
expr.unmount = function () {
each(tags, function (t) {
t.unmount();
});
};
return expr;
}
/**
* Walk the tag DOM to detect the expressions to evaluate
* @this Tag
* @param { HTMLElement } root - root tag where we will start digging the expressions
* @param { Array } expressions - empty array where the expressions will be added
* @param { Boolean } mustIncludeRoot - flag to decide whether the root must be parsed as well
* @returns { Object } an object containing the root noode and the dom tree
*/
function parseExpressions(root, expressions, mustIncludeRoot) {
var this$1 = this;
var tree = { parent: { children: expressions } };
walkNodes(root, function (dom, ctx) {
var type = dom.nodeType,
parent = ctx.parent,
attr,
expr,
tagImpl;
if (!mustIncludeRoot && dom === root) {
return { parent: parent };
}
// text node
if (type === 3 && dom.parentNode.tagName !== 'STYLE' && tmpl.hasExpr(dom.nodeValue)) {
parent.children.push({ dom: dom, expr: dom.nodeValue });
}
if (type !== 1) {
return ctx;
} // not an element
var isVirtual = dom.tagName === 'VIRTUAL';
// loop. each does it's own thing (for now)
if (attr = getAttr(dom, LOOP_DIRECTIVE)) {
if (isVirtual) {
setAttr(dom, 'loopVirtual', true);
} // ignore here, handled in _each
parent.children.push(_each(dom, this$1, attr));
return false;
}
// if-attrs become the new parent. Any following expressions (either on the current
// element, or below it) become children of this expression.
if (attr = getAttr(dom, CONDITIONAL_DIRECTIVE)) {
parent.children.push(Object.create(IfExpr).init(dom, this$1, attr));
return false;
}
if (expr = getAttr(dom, IS_DIRECTIVE)) {
if (tmpl.hasExpr(expr)) {
parent.children.push({ isRtag: true, expr: expr, dom: dom, attrs: [].slice.call(dom.attributes) });
return false;
}
}
// if this is a tag, stop traversing here.
// we ignore the root, since parseExpressions is called while we're mounting that root
tagImpl = getTag(dom);
if (isVirtual) {
if (getAttr(dom, 'virtualized')) {
dom.parentElement.removeChild(dom);
} // tag created, remove from dom
if (!tagImpl && !getAttr(dom, 'virtualized') && !getAttr(dom, 'loopVirtual')) // ok to create virtual tag
{
tagImpl = { tmpl: dom.outerHTML };
}
}
if (tagImpl && (dom !== root || mustIncludeRoot)) {
if (isVirtual && !getAttr(dom, IS_DIRECTIVE)) {
// handled in update
// can not remove attribute like directives
// so flag for removal after creation to prevent maximum stack error
setAttr(dom, 'virtualized', true);
var tag = new Tag$1({ tmpl: dom.outerHTML }, { root: dom, parent: this$1 }, dom.innerHTML);
parent.children.push(tag); // no return, anonymous tag, keep parsing
} else {
var conf = { root: dom, parent: this$1, hasImpl: true };
parent.children.push(initChildTag(tagImpl, conf, dom.innerHTML, this$1));
return false;
}
}
// attribute expressions
parseAttributes.apply(this$1, [dom, dom.attributes, function (attr, expr) {
if (!expr) {
return;
}
parent.children.push(expr);
}]);
// whatever the parent is, all child elements get the same parent.
// If this element had an if-attr, that's the parent for all child elements
return { parent: parent };
}, tree);
}
/**
* Calls `fn` for every attribute on an element. If that attr has an expression,
* it is also passed to fn.
* @this Tag
* @param { HTMLElement } dom - dom node to parse
* @param { Array } attrs - array of attributes
* @param { Function } fn - callback to exec on any iteration
*/
function parseAttributes(dom, attrs, fn) {
var this$1 = this;
each(attrs, function (attr) {
var name = attr.name,
bool = isBoolAttr(name),
expr;
if (contains(REF_DIRECTIVES, name)) {
expr = Object.create(RefExpr).init(dom, this$1, name, attr.value);
} else if (tmpl.hasExpr(attr.value)) {
expr = { dom: dom, expr: attr.value, attr: name, bool: bool };
}
fn(attr, expr);
});
}
/*
Includes hacks needed for the Internet Explorer version 9 and below
See: http://kangax.github.io/compat-table/es5/#ie8
http://codeplanet.io/dropping-ie8/
*/
var reHasYield = /<yield\b/i;
var reYieldAll = /<yield\s*(?:\/>|>([\S\s]*?)<\/yield\s*>|>)/ig;
var reYieldSrc = /<yield\s+to=['"]([^'">]*)['"]\s*>([\S\s]*?)<\/yield\s*>/ig;
var reYieldDest = /<yield\s+from=['"]?([-\w]+)['"]?\s*(?:\/>|>([\S\s]*?)<\/yield\s*>)/ig;
var rootEls = { tr: 'tbody', th: 'tr', td: 'tr', col: 'colgroup' };
var tblTags = IE_VERSION && IE_VERSION < 10 ? RE_SPECIAL_TAGS : RE_SPECIAL_TAGS_NO_OPTION;
var GENERIC = 'div';
/*
Creates the root element for table or select child elements:
tr/th/td/thead/tfoot/tbody/caption/col/colgroup/option/optgroup
*/
function specialTags(el, tmpl, tagName) {
var select = tagName[0] === 'o',
parent = select ? 'select>' : 'table>';
// trim() is important here, this ensures we don't have artifacts,
// so we can check if we have only one element inside the parent
el.innerHTML = '<' + parent + tmpl.trim() + '</' + parent;
parent = el.firstChild;
// returns the immediate parent if tr/th/td/col is the only element, if not
// returns the whole tree, as this can include additional elements
/* istanbul ignore next */
if (select) {
parent.selectedIndex = -1; // for IE9, compatible w/current riot behavior
} else {
// avoids insertion of cointainer inside container (ex: tbody inside tbody)
var tname = rootEls[tagName];
if (tname && parent.childElementCount === 1) {
parent = $(tname, parent);
}
}
return parent;
}
/*
Replace the yield tag from any tag template with the innerHTML of the
original tag in the page
*/
function replaceYield(tmpl, html) {
// do nothing if no yield
if (!reHasYield.test(tmpl)) {
return tmpl;
}
// be careful with #1343 - string on the source having `$1`
var src = {};
html = html && html.replace(reYieldSrc, function (_, ref, text) {
src[ref] = src[ref] || text; // preserve first definition
return '';
}).trim();
return tmpl.replace(reYieldDest, function (_, ref, def) {
// yield with from - to attrs
return src[ref] || def || '';
}).replace(reYieldAll, function (_, def) {
// yield without any "from"
return html || def || '';
});
}
/**
* Creates a DOM element to wrap the given content. Normally an `DIV`, but can be
* also a `TABLE`, `SELECT`, `TBODY`, `TR`, or `COLGROUP` element.
*
* @param { String } tmpl - The template coming from the custom tag definition
* @param { String } html - HTML content that comes from the DOM element where you
* will mount the tag, mostly the original tag in the page
* @returns { HTMLElement } DOM element with _tmpl_ merged through `YIELD` with the _html_.
*/
function mkdom(tmpl, html) {
var match = tmpl && tmpl.match(/^\s*<([-\w]+)/),
tagName = match && match[1].toLowerCase(),
el = mkEl(GENERIC);
// replace all the yield tags with the tag inner html
tmpl = replaceYield(tmpl, html);
/* istanbul ignore next */
if (tblTags.test(tagName)) {
el = specialTags(el, tmpl, tagName);
} else {
setInnerHTML(el, tmpl);
}
return el;
}
/**
* Another way to create a riot tag a bit more es6 friendly
* @param { HTMLElement } el - tag DOM selector or DOM node/s
* @param { Object } opts - tag logic
* @returns { Tag } new riot tag instance
*/
function Tag$2(el, opts) {
// get the tag properties from the class constructor
var ref = this;
var name = ref.name;
var tmpl = ref.tmpl;
var css = ref.css;
var attrs = ref.attrs;
var onCreate = ref.onCreate;
// register a new tag and cache the class prototype
if (!__TAG_IMPL[name]) {
tag$1(name, tmpl, css, attrs, onCreate);
// cache the class constructor
__TAG_IMPL[name].class = this.constructor;
}
// mount the tag using the class instance
mountTo(el, name, opts, this);
// inject the component css
if (css) {
styleManager.inject();
}
return this;
}
/**
* Create a new riot tag implementation
* @param { String } name - name/id of the new riot tag
* @param { String } tmpl - tag template
* @param { String } css - custom tag css
* @param { String } attrs - root tag attributes
* @param { Function } fn - user function
* @returns { String } name/id of the tag just created
*/
function tag$1(name, tmpl, css, attrs, fn) {
if (isFunction(attrs)) {
fn = attrs;
if (/^[\w\-]+\s?=/.test(css)) {
attrs = css;
css = '';
} else {
attrs = '';
}
}
if (css) {
if (isFunction(css)) {
fn = css;
} else {
styleManager.add(css);
}
}
name = name.toLowerCase();
__TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn };
return name;
}
/**
* Create a new riot tag implementation (for use by the compiler)
* @param { String } name - name/id of the new riot tag
* @param { String } tmpl - tag template
* @param { String } css - custom tag css
* @param { String } attrs - root tag attributes
* @param { Function } fn - user function
* @returns { String } name/id of the tag just created
*/
function tag2$1(name, tmpl, css, attrs, fn) {
if (css) {
styleManager.add(css, name);
}
__TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn };
return name;
}
/**
* Mount a tag using a specific tag implementation
* @param { * } selector - tag DOM selector or DOM node/s
* @param { String } tagName - tag implementation name
* @param { Object } opts - tag logic
* @returns { Array } new tags instances
*/
function mount$1(selector, tagName, opts) {
var tags = [];
function pushTagsTo(root) {
if (root.tagName) {
var riotTag = getAttr(root, IS_DIRECTIVE);
// have tagName? force riot-tag to be the same
if (tagName && riotTag !== tagName) {
riotTag = tagName;
setAttr(root, IS_DIRECTIVE, tagName);
}
var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts);
if (tag) {
tags.push(tag);
}
} else if (root.length) {
each(root, pushTagsTo);
} // assume nodeList
}
// inject styles into DOM
styleManager.inject();
if (isObject(tagName)) {
opts = tagName;
tagName = 0;
}
var elem;
var allTags;
// crawl the DOM to find the tag
if (isString(selector)) {
selector = selector === '*' ?
// select all registered tags
// & tags found with the riot-tag attribute set
allTags = selectTags() :
// or just the ones named like the selector
selector + selectTags(selector.split(/, */));
// make sure to pass always a selector
// to the querySelectorAll function
elem = selector ? $$(selector) : [];
} else
// probably you have passed already a tag or a NodeList
{
elem = selector;
}
// select all the registered and mount them inside their root elements
if (tagName === '*') {
// get all custom tags
tagName = allTags || selectTags();
// if the root els it's just a single tag
if (elem.tagName) {
elem = $$(tagName, elem);
} else {
// select all the children for all the different root elements
var nodeList = [];
each(elem, function (_el) {
return nodeList.push($$(tagName, _el));
});
elem = nodeList;
}
// get rid of the tagName
tagName = 0;
}
pushTagsTo(elem);
return tags;
}
// Create a mixin that could be globally shared across all the tags
var mixins = {};
var globals = mixins[GLOBAL_MIXIN] = {};
var mixins_id = 0;
/**
* Create/Return a mixin by its name
* @param { String } name - mixin name (global mixin if object)
* @param { Object } mix - mixin logic
* @param { Boolean } g - is global?
* @returns { Object } the mixin logic
*/
function mixin$1(name, mix, g) {
// Unnamed global
if (isObject(name)) {
mixin$1("__unnamed_" + mixins_id++, name, true);
return;
}
var store = g ? globals : mixins;
// Getter
if (!mix) {
if (isUndefined(store[name])) {
throw new Error('Unregistered mixin: ' + name);
}
return store[name];
}
// Setter
store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix);
}
/**
* Update all the tags instances created
* @returns { Array } all the tags instances
*/
function update$1() {
return each(__TAGS_CACHE, function (tag) {
return tag.update();
});
}
function unregister$1(name) {
delete __TAG_IMPL[name];
}
var version$1 = 'v3.4.2';
var core = Object.freeze({
Tag: Tag$2,
tag: tag$1,
tag2: tag2$1,
mount: mount$1,
mixin: mixin$1,
update: update$1,
unregister: unregister$1,
version: version$1
});
// counter to give a unique id to all the Tag instances
var __uid = 0;
/**
* We need to update opts for this tag. That requires updating the expressions
* in any attributes on the tag, and then copying the result onto opts.
* @this Tag
* @param {Boolean} isLoop - is it a loop tag?
* @param { Tag } parent - parent tag node
* @param { Boolean } isAnonymous - is it a tag without any impl? (a tag not registered)
* @param { Object } opts - tag options
* @param { Array } instAttrs - tag attributes array
*/
function updateOpts(isLoop, parent, isAnonymous, opts, instAttrs) {
// isAnonymous `each` tags treat `dom` and `root` differently. In this case
// (and only this case) we don't need to do updateOpts, because the regular parse
// will update those attrs. Plus, isAnonymous tags don't need opts anyway
if (isLoop && isAnonymous) {
return;
}
var ctx = !isAnonymous && isLoop ? this : parent || this;
each(instAttrs, function (attr) {
if (attr.expr) {
updateAllExpressions.call(ctx, [attr.expr]);
}
// normalize the attribute names
opts[toCamel(attr.name).replace(ATTRS_PREFIX, '')] = attr.expr ? attr.expr.value : attr.value;
});
}
/**
* Tag class
* @constructor
* @param { Object } impl - it contains the tag template, and logic
* @param { Object } conf - tag options
* @param { String } innerHTML - html that eventually we need to inject in the tag
*/
function Tag$1(impl, conf, innerHTML) {
if (impl === void 0) impl = {};
if (conf === void 0) conf = {};
var opts = extend({}, conf.opts),
parent = conf.parent,
isLoop = conf.isLoop,
isAnonymous = !!conf.isAnonymous,
skipAnonymous = settings$1.skipAnonymousTags && isAnonymous,
item = cleanUpData(conf.item),
index = conf.index,
// available only for the looped nodes
instAttrs = [],
// All attributes on the Tag when it's first parsed
implAttrs = [],
// expressions on this type of Tag
expressions = [],
root = conf.root,
tagName = conf.tagName || getTagName(root),
isVirtual = tagName === 'virtual',
propsInSyncWithParent = [],
dom;
// make this tag observable
if (!skipAnonymous) {
observable$1(this);
}
// only call unmount if we have a valid __TAG_IMPL (has name property)
if (impl.name && root._tag) {
root._tag.unmount(true);
}
// not yet mounted
this.isMounted = false;
defineProperty(this, '__', {
isAnonymous: isAnonymous,
instAttrs: instAttrs,
innerHTML: innerHTML,
tagName: tagName,
index: index,
isLoop: isLoop,
// tags having event listeners
// it would be better to use weak maps here but we can not introduce breaking changes now
listeners: [],
// these vars will be needed only for the virtual tags
virts: [],
tail: null,
head: null,
parent: null,
item: null
});
// create a unique id to this tag
// it could be handy to use it also to improve the virtual dom rendering speed
defineProperty(this, '_riot_id', ++__uid); // base 1 allows test !t._riot_id
defineProperty(this, 'root', root);
extend(this, { opts: opts }, item);
// protect the "tags" and "refs" property from being overridden
defineProperty(this, 'parent', parent || null);
defineProperty(this, 'tags', {});
defineProperty(this, 'refs', {});
dom = isLoop && isAnonymous ? root : mkdom(impl.tmpl, innerHTML, isLoop);
/**
* Update the tag expressions and options
* @param { * } data - data we want to use to extend the tag properties
* @returns { Tag } the current tag instance
*/
defineProperty(this, 'update', function tagUpdate(data) {
var nextOpts = {},
canTrigger = this.isMounted && !skipAnonymous;
// make sure the data passed will not override
// the component core methods
data = cleanUpData(data);
extend(this, data);
updateOpts.apply(this, [isLoop, parent, isAnonymous, nextOpts, instAttrs]);
if (canTrigger && this.isMounted && isFunction(this.shouldUpdate) && !this.shouldUpdate(data, nextOpts)) {
return this;
}
// inherit properties from the parent, but only for isAnonymous tags
if (isLoop && isAnonymous) {
inheritFrom.apply(this, [this.parent, propsInSyncWithParent]);
}
extend(opts, nextOpts);
if (canTrigger) {
this.trigger('update', data);
}
updateAllExpressions.call(this, expressions);
if (canTrigger) {
this.trigger('updated');
}
return this;
}.bind(this));
/**
* Add a mixin to this tag
* @returns { Tag } the current tag instance
*/
defineProperty(this, 'mixin', function tagMixin() {
var this$1 = this;
each(arguments, function (mix) {
var instance, obj;
var props = [];
// properties blacklisted and will not be bound to the tag instance
var propsBlacklist = ['init', '__proto__'];
mix = isString(mix) ? mixin$1(mix) : mix;
// check if the mixin is a function
if (isFunction(mix)) {
// create the new mixin instance
instance = new mix();
} else {
instance = mix;
}
var proto = Object.getPrototypeOf(instance);
// build multilevel prototype inheritance chain property list
do {
props = props.concat(Object.getOwnPropertyNames(obj || instance));
} while (obj = Object.getPrototypeOf(obj || instance));
// loop the keys in the function prototype or the all object keys
each(props, function (key) {
// bind methods to this
// allow mixins to override other properties/parent mixins
if (!contains(propsBlacklist, key)) {
// check for getters/setters
var descriptor = Object.getOwnPropertyDescriptor(instance, key) || Object.getOwnPropertyDescriptor(proto, key);
var hasGetterSetter = descriptor && (descriptor.get || descriptor.set);
// apply method only if it does not already exist on the instance
if (!this$1.hasOwnProperty(key) && hasGetterSetter) {
Object.defineProperty(this$1, key, descriptor);
} else {
this$1[key] = isFunction(instance[key]) ? instance[key].bind(this$1) : instance[key];
}
}
});
// init method will be called automatically
if (instance.init) {
instance.init.bind(this$1)();
}
});
return this;
}.bind(this));
/**
* Mount the current tag instance
* @returns { Tag } the current tag instance
*/
defineProperty(this, 'mount', function tagMount() {
var this$1 = this;
root._tag = this; // keep a reference to the tag just created
// Read all the attrs on this instance. This give us the info we need for updateOpts
parseAttributes.apply(parent, [root, root.attributes, function (attr, expr) {
if (!isAnonymous && RefExpr.isPrototypeOf(expr)) {
expr.tag = this$1;
}
attr.expr = expr;
instAttrs.push(attr);
}]);
// update the root adding custom attributes coming from the compiler
implAttrs = [];
walkAttrs(impl.attrs, function (k, v) {
implAttrs.push({ name: k, value: v });
});
parseAttributes.apply(this, [root, implAttrs, function (attr, expr) {
if (expr) {
expressions.push(expr);
} else {
setAttr(root, attr.name, attr.value);
}
}]);
// initialiation
updateOpts.apply(this, [isLoop, parent, isAnonymous, opts, instAttrs]);
// add global mixins
var globalMixin = mixin$1(GLOBAL_MIXIN);
if (globalMixin && !skipAnonymous) {
for (var i in globalMixin) {
if (globalMixin.hasOwnProperty(i)) {
this$1.mixin(globalMixin[i]);
}
}
}
if (impl.fn) {
impl.fn.call(this, opts);
}
if (!skipAnonymous) {
this.trigger('before-mount');
}
// parse layout after init. fn may calculate args for nested custom tags
parseExpressions.apply(this, [dom, expressions, isAnonymous]);
this.update(item);
if (!isAnonymous) {
while (dom.firstChild) {
root.appendChild(dom.firstChild);
}
}
defineProperty(this, 'root', root);
defineProperty(this, 'isMounted', true);
if (skipAnonymous) {
return;
}
// if it's not a child tag we can trigger its mount event
if (!this.parent) {
this.trigger('mount');
}
// otherwise we need to wait that the parent "mount" or "updated" event gets triggered
else {
var p = getImmediateCustomParentTag(this.parent);
p.one(!p.isMounted ? 'mount' : 'updated', function () {
this$1.trigger('mount');
});
}
return this;
}.bind(this));
/**
* Unmount the tag instance
* @param { Boolean } mustKeepRoot - if it's true the root node will not be removed
* @returns { Tag } the current tag instance
*/
defineProperty(this, 'unmount', function tagUnmount(mustKeepRoot) {
var this$1 = this;
var el = this.root,
p = el.parentNode,
ptag,
tagIndex = __TAGS_CACHE.indexOf(this);
if (!skipAnonymous) {
this.trigger('before-unmount');
}
// clear all attributes coming from the mounted tag
walkAttrs(impl.attrs, function (name) {
if (startsWith(name, ATTRS_PREFIX)) {
name = name.slice(ATTRS_PREFIX.length);
}
remAttr(root, name);
});
// remove all the event listeners
this.__.listeners.forEach(function (dom) {
Object.keys(dom[RIOT_EVENTS_KEY]).forEach(function (eventName) {
dom.removeEventListener(eventName, dom[RIOT_EVENTS_KEY][eventName]);
});
});
// remove this tag instance from the global virtualDom variable
if (tagIndex !== -1) {
__TAGS_CACHE.splice(tagIndex, 1);
}
if (p || isVirtual) {
if (parent) {
ptag = getImmediateCustomParentTag(parent);
if (isVirtual) {
Object.keys(this.tags).forEach(function (tagName) {
arrayishRemove(ptag.tags, tagName, this$1.tags[tagName]);
});
} else {
arrayishRemove(ptag.tags, tagName, this);
if (parent !== ptag) // remove from _parent too
{
arrayishRemove(parent.tags, tagName, this);
}
}
} else {
// remove the tag contents
setInnerHTML(el, '');
}
if (p && !mustKeepRoot) {
p.removeChild(el);
}
}
if (this.__.virts) {
each(this.__.virts, function (v) {
if (v.parentNode) {
v.parentNode.removeChild(v);
}
});
}
// allow expressions to unmount themselves
unmountAll(expressions);
each(instAttrs, function (a) {
return a.expr && a.expr.unmount && a.expr.unmount();
});
// custom internal unmount function to avoid relying on the observable
if (this.__.onUnmount) {
this.__.onUnmount();
}
if (!skipAnonymous) {
this.trigger('unmount');
this.off('*');
}
defineProperty(this, 'isMounted', false);
delete this.root._tag;
return this;
}.bind(this));
}
/**
* Detect the tag implementation by a DOM node
* @param { Object } dom - DOM node we need to parse to get its tag implementation
* @returns { Object } it returns an object containing the implementation of a custom tag (template and boot function)
*/
function getTag(dom) {
return dom.tagName && __TAG_IMPL[getAttr(dom, IS_DIRECTIVE) || getAttr(dom, IS_DIRECTIVE) || dom.tagName.toLowerCase()];
}
/**
* Inherit properties from a target tag instance
* @this Tag
* @param { Tag } target - tag where we will inherit properties
* @param { Array } propsInSyncWithParent - array of properties to sync with the target
*/
function inheritFrom(target, propsInSyncWithParent) {
var this$1 = this;
each(Object.keys(target), function (k) {
// some properties must be always in sync with the parent tag
var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k);
if (isUndefined(this$1[k]) || mustSync) {
// track the property to keep in sync
// so we can keep it updated
if (!mustSync) {
propsInSyncWithParent.push(k);
}
this$1[k] = target[k];
}
});
}
/**
* Move the position of a custom tag in its parent tag
* @this Tag
* @param { String } tagName - key where the tag was stored
* @param { Number } newPos - index where the new tag will be stored
*/
function moveChildTag(tagName, newPos) {
var parent = this.parent,
tags;
// no parent no move
if (!parent) {
return;
}
tags = parent.tags[tagName];
if (isArray(tags)) {
tags.splice(newPos, 0, tags.splice(tags.indexOf(this), 1)[0]);
} else {
arrayishAdd(parent.tags, tagName, this);
}
}
/**
* Create a new child tag including it correctly into its parent
* @param { Object } child - child tag implementation
* @param { Object } opts - tag options containing the DOM node where the tag will be mounted
* @param { String } innerHTML - inner html of the child node
* @param { Object } parent - instance of the parent tag including the child custom tag
* @returns { Object } instance of the new child tag just created
*/
function initChildTag(child, opts, innerHTML, parent) {
var tag = new Tag$1(child, opts, innerHTML),
tagName = opts.tagName || getTagName(opts.root, true),
ptag = getImmediateCustomParentTag(parent);
// fix for the parent attribute in the looped elements
defineProperty(tag, 'parent', ptag);
// store the real parent tag
// in some cases this could be different from the custom parent tag
// for example in nested loops
tag.__.parent = parent;
// add this tag to the custom parent tag
arrayishAdd(ptag.tags, tagName, tag);
// and also to the real parent tag
if (ptag !== parent) {
arrayishAdd(parent.tags, tagName, tag);
}
// empty the child node once we got its template
// to avoid that its children get compiled multiple times
opts.root.innerHTML = '';
return tag;
}
/**
* Loop backward all the parents tree to detect the first custom parent tag
* @param { Object } tag - a Tag instance
* @returns { Object } the instance of the first custom parent tag found
*/
function getImmediateCustomParentTag(tag) {
var ptag = tag;
while (ptag.__.isAnonymous) {
if (!ptag.parent) {
break;
}
ptag = ptag.parent;
}
return ptag;
}
/**
* Trigger the unmount method on all the expressions
* @param { Array } expressions - DOM expressions
*/
function unmountAll(expressions) {
each(expressions, function (expr) {
if (expr instanceof Tag$1) {
expr.unmount(true);
} else if (expr.tagName) {
expr.tag.unmount(true);
} else if (expr.unmount) {
expr.unmount();
}
});
}
/**
* Get the tag name of any DOM node
* @param { Object } dom - DOM node we want to parse
* @param { Boolean } skipDataIs - hack to ignore the data-is attribute when attaching to parent
* @returns { String } name to identify this dom node in riot
*/
function getTagName(dom, skipDataIs) {
var child = getTag(dom),
namedTag = !skipDataIs && getAttr(dom, IS_DIRECTIVE);
return namedTag && !tmpl.hasExpr(namedTag) ? namedTag : child ? child.name : dom.tagName.toLowerCase();
}
/**
* With this function we avoid that the internal Tag methods get overridden
* @param { Object } data - options we want to use to extend the tag instance
* @returns { Object } clean object without containing the riot internal reserved words
*/
function cleanUpData(data) {
if (!(data instanceof Tag$1) && !(data && isFunction(data.trigger))) {
return data;
}
var o = {};
for (var key in data) {
if (!RE_RESERVED_NAMES.test(key)) {
o[key] = data[key];
}
}
return o;
}
/**
* Set the property of an object for a given key. If something already
* exists there, then it becomes an array containing both the old and new value.
* @param { Object } obj - object on which to set the property
* @param { String } key - property name
* @param { Object } value - the value of the property to be set
* @param { Boolean } ensureArray - ensure that the property remains an array
* @param { Number } index - add the new item in a certain array position
*/
function arrayishAdd(obj, key, value, ensureArray, index) {
var dest = obj[key];
var isArr = isArray(dest);
var hasIndex = !isUndefined(index);
if (dest && dest === value) {
return;
}
// if the key was never set, set it once
if (!dest && ensureArray) {
obj[key] = [value];
} else if (!dest) {
obj[key] = value;
}
// if it was an array and not yet set
else {
if (isArr) {
var oldIndex = dest.indexOf(value);
// this item never changed its position
if (oldIndex === index) {
return;
}
// remove the item from its old position
if (oldIndex !== -1) {
dest.splice(oldIndex, 1);
}
// move or add the item
if (hasIndex) {
dest.splice(index, 0, value);
} else {
dest.push(value);
}
} else {
obj[key] = [dest, value];
}
}
}
/**
* Removes an item from an object at a given key. If the key points to an array,
* then the item is just removed from the array.
* @param { Object } obj - object on which to remove the property
* @param { String } key - property name
* @param { Object } value - the value of the property to be removed
* @param { Boolean } ensureArray - ensure that the property remains an array
*/
function arrayishRemove(obj, key, value, ensureArray) {
if (isArray(obj[key])) {
var index = obj[key].indexOf(value);
if (index !== -1) {
obj[key].splice(index, 1);
}
if (!obj[key].length) {
delete obj[key];
} else if (obj[key].length === 1 && !ensureArray) {
obj[key] = obj[key][0];
}
} else {
delete obj[key];
} // otherwise just delete the key
}
/**
* Mount a tag creating new Tag instance
* @param { Object } root - dom node where the tag will be mounted
* @param { String } tagName - name of the riot tag we want to mount
* @param { Object } opts - options to pass to the Tag instance
* @param { Object } ctx - optional context that will be used to extend an existing class ( used in riot.Tag )
* @returns { Tag } a new Tag instance
*/
function mountTo(root, tagName, opts, ctx) {
var impl = __TAG_IMPL[tagName],
implClass = __TAG_IMPL[tagName].class,
tag = ctx || (implClass ? Object.create(implClass.prototype) : {}),
// cache the inner HTML to fix #855
innerHTML = root._innerHTML = root._innerHTML || root.innerHTML;
// clear the inner html
root.innerHTML = '';
var conf = extend({ root: root, opts: opts }, { parent: opts ? opts.parent : null });
if (impl && root) {
Tag$1.apply(tag, [impl, conf, innerHTML]);
}
if (tag && tag.mount) {
tag.mount(true);
// add this tag to the virtualDom variable
if (!contains(__TAGS_CACHE, tag)) {
__TAGS_CACHE.push(tag);
}
}
return tag;
}
/**
* makes a tag virtual and replaces a reference in the dom
* @this Tag
* @param { tag } the tag to make virtual
* @param { ref } the dom reference location
*/
function makeReplaceVirtual(tag, ref) {
var frag = createFrag();
makeVirtual.call(tag, frag);
ref.parentNode.replaceChild(frag, ref);
}
/**
* Adds the elements for a virtual tag
* @this Tag
* @param { Node } src - the node that will do the inserting or appending
* @param { Tag } target - only if inserting, insert before this tag's first child
*/
function makeVirtual(src, target) {
var this$1 = this;
var head = createDOMPlaceholder(),
tail = createDOMPlaceholder(),
frag = createFrag(),
sib,
el;
this.root.insertBefore(head, this.root.firstChild);
this.root.appendChild(tail);
this.__.head = el = head;
this.__.tail = tail;
while (el) {
sib = el.nextSibling;
frag.appendChild(el);
this$1.__.virts.push(el); // hold for unmounting
el = sib;
}
if (target) {
src.insertBefore(frag, target.__.head);
} else {
src.appendChild(frag);
}
}
/**
* Move virtual tag and all child nodes
* @this Tag
* @param { Node } src - the node that will do the inserting
* @param { Tag } target - insert before this tag's first child
*/
function moveVirtual(src, target) {
var this$1 = this;
var el = this.__.head,
frag = createFrag(),
sib;
while (el) {
sib = el.nextSibling;
frag.appendChild(el);
el = sib;
if (el === this$1.__.tail) {
frag.appendChild(el);
src.insertBefore(frag, target.__.head);
break;
}
}
}
/**
* Get selectors for tags
* @param { Array } tags - tag names to select
* @returns { String } selector
*/
function selectTags(tags) {
// select all tags
if (!tags) {
var keys = Object.keys(__TAG_IMPL);
return keys + selectTags(keys);
}
return tags.filter(function (t) {
return !/[^-\w]/.test(t);
}).reduce(function (list, t) {
var name = t.trim().toLowerCase();
return list + ",[" + IS_DIRECTIVE + "=\"" + name + "\"]";
}, '');
}
var tags = Object.freeze({
getTag: getTag,
inheritFrom: inheritFrom,
moveChildTag: moveChildTag,
initChildTag: initChildTag,
getImmediateCustomParentTag: getImmediateCustomParentTag,
unmountAll: unmountAll,
getTagName: getTagName,
cleanUpData: cleanUpData,
arrayishAdd: arrayishAdd,
arrayishRemove: arrayishRemove,
mountTo: mountTo,
makeReplaceVirtual: makeReplaceVirtual,
makeVirtual: makeVirtual,
moveVirtual: moveVirtual,
selectTags: selectTags
});
/**
* Riot public api
*/
var settings = settings$1;
var util = {
tmpl: tmpl,
brackets: brackets,
styleManager: styleManager,
vdom: __TAGS_CACHE,
styleNode: styleManager.styleNode,
// export the riot internal utils as well
dom: dom,
check: check,
misc: misc,
tags: tags
};
// export the core props/methods
var Tag$$1 = Tag$2;
var tag$$1 = tag$1;
var tag2$$1 = tag2$1;
var mount$$1 = mount$1;
var mixin$$1 = mixin$1;
var update$$1 = update$1;
var unregister$$1 = unregister$1;
var version$$1 = version$1;
var observable = observable$1;
var riot$1 = extend({}, core, {
observable: observable$1,
settings: settings,
util: util
});
exports.settings = settings;
exports.util = util;
exports.Tag = Tag$$1;
exports.tag = tag$$1;
exports.tag2 = tag2$$1;
exports.mount = mount$$1;
exports.mixin = mixin$$1;
exports.update = update$$1;
exports.unregister = unregister$$1;
exports.version = version$$1;
exports.observable = observable;
exports['default'] = riot$1;
Object.defineProperty(exports, '__esModule', { value: true });
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
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; };
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = __webpack_require__(6);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
/**
* Colors.
*/
exports.colors = ['lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style ||
// is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window && window.console && (console.firebug || console.exception && console.table) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
// double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch (e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch (e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
/***/ }),
/* 5 */
/***/ (function(module, exports) {
'use strict';
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = __webpack_require__(7);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0,
i;
for (i in namespace) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/***/ }),
/* 7 */
/***/ (function(module, exports) {
'use strict';
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; };
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val === 'undefined' ? 'undefined' : _typeof(val);
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val));
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 10000) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(9);
__webpack_require__(68);
__webpack_require__(72);
__webpack_require__(74);
__webpack_require__(99);
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(10);
__webpack_require__(54);
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(11);
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('view-manager', '', '', '', function(opts) {
"use strict";
var _this2 = this;
var Promise = __webpack_require__(12);
var $ = __webpack_require__(1);
var defaultValue = __webpack_require__(50);
Object.assign(this, {
currentView: null,
viewPrefix: defaultValue(opts.viewPrefix, "uikit-view"),
switchView: function switchView(viewName, locals) {
if (this.currentView != null) {
this.currentView.unmount(); // FIXME: Do we need more cleanup here?
}
var viewElementName = this.viewPrefix + "-" + viewName;
var newViewElement = $("<" + viewElementName + ">").appendTo(this.root);
this.currentView = riot.mount(newViewElement[0], viewElementName, locals)[0];
this.trigger("switched");
},
navigate: function navigate(method, uri) {
var _this = this;
var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return Promise.try(function () {
_this.trigger("navigating");
return opts.router.handle(method, uri, data);
}).then(function (response) {
response.actions.forEach(function (action) {
if (action.type === "render") {
_this.switchView(action.viewName, action.locals);
}
// MARKER: Emit notifications!
});
_this.trigger("navigated");
});
}
});
["get", "post", "put", "delete", "patch", "head"].forEach(function (method) {
_this2[method] = _this2.navigate.bind(_this2, method);
});
// FIXME: Get rid of jQuery here?
$(this.root).on("submit", "form:not(.no-intercept)", function (event) {
Promise.try(function () {
var form = event.target;
event.preventDefault();
event.stopPropagation();
return _this2.navigate(form.method, form.action, new FormData(form), {
multipart: form.enctype === "multipart/form-data"
});
});
});
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try {
if (Promise === bluebird) Promise = old;
} catch (e) {}
return bluebird;
}
var bluebird = __webpack_require__(13)();
bluebird.noConflict = noConflict;
module.exports = bluebird;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
module.exports = function () {
var makeSelfResolutionError = function makeSelfResolutionError() {
return new TypeError("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n");
};
var reflectHandler = function reflectHandler() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function apiRejection(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = __webpack_require__(14);
var getDomain;
if (util.isNode) {
getDomain = function getDomain() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function getDomain() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = __webpack_require__(15);
var Async = __webpack_require__(16);
var async = new Async();
es5.defineProperty(Promise, "_async", { value: async });
var errors = __webpack_require__(21);
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function INTERNAL() {};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = __webpack_require__(22)(Promise, INTERNAL);
var PromiseArray = __webpack_require__(23)(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable);
var Context = __webpack_require__(24)(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = __webpack_require__(25)(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext = __webpack_require__(26)(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = __webpack_require__(27)(NEXT_FILTER);
var nodebackForPromise = __webpack_require__(28);
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0,
i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " + "expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler, reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise = this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function (fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function (fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (didFulfill, didReject, _, receiver, internalData) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined && (this._bitField & 2097152) !== 0) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler,
value,
settler = target._settlePromiseCtx;
if ((bitField & 33554432) !== 0) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if ((bitField & 16777216) !== 0) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler : typeof handler === "function" && util.domainBind(domain, handler),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = this._bitField & -65536 | len & 65535;
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function () {
this._bitField = this._bitField & ~65536;
};
Promise.prototype._setCancelled = function () {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function () {
this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function () {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function () {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (fulfill, reject, promise, receiver, domain) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] = domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function (value, shouldBind) {
if ((this._bitField & 117506048) !== 0) return;
if (value === this) return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if ((bitField & 50397184) === 0) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if ((bitField & 33554432) !== 0) {
this._fulfill(promise._value());
} else if ((bitField & 16777216) !== 0) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback = function (reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " + util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function (value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (handler, receiver, value, promise) {
var bitField = promise._bitField;
if ((bitField & 65536) !== 0) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if ((bitField & 65536) !== 0) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function () {
var ret = this;
while (ret._isFollowing()) {
ret = ret._followee();
}return ret;
};
Promise.prototype._followee = function () {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function (promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function (promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = (bitField & 134217728) !== 0;
if ((bitField & 65536) !== 0) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if ((bitField & 33554432) !== 0) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if ((bitField & 33554432) !== 0) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function (ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function (ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function (handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function (index) {
var base = index * 4 - 4;
this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if ((bitField & 117506048) >>> 16) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if ((bitField & 134217728) !== 0) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if ((bitField & 117506048) >>> 16) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = bitField & 65535;
if (len > 0) {
if ((bitField & 16842752) !== 0) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function () {
var bitField = this._bitField;
if ((bitField & 33554432) !== 0) {
return this._rejectionHandler0;
} else if ((bitField & 16777216) !== 0) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {
this.promise._resolveCallback(v);
}
function deferReject(v) {
this.promise._rejectCallback(v, false);
}
Promise.defer = Promise.pending = function () {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError);
__webpack_require__(29)(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug);
__webpack_require__(30)(Promise, INTERNAL, tryConvertToPromise, debug);
__webpack_require__(31)(Promise, PromiseArray, apiRejection, debug);
__webpack_require__(32)(Promise);
__webpack_require__(33)(Promise);
__webpack_require__(34)(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.5.0";
__webpack_require__(35)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
__webpack_require__(36)(Promise);
__webpack_require__(37)(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
__webpack_require__(38)(Promise, INTERNAL, debug);
__webpack_require__(39)(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
__webpack_require__(40)(Promise);
__webpack_require__(41)(Promise, INTERNAL);
__webpack_require__(42)(Promise, PromiseArray, tryConvertToPromise, apiRejection);
__webpack_require__(43)(Promise, INTERNAL, tryConvertToPromise, apiRejection);
__webpack_require__(44)(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
__webpack_require__(45)(Promise, PromiseArray, debug);
__webpack_require__(46)(Promise, PromiseArray, apiRejection);
__webpack_require__(47)(Promise, INTERNAL);
__webpack_require__(48)(Promise, INTERNAL);
__webpack_require__(49)(Promise);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({ a: 1 });
fillTypes({ b: 2 });
fillTypes({ c: 3 });
fillTypes(1);
fillTypes(function () {});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {"use strict";
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 es5 = __webpack_require__(15);
var canEvaluate = typeof navigator == "undefined";
var errorObj = { e: {} };
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function inherits(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length - 1) !== "$") {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false || typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" || (typeof value === "undefined" ? "undefined" : _typeof(value)) === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null ? desc.value : defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = function () {
var excludedPrototypes = [Array.prototype, Object.prototype, Function.prototype];
var isExcludedProto = function isExcludedProto(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function (obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function (obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
}();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) {
new FakeConstructor();
}return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for (var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null && (typeof obj === "undefined" ? "undefined" : _typeof(obj)) === "object" && typeof obj.message === "string" && typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
} catch (ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return e instanceof Error["__BluebirdErrorTypes__"].OperationalError || e["isOperational"] === true;
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = function () {
if (!("stack" in new Error())) {
return function (value) {
if (canAttachTrace(value)) return value;
try {
throw new Error(safeToString(value));
} catch (err) {
return err;
}
};
} else {
return function (value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
}();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function asArray(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function (v) {
return Array.from(v);
} : function (v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!(itResult = it.next()).done) {
ret.push(itResult.value);
}
return ret;
};
asArray = function asArray(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]";
var hasEnvVariables = typeof process !== "undefined" && typeof process.env !== "undefined";
function env(key) {
return hasEnvVariables ? process.env[key] : undefined;
}
function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function () {});
if ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
};
ret.isRecentNode = ret.isNode && function () {
var version = process.versions.node.split(".").map(Number);
return version[0] === 0 && version[1] > 10 || version[0] > 0;
}();
if (ret.isNode) ret.toFastProperties(process);
try {
throw new Error();
} catch (e) {
ret.lastLineError = e;
}
module.exports = ret;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(5)))
/***/ }),
/* 15 */
/***/ (function(module, exports) {
"use strict";
var isES5 = function () {
"use strict";
return this === undefined;
}();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function propertyIsWritable(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function ObjectGetDescriptor(o, key) {
return { value: o[key] };
};
var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function ObjectFreeze(obj) {
return obj;
};
var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
} catch (e) {
return proto;
}
};
var ArrayIsArray = function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
} catch (e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function propertyIsWritable() {
return true;
}
};
}
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
var firstLineError;
try {
throw new Error();
} catch (e) {
firstLineError = e;
}
var schedule = __webpack_require__(17);
var Queue = __webpack_require__(20);
var util = __webpack_require__(14);
function Async() {
this._customScheduler = false;
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule = schedule;
}
Async.prototype.setScheduler = function (fn) {
var prev = this._schedule;
this._schedule = fn;
this._customScheduler = true;
return prev;
};
Async.prototype.hasCustomScheduler = function () {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function () {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function () {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function (e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + "\n");
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function (fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function fn() {
throw arg;
};
}
if (typeof setTimeout !== "undefined") {
setTimeout(function () {
fn(arg);
}, 0);
} else try {
this._schedule(function () {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function () {
setTimeout(function () {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function () {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function (promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function () {
promise._settlePromises();
});
}
};
}
Async.prototype._drainQueue = function (queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process, setImmediate) {"use strict";
var util = __webpack_require__(14);
var schedule;
var noAsyncScheduler = function noAsyncScheduler() {
throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode ? function (fn) {
GlobalSetImmediate.call(global, fn);
} : function (fn) {
ProcessNextTick.call(process, fn);
};
} else if (typeof NativePromise === "function" && typeof NativePromise.resolve === "function") {
var nativePromise = NativePromise.resolve();
schedule = function schedule(fn) {
nativePromise.then(fn);
};
} else if (typeof MutationObserver !== "undefined" && !(typeof window !== "undefined" && window.navigator && (window.navigator.standalone || window.cordova))) {
schedule = function () {
var div = document.createElement("div");
var opts = { attributes: true };
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function () {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function scheduleToggle() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function () {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
}();
} else if (typeof setImmediate !== "undefined") {
schedule = function schedule(fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function schedule(fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(5), __webpack_require__(18).setImmediate))
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function () {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function () {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout = exports.clearInterval = function (timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function () {};
Timeout.prototype.close = function () {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function (item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function (item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function (item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout) item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(19);
exports.setImmediate = setImmediate;
exports.clearImmediate = clearImmediate;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {"use strict";
(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function registerImmediate(handle) {
process.nextTick(function () {
runIfPresent(handle);
});
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function () {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function onGlobalMessage(event) {
if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function registerImmediate(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function (event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function registerImmediate(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function registerImmediate(handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function registerImmediate(handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 68
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
})(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(5)))
/***/ }),
/* 20 */
/***/ (function(module, exports) {
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = this._front + length & this._capacity - 1;
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[j + 0 & wrapMask] = fn;
this[j + 1 & wrapMask] = receiver;
this[j + 2 & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = front + 1 & this._capacity - 1;
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = front + length & oldCapacity - 1;
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var es5 = __webpack_require__(15);
var Objectfreeze = es5.freeze;
var util = __webpack_require__(14);
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch (e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function () {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError)) return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, INTERNAL) {
var util = __webpack_require__(14);
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(ret._fulfill, ret._reject, undefined, ret, null);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) {
var util = __webpack_require__(14);
var isArray = util.isArray;
function toResolutionValue(val) {
switch (val) {
case -2:
return [];
case -3:
return {};
case -6:
return new Map();
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if ((bitField & 50397184) === 0) {
this._promise._setAsyncGuaranteed();
return values._then(init, this._reject, undefined, this, resolveValueIfEmpty);
} else if ((bitField & 33554432) !== 0) {
values = values._value();
} else if ((bitField & 16777216) !== 0) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection("expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
} else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function (values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if ((bitField & 50397184) === 0) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if ((bitField & 33554432) !== 0) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if ((bitField & 16777216) !== 0) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function () {
if (this._isResolved() || !this._promise._isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function () {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function () {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
/***/ }),
/* 24 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function () {};
Promise.prototype._pushContext = function () {};
Promise.prototype._popContext = function () {
return null;
};
Promise._peekContext = Promise.prototype._peekContext = function () {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function () {};
Context.activateLongStackTraces = function () {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function () {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function () {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {"use strict";
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; };
module.exports = function (Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = __webpack_require__(21).Warning;
var util = __webpack_require__(14);
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (false || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function () {
var target = this._target();
target._bitField = target._bitField & ~1048576 | 524288;
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function () {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function () {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & ~262144;
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & ~1048576;
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function (message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection = typeof fn === "function" ? domain === null ? fn : util.domainBind(domain, fn) : undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled = typeof fn === "function" ? domain === null ? fn : util.domainBind(domain, fn) : undefined;
};
var disableLongStackTraces = function disableLongStackTraces() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function disableLongStackTraces() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = function () {
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function (name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function (name, event) {
var domEvent = new Event(name.toLowerCase(), {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function (name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true, event);
return !util.global.dispatchEvent(domEvent);
};
}
} catch (e) {}
return function () {
return false;
};
}();
var fireGlobalEvent = function () {
if (util.isNode) {
return function () {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function () {
return false;
};
}
return function (name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
}();
function generatePromiseLifecycleEventObject(name, promise) {
return { promise: promise };
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function promiseChained(name, promise, child) {
return { promise: promise, child: child };
},
warning: function warning(name, _warning) {
return { warning: _warning };
},
unhandledRejection: function unhandledRejection(name, reason, promise) {
return { reason: reason, promise: promise };
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function activeFireEvent(name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function (opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error("cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData = cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
_propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
};
function defaultFireEvent() {
return false;
}
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function (executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) {
;
};
Promise.prototype._attachCancellationCallback = function (onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function () {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function (onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this._isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var _propagateFromFunction = bindingPropagateFrom;
function _boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) {
if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var handlerLine = "";
var creatorLine = "";
if (promiseCreated._trace) {
var traceLines = promiseCreated._trace.stack.split("\n");
var stack = cleanStack(traceLines);
for (var i = stack.length - 1; i >= 0; --i) {
var line = stack[i];
if (!nodeFramePattern.test(line)) {
var lineMatches = line.match(parseLinePattern);
if (lineMatches) {
handlerLine = "at " + lineMatches[1] + ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
}
break;
}
}
if (stack.length > 0) {
var firstUserLine = stack[0];
for (var i = 0; i < traceLines.length; ++i) {
if (traceLines[i] === firstUserLine) {
if (i > 0) {
creatorLine = "\n" + traceLines[i - 1];
}
break;
}
}
}
}
var msg = "a promise was created in a " + name + "handler " + handlerLine + "but was not returned from it, " + "see http://goo.gl/rRqMUw" + creatorLine;
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name + " is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 || i + 1 < stacks.length && stacks[i][0] === stacks[i + 1][0]) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0 && error.name != "SyntaxError") {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" || _typeof(console.log) === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " + (obj.name || "anonymous") + "]";
} else {
str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
} catch (e) {}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return "(<" + snip(str) + ">, no stack trace)";
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function shouldIgnore() {
return false;
};
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function shouldIgnore(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName && firstIndex <= info.line && info.line <= lastIndex) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function () {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length = cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function (error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function v8stackFormatter(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined && error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function shouldIgnore(line) {
return bluebirdFramePattern.test(line);
};
return function (receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try {
throw new Error();
} catch (e) {
hasStackAfterThrow = "stack" in e;
}
if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try {
throw new Error();
} catch (e) {
o.stack = e.stack;
}
Error.stackTraceLimit -= 6;
};
}
formatStack = function formatStack(stack, error) {
if (typeof stack === "string") return stack;
if (((typeof error === "undefined" ? "undefined" : _typeof(error)) === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
}([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function printWarning(message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function printWarning(message, isSoft) {
var color = isSoft ? "\x1B[33m" : "\x1B[31m";
console.warn(color + message + "\x1B[0m\n");
};
} else if (!util.isNode && typeof new Error().stack === "string") {
printWarning = function printWarning(message, isSoft) {
console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function longStackTraces() {
return config.longStackTraces;
},
warnings: function warnings() {
return config.warnings;
},
cancellation: function cancellation() {
return config.cancellation;
},
monitoring: function monitoring() {
return config.monitoring;
},
propagateFromFunction: function propagateFromFunction() {
return _propagateFromFunction;
},
boundValueFunction: function boundValueFunction() {
return _boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)))
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, tryConvertToPromise, NEXT_FILTER) {
var util = __webpack_require__(14);
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
var catchFilter = __webpack_require__(27)(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function () {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function () {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue);
if (ret === NEXT_FILTER) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise._isCancelled()) {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function (handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined);
};
Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler, 0, finallyHandler, finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if (len === 1) {
return this._passThrough(handlerOrPredicate, 1, undefined, finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0,
i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError("tapCatch statement predicate: " + "expecting an object but got " + util.classString(item)));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this), 1, undefined, finallyHandler);
}
};
return PassThroughHandlerContext;
};
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (NEXT_FILTER) {
var util = __webpack_require__(14);
var getKeys = __webpack_require__(15).keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function (e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error || item != null && item.prototype instanceof Error) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(14);
var maybeWrapAsError = util.maybeWrapAsError;
var errors = __webpack_require__(21);
var OperationalError = errors.OperationalError;
var es5 = __webpack_require__(15);
function isUntypedError(obj) {
return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function (err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0));for (var $_i = 1; $_i < $_len; ++$_i) {
args[$_i - 1] = arguments[$_i];
};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = __webpack_require__(14);
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};
/***/ }),
/* 30 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function rejectThis(_, e) {
this._reject(e);
};
var targetRejected = function targetRejected(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function bindingResolved(thisArg, context) {
if ((this._bitField & 50397184) === 0) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function bindingRejected(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & ~2097152;
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, apiRejection, debug) {
var util = __webpack_require__(14);
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function () {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function () {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function () {
return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function (canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function () {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function () {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function () {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function () {
this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function () {
return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function () {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function (onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function () {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function () {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function () {
this.cancel();
};
};
/***/ }),
/* 32 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(returner, undefined, undefined, { value: value }, undefined);
};
Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) {
return this._then(thrower, undefined, undefined, { reason: reason }, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(undefined, thrower, undefined, { reason: reason }, undefined);
} else {
var _reason = arguments[1];
var handler = function handler() {
throw _reason;
};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(undefined, returner, undefined, { value: value }, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function handler() {
return _value;
};
return this.caught(value, handler);
}
};
};
/***/ }),
/* 33 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined;
} else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function () {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function () {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function () {
return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function () {
return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function () {
return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function () {
return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function () {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function () {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function () {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function () {
return isResolved.call(this._target());
};
Promise.prototype.value = function () {
return value.call(this._target());
};
Promise.prototype.reason = function () {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function () {
return this._settledValue();
};
Promise.prototype._reason = function () {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain) {
var util = __webpack_require__(14);
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (true) {
if (canEvaluate) {
var thenCallback = function thenCallback(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function promiseSetter(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function generateHolderClass(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i + 1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode = "var promise;\n" + props.map(function (prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise, async) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.asyncNeeded = true; \n\
this.now = 0; \n\
} \n\
\n\
[TheName].prototype._callFunction = function(promise) { \n\
promise._pushContext(); \n\
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
}; \n\
\n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
if (this.asyncNeeded) { \n\
async.invoke(this._callFunction, this, promise); \n\
} else { \n\
this._callFunction(promise); \n\
} \n\
\n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise, async); \n\
";
code = code.replace(/\[TheName\]/g, name).replace(/\[TheTotal\]/g, total).replace(/\[ThePassedArguments\]/g, passedArguments).replace(/\[TheProperties\]/g, assignment).replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", "async", code)(tryCatch, errorObj, Promise, async);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function reject(reason) {
this._reject(reason);
};
}
}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (true) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if ((bitField & 50397184) === 0) {
maybePromise._then(callbacks[i], reject, undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if ((bitField & 33554432) !== 0) {
callbacks[i].call(ret, maybePromise._value(), holder);
} else if ((bitField & 16777216) !== 0) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len);for (var $_i = 0; $_i < $_len; ++$_i) {
args[$_i] = arguments[$_i];
};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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; };
module.exports = function (Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) {
var getDomain = Promise._getDomain;
var util = __webpack_require__(14);
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : util.domainBind(domain, fn);
this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null;
this._limit = limit;
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function () {
this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = index * -1 - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if ((bitField & 50397184) === 0) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if ((bitField & 33554432) !== 0) {
ret = maybePromise._value();
} else if ((bitField & 16777216) !== 0) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(new TypeError("'concurrency' must be a number but it is " + util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError("options argument must be an object but it is " + util.classString(options)));
}
}
limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function (Promise) {
var util = __webpack_require__(14);
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (true) {
var makeMethodCaller = function makeMethodCaller(methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function makeGetter(propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function getCompiled(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) {
delete cache[keys[i]];
}cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function getMethodCaller(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function getGetter(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0));for (var $_i = 1; $_i < $_len; ++$_i) {
args[$_i - 1] = arguments[$_i];
};
if (true) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = typeof propertyName === "number";
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) {
var util = __webpack_require__(14);
var TypeError = __webpack_require__(21).TypeError;
var inherits = __webpack_require__(14).inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var NULL = {};
function thrower(e) {
setTimeout(function () {
throw e;
}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise && maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection), resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower, null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return NULL;
};
Disposer.prototype.tryDispose = function (inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== NULL ? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return d != null && typeof d.resource === "function" && typeof d.tryDispose === "function";
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length - 1] = null;
}
ResourceList.prototype._resultCancelled = function () {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection("you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource = maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources).then(function (inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function () {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & ~131072;
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, INTERNAL, debug) {
var util = __webpack_require__(14);
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle) {
this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function () {
clearTimeout(this.handle);
};
var afterValue = function afterValue(value) {
return delay(+this).thenReturn(value);
};
var delay = Promise.delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function () {
ret._fulfill();
}, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
ret._captureStackTrace();
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
var afterTimeout = function afterTimeout(promise, message, parent) {
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
if (parent != null) {
parent.cancel();
}
};
function successClear(value) {
clearTimeout(this.handle);
return value;
}
function failureClear(reason) {
clearTimeout(this.handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined);
}
return ret;
};
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) {
var errors = __webpack_require__(21);
var TypeError = errors.TypeError;
var util = __webpack_require__(14);
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
if (debug.cancellation()) {
var internal = new Promise(INTERNAL);
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
this._promise = internal.lastly(function () {
return _finallyPromise;
});
internal._captureStackTrace();
internal._setOnCancel(this);
} else {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
}
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers;
this._yieldedPromise = null;
this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function () {
return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function () {
this._promise = this._generator = null;
if (debug.cancellation() && this._finallyPromise !== null) {
this._finallyPromise._fulfill();
this._finallyPromise = null;
}
};
PromiseSpawn.prototype._promiseCancelled = function () {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError("generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator, reason);
this._promise._popContext();
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator, undefined);
this._promise._popContext();
}
this._cancellationPhase = true;
this._yieldedPromise = null;
this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function (value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function (reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"]).call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function () {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver = this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._rejectCallback(result.e, false);
}
}
var value = result.value;
if (result.done === true) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._resolveCallback(value);
}
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise);
if (maybePromise === null) {
this._promiseRejected(new TypeError("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s", String(value)) + "From coroutine:\n" + this._stack.split("\n").slice(1, -7).join("\n")));
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if ((bitField & 50397184) === 0) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if ((bitField & 33554432) !== 0) {
Promise._async.invoke(this._promiseFulfilled, this, maybePromise._value());
} else if ((bitField & 16777216) !== 0) {
Promise._async.invoke(this._promiseRejected, this, maybePromise._reason());
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function (fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise) {
var util = __webpack_require__(14);
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(adapter, errorAdapter, undefined, this, nodeback);
}
return this;
};
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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; };
module.exports = function (Promise, INTERNAL) {
var THIS = {};
var util = __webpack_require__(14);
var nodebackForPromise = __webpack_require__(28);
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = __webpack_require__(21).TypeError;
var defaultSuffix = "Async";
var defaultPromisified = { __isPromisified__: true };
var noCopyProps = ["arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__"];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function defaultFilter(name) {
return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
} catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj);
if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function escapeIdentRegex(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (true) {
var switchCaseArgumentOrder = function switchCaseArgumentOrder(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for (var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for (var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function argumentSequence(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function parameterDeclaration(parameterCount) {
return util.filledRange(Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function parameterCount(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval = function makeNodePromisifiedEval(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] + ":" + generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n");
return ret;
}
var getFunctionCode = typeof callback === "string" ? "this != null ? this['" + callback + "'] : fn" : "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()).replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)(Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = function () {
return this;
}();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch (e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i += 2) {
var key = methods[i];
var fn = methods[i + 1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function () {
return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && (typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" && util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = __webpack_require__(14);
var isObject = util.isObject;
var es5 = __webpack_require__(15);
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = function () {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
}();
var entriesToMap = function entriesToMap(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, isMap ? -6 : -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n");
} else if (castValue instanceof Promise) {
ret = castValue._then(Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = __webpack_require__(14);
var raceLater = function raceLater(promise) {
return promise.then(function (array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) {
var getDomain = Promise._getDomain;
var util = __webpack_require__(14);
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : util.domainBind(domain, fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
if (_each === INTERNAL) {
this._eachValues = Array(this._length);
} else if (_each === 0) {
this._eachValues = null;
} else {
this._eachValues = undefined;
}
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function (accum) {
if (this._eachValues !== undefined && this._eachValues !== null && accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function (value) {
if (this._eachValues !== null) {
this._eachValues.push(value);
}
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function () {};
ReductionPromiseArray.prototype._resolveEmptyArray = function () {
this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function (value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function (sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise);
return ret;
}
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = __webpack_require__(14);
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (Promise, PromiseArray, apiRejection) {
var util = __webpack_require__(14);
var RangeError = __webpack_require__(21).RangeError;
var AggregateError = __webpack_require__(21).AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function () {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
/***/ }),
/* 47 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
/***/ }),
/* 48 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};
/***/ }),
/* 49 */
/***/ (function(module, exports) {
"use strict";
module.exports = function (Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(51);
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var promiseTry = __webpack_require__(52);
function evaluateValue(value) {
if (typeof value === "function") {
return value();
} else {
return value;
}
}
function maybeEvaluateValue(value, evaluate) {
if (evaluate === true) {
return evaluateValue(value);
} else {
return value;
}
}
function defaultValue(value, fallbackValue) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
value = maybeEvaluateValue(value, options.evaluate);
if (value != null) {
return value;
} else {
return maybeEvaluateValue(fallbackValue, options.evaluate);
}
}
defaultValue.async = function defaultAsyncValue(value, fallbackValue) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
return promiseTry(function () {
return maybeEvaluateValue(value, options.evaluate);
}).then(function (resultValue) {
if (resultValue != null) {
return resultValue;
} else {
return maybeEvaluateValue(fallbackValue, options.evaluate);
}
});
};
module.exports = defaultValue;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(53);
/***/ }),
/* 53 */
/***/ (function(module, exports) {
'use strict';
module.exports = function promiseTry(func) {
return new Promise(function (resolve, reject) {
resolve(func());
});
};
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('window', '<div class="wrapper {focused: focused, dragged: dragged}"> <div class="title"> <div class="title-inner">{windowTitle}</div> <div class="close"><a href="#">X</a></div> </div> <div class="outer"> <div class="inner-wrapper"> <div class="inner"> <view-manager router="{opts.router}" view-prefix="openng-view"></view-manager> </div> </div> <div class="resizer" show="{opts.resizable}"></div> </div> </div>', 'window .noscroll,[data-is="window"] .noscroll{ overflow-x: hidden !important; overflow-y: hidden !important; } window .wrapper,[data-is="window"] .wrapper{ position: absolute; } window .title,[data-is="window"] .title{ -webkit-box-shadow: 5px 5px 10px #1a1a1a; -moz-box-shadow: 5px 5px 10px #1a1a1a; box-shadow: 5px 5px 10px #1a1a1a; position: absolute; z-index: 2; left: 0px; right: 0px; top: 0px; cursor: default; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; border-top-left-radius: 10px; border-top-right-radius: 10px; height: 16px; color: white; font-size: 14px; font-weight: bold; padding: 4px; padding-left: 7px; border-top: 1px solid #959595; border-right: 1px solid #959595; border-left: 1px solid #959595; background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #525252), color-stop(1, #91acbe)); background-image: -moz-linear-gradient(center bottom, #525252 0%, #91acbe 100%); filter: alpha(opacity=95); opacity: 0.95; } window .outer,[data-is="window"] .outer{ -webkit-box-shadow: 5px 5px 10px #1a1a1a; -moz-box-shadow: 5px 5px 10px #1a1a1a; box-shadow: 5px 5px 10px #1a1a1a; position: absolute; z-index: 3; left: 0px; right: 0px; bottom: 0px; font-size: 13px; top: 25px; border-bottom: 1px solid gray; border-right: 1px solid gray; border-left: 1px solid gray; background-color: #F7F7F0; filter: alpha(opacity=95); opacity: 0.95; } window .inner-wrapper,[data-is="window"] .inner-wrapper{ position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; overflow-y: auto; overflow-x: auto; } window .inner,[data-is="window"] .inner{ padding: 7px; } window .close,[data-is="window"] .close{ float: right; } window .close a,[data-is="window"] .close a{ position: absolute; right: 3px; top: 2px; display: block; padding: 1px 4px; text-decoration: none; font-size: 12px; border-radius: 5px; color: white; border: 1px solid #014D8C; } window .close a:hover,[data-is="window"] .close a:hover{ background-color: #014D8C; border: 1px solid white; } window .resizer,[data-is="window"] .resizer{ position: absolute; width: 12px; height: 12px; bottom: -6px; right: -6px; cursor: se-resize; } window .focused .title,[data-is="window"] .focused .title{ border-top: 1px solid #6262FF; border-right: 1px solid #6262FF; border-left: 1px solid #6262FF; background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #0057b3), color-stop(1, #0099ff)); background-image: -moz-linear-gradient(center bottom, #0057b3 0%, #0099ff 100%); filter: alpha(opacity=85); opacity: 0.85; } window .dragged .title,[data-is="window"] .dragged .title{ -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background-color: #0070D5; background-image: none; } window .dragged .outer,[data-is="window"] .dragged .outer{ -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; background: none; } window .dragged .inner,[data-is="window"] .dragged .inner{ visibility: hidden; } window .resized,[data-is="window"] .resized{ cursor: default; user-select: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -webkit-touch-callout: none; }', '', function(opts) {
"use strict";
var _this = this;
var $ = __webpack_require__(1);
var debounce = __webpack_require__(55);
var query = __webpack_require__(57);
__webpack_require__(65)($);
this.mixin(query.mixin);
this.mixin(__webpack_require__(67));
Object.assign(this, {
dragged: false,
focused: false,
resized: false,
width: parseInt(opts.width),
height: parseInt(opts.height),
windowTitle: opts.windowTitle,
x: parseInt(opts.x),
y: parseInt(opts.y),
z: parseInt(opts.z),
focus: function focus() {
_this.trigger("focused");
_this.change({
focused: true
});
},
defocus: function defocus() {
_this.trigger("defocused");
_this.change({
focused: false
});
},
setZIndex: function setZIndex(index) {
_this.change({
z: index
});
},
setSize: function setSize(width, height) {
_this.change({
width: width,
height: height
});
},
setWidth: function setWidth(width) {
_this.change({
width: width
});
},
setHeight: function setHeight(height) {
_this.change({
height: height
});
},
setTitle: function setTitle(title) {
_this.change({
windowTitle: title
});
},
reportClose: function reportClose() {
_this.trigger("closing");
},
_handleMouseDown: function _handleMouseDown(event) {
_this.focus();
}
});
var updatePosition = function updatePosition() {
$(_this.queryOne("//.wrapper")).css({
left: _this.x + "px",
top: _this.y + "px",
width: _this.width + "px",
height: _this.height + "px",
zIndex: _this.z
});
};
this.on("updated", function () {
updatePosition();
});
this.on("mount", function () {
var viewManager = _this.queryOne("view-manager");
var resizeHandle = $(_this.queryOne("//.resizer"));
var titleBar = $(_this.queryOne("//.title"));
var closeButton = $(_this.queryOne("//.close"));
if (opts.url != null) {
viewManager.get(opts.url);
}
viewManager.on("switched", function () {
query(viewManager.currentView, "window-meta").forEach(function (windowMeta) {
if (windowMeta.windowTitle != null) {
_this.setTitle(windowMeta.windowTitle);
}
if (windowMeta.requestedWidth != null) {
_this.setWidth(windowMeta.requestedWidth);
}
if (windowMeta.requestedHeight != null) {
_this.setHeight(windowMeta.requestedHeight);
}
});
});
closeButton.on("click", function (event) {
event.stopPropagation();
event.preventDefault;
_this.trigger("requestClose");
});
var startWidth = void 0,
startHeight = void 0;
resizeHandle.draggable();
resizeHandle.on("draggable:start", function (event) {
startWidth = _this.width;
startHeight = _this.height;
_this.change({
resized: true
});
});
resizeHandle.on("draggable:end", function (event) {
_this.change({
resized: false
});
});
resizeHandle.on("draggable:move", function (event, data) {
_this.change({
width: startWidth + data.offsetX,
height: startHeight + data.offsetY
});
});
var startX = void 0,
startY = void 0;
titleBar.draggable();
titleBar.on("draggable:start", function (event) {
startX = _this.x;
startY = _this.y;
_this.change({
dragged: true
});
});
titleBar.on("draggable:end", function (event) {
_this.change({
dragged: false
});
});
titleBar.on("draggable:move", function (event, data) {
_this.change({
x: startX + data.offsetX,
y: startY + data.offsetY
});
});
$(_this.queryOne("//.wrapper")).on("mousedown", function () {
_this._handleMouseDown();
});
updatePosition();
});
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
/**
* Module dependencies.
*/
var now = __webpack_require__(56);
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
*
* @source underscore.js
* @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
* @param {Function} function to wrap
* @param {Number} timeout in ms (`100`)
* @param {Boolean} whether to execute at the beginning (`false`)
* @api public
*/
module.exports = function debounce(func, wait, immediate) {
var timeout, args, context, timestamp, result;
if (null == wait) wait = 100;
function later() {
var last = now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function debounced() {
context = this;
args = arguments;
timestamp = now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
/***/ }),
/* 56 */
/***/ (function(module, exports) {
"use strict";
module.exports = Date.now || now;
function now() {
return new Date().getTime();
}
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(58);
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var _typeof2 = 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 _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var dedupe = __webpack_require__(59);
var queryParser = __webpack_require__(61);
var flatten = __webpack_require__(62);
var tagQueries = __webpack_require__(63);
function ensureArray(item) {
if (Array.isArray(item)) {
return item;
} else if (item == null) {
return [];
} else {
return [item];
}
}
function recurseTags(tag) {
var allTags = [tag];
Object.keys(tag.tags).forEach(function (tagType) {
ensureArray(tag.tags[tagType]).forEach(function (subTag) {
allTags = allTags.concat(recurseTags(subTag));
});
});
return allTags;
}
function createQuery(query) {
var _queryParser$parse = queryParser.parse(query);
var riotQuery = _queryParser$parse.riotQuery;
var domQuery = _queryParser$parse.domQuery;
var tagObtainer = void 0;
if (riotQuery != null) {
(function () {
var flattenedQueries = flatten(riotQuery);
tagQueries(flattenedQueries);
tagObtainer = function tagObtainer(tag) {
var results = [];
flattenedQueries.forEach(function (subQuery) {
var lastFound = [tag];
subQuery.forEach(function (segment) {
var nextLastFound = [];
lastFound.forEach(function (subTag) {
//console.log("subtag", subQuery, segment, subTag);
var found = void 0;
if (segment.type === "identifier") {
found = ensureArray(subTag.tags[segment.value]);
} else if (segment.type === "wildcard") {
found = recurseTags(subTag);
}
if (found.length > 0) {
nextLastFound = nextLastFound.concat(found);
}
});
lastFound = nextLastFound;
});
results = results.concat(lastFound);
});
return dedupe(results, function (result) {
return result._riot_id;
});
};
})();
} else {
tagObtainer = function tagObtainer(tag) {
return [tag];
};
}
return function traverse(tag) {
var riotResults = tagObtainer(tag);
if (domQuery == null) {
return riotResults;
} else {
var _ret2 = function () {
var domElements = [];
riotResults.forEach(function (foundTag) {
domElements = domElements.concat(Array.from(foundTag.root.querySelectorAll(domQuery)));
});
return {
v: domElements
};
}();
if ((typeof _ret2 === "undefined" ? "undefined" : _typeof(_ret2)) === "object") return _ret2.v;
}
};
}
var queryCache = {};
function query(tag, queryString) {
if (queryCache[queryString] == null) {
queryCache[queryString] = createQuery(queryString);
}
// TODO: DOM traversal
return queryCache[queryString](tag);
}
query.one = function queryOne(tag, queryString) {
var results = query(tag, queryString);
if (results.length === 0) {
throw new Error("No matches found for query " + queryString);
} else {
return results[0];
}
};
/* For use with `riot.mixin(query.mixin)`: */
query.mixin = {
init: function init() {
this.query = query.bind(null, this);
this.queryOne = query.one.bind(null, this);
}
};
module.exports = query;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var sigmund = __webpack_require__(60);
function dedupe(client, hasher) {
hasher = hasher || sigmund;
var clone = [];
var lookup = {};
for (var i = 0; i < client.length; i++) {
var elem = client[i];
var hashed = hasher(elem);
if (!lookup[hashed]) {
clone.push(elem);
lookup[hashed] = true;
}
}
return clone;
}
module.exports = dedupe;
/***/ }),
/* 60 */
/***/ (function(module, exports) {
'use strict';
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; };
module.exports = sigmund;
function sigmund(subject, maxSessions) {
maxSessions = maxSessions || 10;
var notes = [];
var analysis = '';
var RE = RegExp;
function psychoAnalyze(subject, session) {
if (session > maxSessions) return;
if (typeof subject === 'function' || typeof subject === 'undefined') {
return;
}
if ((typeof subject === 'undefined' ? 'undefined' : _typeof(subject)) !== 'object' || !subject || subject instanceof RE) {
analysis += subject;
return;
}
if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
notes.push(subject);
analysis += '{';
Object.keys(subject).forEach(function (issue, _, __) {
// pseudo-private values. skip those.
if (issue.charAt(0) === '_') return;
var to = _typeof(subject[issue]);
if (to === 'function' || to === 'undefined') return;
analysis += issue;
psychoAnalyze(subject[issue], session + 1);
});
}
psychoAnalyze(subject, 0);
return analysis;
}
// vim: set softtabstop=4 shiftwidth=4:
/***/ }),
/* 61 */
/***/ (function(module, exports) {
"use strict";
module.exports = function () {
"use strict";
/*
* Generated by PEG.js 0.9.0.
*
* http://pegjs.org/
*/
function peg$subclass(child, parent) {
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = "SyntaxError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
function peg$parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
parser = this,
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = function peg$c0(riotQuery, domQuery) {
return combineFinal(riotQuery, domQuery);
},
peg$c1 = "/",
peg$c2 = { type: "literal", value: "/", description: "\"/\"" },
peg$c3 = function peg$c3(segment, subSegments) {
return concatRepeat(segment, subSegments, 1);
},
peg$c4 = "{",
peg$c5 = { type: "literal", value: "{", description: "\"{\"" },
peg$c6 = "}",
peg$c7 = { type: "literal", value: "}", description: "\"}\"" },
peg$c8 = function peg$c8(items) {
return { type: "group", items: items };
},
peg$c9 = ",",
peg$c10 = { type: "literal", value: ",", description: "\",\"" },
peg$c11 = function peg$c11(item, subItems) {
return concatRepeat(item, subItems, 1);
},
peg$c12 = "",
peg$c13 = function peg$c13() {
return [{ type: "empty" }];
},
peg$c14 = /^[a-z\-]/,
peg$c15 = { type: "class", value: "[a-z-]", description: "[a-z-]" },
peg$c16 = function peg$c16(identifier) {
return { type: "identifier", value: identifier.join("") };
},
peg$c17 = "**",
peg$c18 = { type: "literal", value: "**", description: "\"**\"" },
peg$c19 = function peg$c19() {
return { type: "wildcard" };
},
peg$c20 = { type: "any", description: "any character" },
peg$c21 = function peg$c21(query) {
return query.join("");
},
peg$c22 = "//",
peg$c23 = { type: "literal", value: "//", description: "\"//\"" },
peg$currPos = 0,
peg$savedPos = 0,
peg$posDetailsCache = [{ line: 1, column: 1, seenCR: false }],
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$savedPos, peg$currPos);
}
function location() {
return peg$computeLocation(peg$savedPos, peg$currPos);
}
function expected(description) {
throw peg$buildException(null, [{ type: "other", description: description }], input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos));
}
function error(message) {
throw peg$buildException(message, null, input.substring(peg$savedPos, peg$currPos), peg$computeLocation(peg$savedPos, peg$currPos));
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos],
p,
ch;
if (details) {
return details;
} else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column,
seenCR: details.seenCR
};
while (p < pos) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) {
details.line++;
}
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos),
endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column
}
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) {
return;
}
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, found, location) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function (a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) {
return ch.charCodeAt(0).toString(16).toUpperCase();
}
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\x08/g, '\\b').replace(/\t/g, '\\t').replace(/\n/g, '\\n').replace(/\f/g, '\\f').replace(/\r/g, '\\r').replace(/[\x00-\x07\x0B\x0E\x0F]/g, function (ch) {
return '\\x0' + hex(ch);
}).replace(/[\x10-\x1F\x80-\xFF]/g, function (ch) {
return '\\x' + hex(ch);
}).replace(/[\u0100-\u0FFF]/g, function (ch) {
return "\\u0" + hex(ch);
}).replace(/[\u1000-\uFFFF]/g, function (ch) {
return "\\u" + hex(ch);
});
}
var expectedDescs = new Array(expected.length),
expectedDesc,
foundDesc,
i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
if (expected !== null) {
cleanupExpected(expected);
}
return new peg$SyntaxError(message !== null ? message : buildMessage(expected, found), expected, found, location);
}
function peg$parsestart() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = peg$parseriotQuery();
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsedomQuerySuffix();
if (s2 === peg$FAILED) {
s2 = null;
}
if (s2 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c0(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parseriotQuery() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseriotQuerySegment();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s4 = peg$c1;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c2);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseriotQuerySegment();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s4 = peg$c1;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c2);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseriotQuerySegment();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c3(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parseriotQuerySegment() {
var s0;
s0 = peg$parseriotQuerySegmentSelector();
if (s0 === peg$FAILED) {
s0 = peg$parseriotQuerySegmentGroup();
}
return s0;
}
function peg$parseriotQuerySegmentGroup() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c4;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c5);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseriotQuerySegmentGroupItems();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s3 = peg$c6;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c7);
}
}
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c8(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parseriotQuerySegmentGroupItems() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parseriotQuerySegmentGroupItemsItem();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 44) {
s4 = peg$c9;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseriotQuerySegmentGroupItemsItem();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 44) {
s4 = peg$c9;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s4 !== peg$FAILED) {
s5 = peg$parseriotQuerySegmentGroupItemsItem();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c11(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parseriotQuerySegmentGroupItemsItem() {
var s0, s1;
s0 = peg$parseriotQuery();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$c12;
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c13();
}
s0 = s1;
}
return s0;
}
function peg$parseriotQuerySegmentSelector() {
var s0;
s0 = peg$parseriotQueryIdentifier();
if (s0 === peg$FAILED) {
s0 = peg$parseriotQueryWildcard();
}
return s0;
}
function peg$parseriotQueryIdentifier() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c14.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c15);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c14.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c15);
}
}
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c16(s1);
}
s0 = s1;
return s0;
}
function peg$parseriotQueryWildcard() {
var s0, s1;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c17) {
s1 = peg$c17;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c18);
}
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c19();
}
s0 = s1;
return s0;
}
function peg$parsedomQuery() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c20);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c20);
}
}
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c21(s1);
}
s0 = s1;
return s0;
}
function peg$parsedomQuerySuffix() {
var s0, s1, s2;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c22) {
s1 = peg$c22;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c23);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parsedomQuery();
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function concatRepeat(first, rest, restIndex) {
return [first].concat(rest.map(function (item) {
return item[restIndex];
}));
}
function combineFinal(riotQuery, domQuery) {
var resultObject = {
riotQuery: riotQuery
};
if (domQuery != null) {
resultObject.domQuery = domQuery[1];
}
return resultObject;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, peg$maxFailPos < input.length ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) : peg$computeLocation(peg$maxFailPos, peg$maxFailPos));
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse
};
}();
/***/ }),
/* 62 */
/***/ (function(module, exports) {
'use strict';
var _typeof2 = 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 _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
function flattenSegmentTree(stacks, segments) {
segments.forEach(function (segment) {
stacks = flattenSegment(stacks, segment);
});
return stacks;
}
function flattenSegment(stacks, segment) {
if (segment.type === "identifier" || segment.type === "wildcard") {
return stacks.map(function (stack) {
return stack.concat([segment]);
});
} else if (segment.type === "group") {
var _ret = function () {
var newStacks = [];
segment.items.forEach(function (groupItem) {
newStacks = newStacks.concat(flattenSegmentTree(stacks, groupItem));
});
return {
v: newStacks
};
}();
if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v;
} else if (segment.type === "empty") {
return stacks;
} else {
throw new Error("Unknown segment type '" + segment.type + "'");
}
}
module.exports = function (queryTree) {
return flattenSegmentTree([[]], queryTree);
};
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var format = __webpack_require__(64);
module.exports = function tagQuerySegments(queries) {
var tagMap = {};
var currentTag = 0;
queries.forEach(function (query) {
var stack = [];
query.forEach(function (segment) {
stack.push(segment);
var formatted = format(stack);
if (tagMap[formatted] == null) {
tagMap[formatted] = currentTag++;
}
segment.tag = tagMap[formatted];
});
});
};
/***/ }),
/* 64 */
/***/ (function(module, exports) {
'use strict';
module.exports = function (query) {
return query.map(function (segment) {
if (segment.type === "identifier") {
return segment.value;
} else if (segment.type === "wildcard") {
return "**";
} else {
return "?";
}
}).join("/");
};
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var debounce = __webpack_require__(55);
var defaultValue = __webpack_require__(50);
var selectable = __webpack_require__(66);
module.exports = function ($) {
selectable($);
$.fn.draggable = function () {
var _this = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var debounceInterval = defaultValue(options.debounce, 10);
this.on("mousedown", function (event) {
var startX = event.pageX;
var startY = event.pageY;
var moveHandler = debounce(function (event) {
_this.trigger("draggable:move", [{
offsetX: event.pageX - startX,
offsetY: event.pageY - startY
}]);
}, debounceInterval);
$(document).on("mousemove", moveHandler);
$(document).one("mouseup", function (event) {
$(document).off("mousemove", moveHandler);
$(document).enableSelection();
_this.trigger("draggable:end");
});
$(document).disableSelection();
_this.trigger("draggable:start");
});
};
};
/***/ }),
/* 66 */
/***/ (function(module, exports) {
'use strict';
module.exports = function ($) {
$.fn.disableSelection = function () {
return this.attr("unselectable", "on").css("user-select", "none").on("selectstart", false);
};
$.fn.enableSelection = function () {
return this.removeAttr("unselectable").css("user-select", "auto").off("selectstart", false);
};
};
/***/ }),
/* 67 */
/***/ (function(module, exports) {
'use strict';
module.exports = {
change: function change(data) {
Object.assign(this, data);
this.update();
}
};
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(69);
__webpack_require__(71);
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(70);
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('notification', '<div class="contents"> <div class="header"> <button class="close"><i class="fa fa-times"></i></button><i class="icon fa fa-{opts.notification.icon}"></i>{opts.notification.title} </div> <div class="message" if="{opts.notification.message != null}">{opts.notification.message}</div> </div>', 'notification,[data-is="notification"]{ display: block; text-align: right; } notification .close,[data-is="notification"] .close{ display: none; float: right; background: none; border: 0; padding: 1px 3px; font-size: 12px; color: #bebebe; border: 1px solid #bebebe; border-radius: 4px; } notification .close:hover,[data-is="notification"] .close:hover{ color: white; border-color: white; } notification .contents,[data-is="notification"] .contents{ text-align: left; display: inline-block; border-radius: 6px; margin-right: 19px; margin-top: 10px; padding: 9px 14px; color: white; font-size: 15px; filter: alpha(opacity=85); opacity: 0.85; width: auto; background-color: black; } notification .contents .header,[data-is="notification"] .contents .header{ margin-right: 6px; font-weight: bold; } notification .contents .header .icon,[data-is="notification"] .contents .header .icon{ font-size: 19px; margin-right: 9px !important; } notification .contents .message,[data-is="notification"] .contents .message{ margin-top: 8px; } notification.type-error .contents,[data-is="notification"].type-error .contents{ background-color: #371B1B; } notification.type-error .contents .header .icon,[data-is="notification"].type-error .contents .header .icon{ color: #FFD2D2; } notification.type-info .contents,[data-is="notification"].type-info .contents{ background-color: #2D2D2D; } notification.type-info .contents .header .icon,[data-is="notification"].type-info .contents .header .icon{ color: #CBCAFF; }', 'class="type-{opts.notification.type}"', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('notification-box', '<notification each="{notification in notifications}" notification="{notification}"></notification>', '', '', function(opts) {
"use strict";
var defaultValue = __webpack_require__(50);
Object.assign(this, {
notifications: [{
title: "Foo bar!",
//message: "Bar bar baz foo. Bar.",
type: "info",
icon: "info-circle"
}, {
title: "Whoopteedoo",
//message: "Boop boop woop whoop toop boop!",
type: "error",
icon: "exclamation-circle"
}],
add: function addNotification(title) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var notificationObject = {
title: title,
message: options.message,
type: defaultValue(options.type, "info"),
icon: options.icon,
options: options
};
this.notifications.push(notificationObject);
if (options.timeout != null) {
setTimeout(function () {
_this.remove(notificationObject);
}, options.timeout);
}
this.update();
},
remove: function removeNotification(notificationObject) {
var notificationIndex = this.notifications.indexOf(notificationObject);
// TODO: Fade/collapse animation?
if (notificationIndex !== -1) {
this.notifications.splice(notificationIndex, 1);
this.update();
}
}
});
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(73);
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('openng-view-sample', '<p>Text: {opts.text}</p>', 'openng-view-sample p { background-color: red; color: white; font-weight: bold; padding: 4px 6px; }', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(75);
__webpack_require__(82);
__webpack_require__(84);
__webpack_require__(86);
__webpack_require__(88);
__webpack_require__(90);
__webpack_require__(92);
__webpack_require__(94);
__webpack_require__(96);
__webpack_require__(98);
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(76);
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-frame', '<div class="frame-wrapper"><yield></yield> </div>', 'uikit-frame { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; }', '', function(opts) {
"use strict";
this.mixin(__webpack_require__(77));
this.mixin(__webpack_require__(80));
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var elementSize = __webpack_require__(78);
var sortDockable = __webpack_require__(79);
function px(pixels) {
return pixels + "px";
}
module.exports = {
init: function init() {
var _this = this;
var dockableAPI = {
isActive: function isActive() {
return _this.opts.dockableContainer != null;
},
stack: [],
fillElement: null,
recalculateLayout: function recalculateLayout() {
dockableAPI.stack.forEach(function (item, i) {
item.stackIndex = i;
});
var orderedStack = dockableAPI.stack.slice().sort(sortDockable);
var reservedLeft = 0;
var reservedRight = 0;
var reservedTop = 0;
var reservedBottom = 0;
orderedStack.forEach(function (item) {
var element = item.tag.root;
/* We set the positioning to absolute *before* attempting
* to obtain the element size - this way, we can be sure
* that the element won't try to stretch to its container.
* Instead, it'll be auto-sized, which is exactly what we
* want. */
element.style.position = "absolute";
var _elementSize = elementSize(element),
width = _elementSize[0],
height = _elementSize[1];
if (item.heightHint != null) {
height = item.heightHint;
}
if (item.widthHint != null) {
width = item.widthHint;
}
// FIXME: Should the following really be errors?
if ((item.side === "left" || item.side === "right") && width === 0) {
throw new Error("Cannot horizontally dock an element without a width; you may need to specify a dock-width");
} else if ((item.side === "top" || item.side === "bottom") && height === 0) {
throw new Error("Cannot vertically dock an element without a height; you may need to specify a dock-height");
}
if (item.side === "left") {
Object.assign(element.style, {
left: px(reservedLeft),
top: px(reservedTop),
bottom: px(reservedBottom)
});
delete element.style.right;
reservedLeft += width;
} else if (item.side === "right") {
Object.assign(element.style, {
right: px(reservedRight),
top: px(reservedTop),
bottom: px(reservedBottom)
});
delete element.style.left;
reservedRight += width;
} else if (item.side === "top") {
Object.assign(element.style, {
left: px(reservedLeft),
right: px(reservedRight),
top: px(reservedTop)
});
delete element.style.bottom;
reservedTop += height;
} else if (item.side === "bottom") {
Object.assign(element.style, {
left: px(reservedLeft),
right: px(reservedRight),
bottom: px(reservedBottom)
});
delete element.style.top;
reservedBottom += height;
}
});
var item = dockableAPI.fillElement;
if (item != null) {
var element = item.root;
Object.assign(element.style, {
position: "absolute",
left: px(reservedLeft),
right: px(reservedRight),
top: px(reservedTop),
bottom: px(reservedBottom)
});
}
}
};
this._uikitDockableContainer = dockableAPI;
this.on("mount", function () {
if (dockableAPI.isActive()) {
dockableAPI.recalculateLayout();
}
});
}
};
/***/ }),
/* 78 */
/***/ (function(module, exports) {
'use strict';
module.exports = getSize;
function getSize(element) {
// Handle cases where the element is not already
// attached to the DOM by briefly appending it
// to document.body, and removing it again later.
if (element === window || element === document.body) {
return [window.innerWidth, window.innerHeight];
}
if (!element.parentNode) {
var temporary = true;
document.body.appendChild(element);
}
var bounds = element.getBoundingClientRect();
var styles = getComputedStyle(element);
var height = (bounds.height | 0) + parse(styles.getPropertyValue('margin-top')) + parse(styles.getPropertyValue('margin-bottom'));
var width = (bounds.width | 0) + parse(styles.getPropertyValue('margin-left')) + parse(styles.getPropertyValue('margin-right'));
if (temporary) {
document.body.removeChild(element);
}
return [width, height];
}
function parse(prop) {
return parseFloat(prop) || 0;
}
/***/ }),
/* 79 */
/***/ (function(module, exports) {
'use strict';
module.exports = function (a, b) {
var aOrder = void 0,
bOrder = void 0;
if (a.order != null) {
aOrder = parseInt(a.order);
}
if (b.order != null) {
bOrder = parseInt(b.order);
}
if (aOrder != null && bOrder == null) {
return -1;
} else if (aOrder == null && bOrder != null) {
return 1;
} else if (aOrder != null && bOrder != null) {
if (aOrder < bOrder) {
return -1;
} else if (aOrder > bOrder) {
return 1;
} else {
return 0;
}
} else {
if (a.stackIndex < b.stackIndex) {
return -1;
} else if (a.stackIndex > b.stackIndex) {
return 1;
} else {
return 0;
}
}
};
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var inArray = __webpack_require__(81);
function findContainer(tag) {
var lastTag = tag;
var dockableContainer = void 0;
while (dockableContainer == null && lastTag != null) {
var candidate = lastTag.parent;
if (candidate != null && candidate._uikitDockableContainer != null && candidate._uikitDockableContainer.isActive()) {
dockableContainer = candidate;
} else {
lastTag = candidate;
}
}
if (dockableContainer != null) {
return dockableContainer;
} else {
// FIXME: Better error reporting?
throw new Error("Could not find a dockable container for tag");
}
}
module.exports = {
init: function init() {
if (this.opts.dock != null) {
var dockableContainer = findContainer(this);
var containerData = dockableContainer._uikitDockableContainer;
if (inArray(["bottom", "top", "left", "right"], this.opts.dock)) {
containerData.stack.push({
tag: this,
side: this.opts.dock,
order: this.opts.dockOrder,
widthHint: this.opts.dockWidth,
heightHint: this.opts.dockHeight
});
} else if (this.opts.dock === "fill") {
if (containerData.fillElement != null) {
throw new Error("There can be only one tag with a `dock` setting of `fill` within a dockable container");
} else {
containerData.fillElement = this;
}
} else {
throw new Error("Invalid `dock` property; must be one of bottom, top, left, right, fill");
}
}
}
};
/***/ }),
/* 81 */
/***/ (function(module, exports) {
/*!
* in-array <https://github.com/jonschlinkert/in-array>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT License
*/
'use strict';
module.exports = function inArray(arr, val) {
arr = arr || [];
var len = arr.length;
var i;
for (i = 0; i < len; i++) {
if (arr[i] === val) {
return true;
}
}
return false;
};
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(83);
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-toolbar', '<div><yield></yield> </div>', '', '', function(opts) {
"use strict";
this.mixin(__webpack_require__(80));
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(85);
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-button', '<button class="pure-button {confirm: opts.type === \'submit\', cancel: opts.type === \'cancel\', normal: opts.type == null}" type="{opts.type}"><i class="fa fa-{opts.icon}" if="{opts.icon != null}"></i><yield></yield> </button>', 'uikit-button button,[data-is="uikit-button"] button{ font-weight: bold; } uikit-button button.confirm,[data-is="uikit-button"] button.confirm{ background-color: #006B00; color: white; } uikit-button button.cancel,[data-is="uikit-button"] button.cancel{ background-color: #AF0000; color: white; } uikit-button button.normal,[data-is="uikit-button"] button.normal{ background-color: #1B4AB5; color: white; }', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(87);
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-form-section', '<div><yield></yield> </div>', '', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(89);
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-input-spawner', '<div><yield></yield> </div>', '', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(91);
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-input', '<label>{opts.label}</label> <input type="{opts.type}" name="{opts.name}">', 'uikit-input label,[data-is="uikit-input"] label{ margin-right: 8px; }', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(93);
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-textarea', '<div><yield></yield> </div>', '', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(95);
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('uikit-autocomplete', '<div><yield></yield> </div>', '', '', function(opts) {
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(97);
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('window-meta', '<span></span>', '', '', function(opts) {
"use strict";
Object.assign(this, {
windowTitle: opts.windowTitle,
requestedWidth: opts.requestWidth,
requestedHeight: opts.requestHeight
});
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('openng-view-node-create', '<window-meta window-title="Create new node" request-width="400" request-height="300"></window-meta> <form method="post" action="/nodes/create"> <uikit-frame dockable-container> <uikit-toolbar class="main" dock="bottom" align="right" dock-order="1"> <uikit-button type="submit" icon="check">Create</uikit-button> </uikit-toolbar> <uikit-frame class="main" dock="fill"> <uikit-form-section> <uikit-input name="name" label="Name"></uikit-input> </uikit-form-section> </uikit-frame> </uikit-frame> </form>', 'openng-view-node-create uikit-toolbar.main,[data-is="openng-view-node-create"] uikit-toolbar.main{ padding: 6px; } openng-view-node-create uikit-frame.main,[data-is="openng-view-node-create"] uikit-frame.main{ padding: 8px; }', '', function(opts) {
"use strict";
this.mixin(__webpack_require__(57).mixin);
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(riot) {
riot.tag2('app', '<window each="{windowItem in windows}" router="{parent.router}" window-title="{windowItem.title}" width="640" height="480" x="{windowItem.x}" y="{windowItem.y}" z="0" resizable="true" url="{windowItem.url}"></window> <notification-box></notification-box>', 'app notification-box,[data-is="app"] notification-box{ position: absolute; right: 0px; bottom: 32px; z-index: 2147483640; }', '', function(opts) {
"use strict";
var _this = this;
var createRouter = __webpack_require__(100);
this.mixin(__webpack_require__(121));
this.mixin(__webpack_require__(57).mixin);
this.windows = [{ title: "test one", x: 10, y: 10, url: "/?target=Foo" }, { title: "test two", x: 200, y: 200, url: "/" }, { title: "", x: 390, y: 390, url: "/nodes/create" }];
var currentZIndex = 0;
this.router = createRouter();
this.onChild("create:window", function (window) {
window.on("focused", function () {
_this.query("window").filter(function (otherWindow) {
return otherWindow !== window;
}).forEach(function (otherWindow) {
otherWindow.defocus();
});
window.setZIndex(currentZIndex++);
});
window.on("requestClose", function () {
window.reportClose();
_this.windows = _this.windows.filter(function (windowItem) {
return windowItem !== window._item;
});
_this.update();
});
window.focus();
});
});
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var Promise = __webpack_require__(12);
var stateRouter = __webpack_require__(101);
module.exports = function createRouter() {
var router = stateRouter();
router.get("/", function (req, res) {
var text = void 0;
if (req.query.target != null) {
text = req.query.target;
} else {
text = "World";
}
res.render("sample", {
text: "Hello " + text + "!"
});
});
router.get("/nodes/create", function (req, res) {
res.render("node-create");
});
router.post("/nodes/create", function (req, res) {
return Promise.try(function () {
return req.pass();
}).then(function (response) {
console.log(response.body);
});
});
return router;
};
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Promise = __webpack_require__(12);
var pathToRegexp = __webpack_require__(102);
var url = __webpack_require__(104);
var xtend = __webpack_require__(111);
var defaultValue = __webpack_require__(50);
var formDataToObject = __webpack_require__(112);
var objectToURLSearchParams = __webpack_require__(118);
var objectToFormData = __webpack_require__(120);
module.exports = function () {
var routes = [];
function addRoute(method, path, handler) {
// Mutable arguments? WTF.
var keys = [];
var regex = pathToRegexp(path, keys);
routes.push({ method: method, path: path, regex: regex, keys: keys, handler: handler });
}
function getRoute(method, path) {
var matches = void 0;
var matchingRoute = routes.find(function (route) {
return route.method === method && (matches = route.regex.exec(path));
});
if (matchingRoute == null) {
throw new Error("No matching routes found");
} else {
var params = {};
matchingRoute.keys.forEach(function (key, i) {
params[key] = matches[i + 1];
});
return {
handler: matchingRoute.handler,
params: params
};
}
}
function handle(method, uri, data) {
var handleOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
return Promise.try(function () {
// FIXME: Support relative paths?
var _url$parse = url.parse(uri, true),
pathname = _url$parse.pathname,
query = _url$parse.query;
var route = getRoute(method, pathname);
var tasks = [];
var body = void 0;
if (data instanceof FormData) {
body = formDataToObject(data);
} else if (data instanceof URLSearchParams) {
body = formDataToObject(data); // FIXME: Does this work?
} else {
body = data;
}
var req = {
path: pathname,
query: query,
body: body,
params: route.params,
pass: function pass() {
var _this = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Promise.try(function () {
var body = void 0;
if (handleOptions.multipart) {
body = objectToFormData(_this.body);
} else {
body = objectToURLSearchParams(_this.body);
}
return window.fetch(uri, Object.assign({ // FIXME: Override URI but maintain query?
method: method,
credentials: true,
body: body
}, options));
}).then(function (response) {
if (!response.ok) {
// FIXME: Is this what we want?
throw new Error("Got a non-200 response: " + response.status, { response: response });
} else {
return Promise.try(function () {
return response.json();
}).then(function (json) {
return {
status: response.status,
body: json
};
});
}
});
// FIXME: window.fetch passthrough
},
// MARKER: passActions?
passRender: function passRender(viewName) {
var _this2 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Promise.try(function () {
return _this2.pass(options.requestOptions);
}).then(function (response) {
var locals = defaultValue(options.locals, {});
var combinedLocals = xtend(locals, response.body);
res.render(viewName, combinedLocals, options.renderOptions);
});
}
};
var res = {
render: function render(viewName) {
var locals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
tasks.push({
type: "render",
viewName: viewName, locals: locals, options: options
});
},
open: function open(path) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
tasks.push({
type: "open",
path: path, options: options
});
},
close: function close() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
tasks.push({
type: "close",
options: options
});
},
notify: function notify(message) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
tasks.push({
type: "notify",
message: message, options: options
});
},
error: function error(_error) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
tasks.push({
type: "error",
error: _error, context: context
});
}
};
return Promise.try(function () {
return route.handler(req, res);
}).then(function (result) {
return {
result: result,
actions: tasks
};
});
});
}
var api = {
get: addRoute.bind(api, "get"),
post: addRoute.bind(api, "post"),
put: addRoute.bind(api, "put"),
delete: addRoute.bind(api, "delete"),
head: addRoute.bind(api, "head"),
patch: addRoute.bind(api, "patch"),
addRoute: addRoute,
handle: handle
};
return api;
};
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
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 isarray = __webpack_require__(103);
/**
* Expose `pathToRegexp`.
*/
module.exports = pathToRegexp;
module.exports.parse = parse;
module.exports.compile = compile;
module.exports.tokensToFunction = tokensToFunction;
module.exports.tokensToRegExp = tokensToRegExp;
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'].join('|'), 'g');
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse(str, options) {
var tokens = [];
var key = 0;
var index = 0;
var path = '';
var defaultDelimiter = options && options.delimiter || '/';
var res;
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0];
var escaped = res[1];
var offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue;
}
var next = str[index];
var prefix = res[2];
var name = res[3];
var capture = res[4];
var group = res[5];
var modifier = res[6];
var asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
var partial = prefix != null && next != null && next !== prefix;
var repeat = modifier === '+' || modifier === '*';
var optional = modifier === '?' || modifier === '*';
var delimiter = res[2] || defaultDelimiter;
var pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?'
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens;
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile(str, options) {
return tokensToFunction(parse(str, options));
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty(str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk(str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length);
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (_typeof(tokens[i]) === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
}
}
return function (obj, opts) {
var path = '';
var data = obj || {};
var options = opts || {};
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue;
}
var value = data[token.name];
var segment;
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix;
}
continue;
} else {
throw new TypeError('Expected "' + token.name + '" to be defined');
}
}
if (isarray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`');
}
if (value.length === 0) {
if (token.optional) {
continue;
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty');
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j]);
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`');
}
path += (j === 0 ? token.prefix : token.delimiter) + segment;
}
continue;
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value);
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"');
}
path += token.prefix + segment;
}
return path;
};
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1');
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup(group) {
return group.replace(/([=!:$\/()])/g, '\\$1');
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys(re, keys) {
re.keys = keys;
return re;
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags(options) {
return options.sensitive ? '' : 'i';
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp(path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null
});
}
}
return attachKeys(path, keys);
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp(path, keys, options) {
var parts = [];
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys);
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp(path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp(tokens, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */keys || options;
keys = [];
}
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var route = '';
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
var prefix = escapeString(token.prefix);
var capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
var delimiter = escapeString(options.delimiter || '/');
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys);
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp(path, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */keys || options;
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */keys);
}
if (isarray(path)) {
return arrayToRegexp( /** @type {!Array} */path, /** @type {!Array} */keys, options);
}
return stringToRegexp( /** @type {string} */path, /** @type {!Array} */keys, options);
}
/***/ }),
/* 103 */
/***/ (function(module, exports) {
'use strict';
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
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 punycode = __webpack_require__(105);
var util = __webpack_require__(107);
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = __webpack_require__(108);
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url();
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + (typeof url === 'undefined' ? 'undefined' : _typeof(url)));
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1) hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1) continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function () {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query && util.isObject(this.query) && Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || query && '?' + query || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function (match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function (relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function (relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol') result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift())) {}
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/',
isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/',
mustEndAbs = isRelAbs || isSourceAbs || result.host && relative.pathname,
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = relative.host || relative.host === '' ? relative.host : result.host;
result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === '';
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && srcPath.join('/').substr(-1) !== '/') {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' || srcPath[0] && srcPath[0].charAt(0) === '/';
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || result.host && srcPath.length;
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function () {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {'use strict';
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; };
/*! https://mths.be/punycode v1.3.2 by @mathias */
;(function (root) {
/** Detect free variables */
var freeExports = ( false ? 'undefined' : _typeof(exports)) == 'object' && exports && !exports.nodeType && exports;
var freeModule = ( false ? 'undefined' : _typeof(module)) == 'object' && module && !module.nodeType && module;
var freeGlobal = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647,
// aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128,
// 0x80
delimiter = '-',
// '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/,
// unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g,
// RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function (value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base;; /* no condition */k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base;; /* no condition */k += base) {
t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function (string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function (string) {
return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if ("function" == 'function' && _typeof(__webpack_require__(106)) == 'object' && __webpack_require__(106)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return punycode;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
})(this);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)(module), (function() { return this; }())))
/***/ }),
/* 106 */
/***/ (function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ }),
/* 107 */
/***/ (function(module, exports) {
'use strict';
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; };
module.exports = {
isString: function isString(arg) {
return typeof arg === 'string';
},
isObject: function isObject(arg) {
return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null;
},
isNull: function isNull(arg) {
return arg === null;
},
isNullOrUndefined: function isNullOrUndefined(arg) {
return arg == null;
}
};
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.decode = exports.parse = __webpack_require__(109);
exports.encode = exports.stringify = __webpack_require__(110);
/***/ }),
/* 109 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function (qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr,
vstr,
k,
v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (Array.isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
/***/ }),
/* 110 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
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 stringifyPrimitive = function stringifyPrimitive(v) {
switch (typeof v === 'undefined' ? 'undefined' : _typeof(v)) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function (obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') {
return Object.keys(obj).map(function (k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (Array.isArray(obj[k])) {
return obj[k].map(function (v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));
};
/***/ }),
/* 111 */
/***/ (function(module, exports) {
"use strict";
module.exports = extend;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {};
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
}
/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var qs = __webpack_require__(113);
// FIXME: Can this also take a URLSearchParams?
module.exports = function formDataToObject(formData) {
var items = Array.from(formData.entries()).reduce(function (items, _ref) {
var key = _ref[0],
value = _ref[1];
if (key.match(/\[\]$/)) {
/* Array item */
if (items[key] == null) {
items[key] = [];
}
items[key].push(value);
} else {
/* Single item */
items[key] = value;
}
return items;
}, {});
console.log("ITEMS", qs.stringify(items));
/* This is a bit of a hack... we have an array of values that may or may not
involve array and object specifications, and the `items` object is an
object that contains a flat set of them as keys and values. By passing it
into `stringify` and `parse` consecutively, we get back a properly nested
version of it. */
return qs.parse(qs.stringify(items));
};
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var stringify = __webpack_require__(114);
var parse = __webpack_require__(117);
var formats = __webpack_require__(116);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
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 utils = __webpack_require__(115);
var formats = __webpack_require__(116);
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
// eslint-disable-line func-name-matching
return prefix + '[]';
},
indices: function indices(prefix, key) {
// eslint-disable-line func-name-matching
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
// eslint-disable-line func-name-matching
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults = {
delimiter: '&',
encode: true,
encoder: utils.encode,
encodeValuesOnly: false,
serializeDate: function serializeDate(date) {
// eslint-disable-line func-name-matching
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify( // eslint-disable-line func-name-matching
object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix);
return [formatter(keyValue) + '=' + formatter(encoder(obj))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
} else {
values = values.concat(stringify(obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
}
}
return values;
};
module.exports = function (object, opts) {
var obj = object;
var options = opts || {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
if (typeof options.format === 'undefined') {
options.format = formats.default;
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly));
}
return keys.join(delimiter);
};
/***/ }),
/* 115 */
/***/ (function(module, exports) {
'use strict';
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 has = Object.prototype.hasOwnProperty;
var hexTable = function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}();
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if ((typeof source === 'undefined' ? 'undefined' : _typeof(source)) !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object') {
if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && _typeof(target[i]) === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (Object.prototype.hasOwnProperty.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (c === 0x2D || // -
c === 0x2E || // .
c === 0x5F || // _
c === 0x7E || // ~
c >= 0x30 && c <= 0x39 || // 0-9
c >= 0x41 && c <= 0x5A || // a-z
c >= 0x61 && c <= 0x7A // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | c >> 6] + hexTable[0x80 | c & 0x3F]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | c >> 12] + hexTable[0x80 | c >> 6 & 0x3F] + hexTable[0x80 | c & 0x3F]);
continue;
}
i += 1;
c = 0x10000 + ((c & 0x3FF) << 10 | string.charCodeAt(i) & 0x3FF);
out += hexTable[0xF0 | c >> 18] + hexTable[0x80 | c >> 12 & 0x3F] + hexTable[0x80 | c >> 6 & 0x3F] + hexTable[0x80 | c & 0x3F]; // eslint-disable-line max-len
}
return out;
};
exports.compact = function (obj, references) {
if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && _typeof(obj[i]) === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ }),
/* 116 */
/***/ (function(module, exports) {
'use strict';
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function RFC1738(value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function RFC3986(value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(115);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos));
val = options.decoder(part.slice(pos + 1));
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObjectRecursive(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && options.parseArrays && index <= options.arrayLimit) {
obj = [];
obj[index] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
module.exports = function (str, opts) {
var options = opts || {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var deconstructFormObject = __webpack_require__(119);
module.exports = function objectToURLSearchParams(object) {
var params = new URLSearchParams();
deconstructFormObject(object).forEach(function (item) {
params.append(item.name, item.value);
});
return params;
};
/***/ }),
/* 119 */
/***/ (function(module, exports) {
'use strict';
function isObject(value) {
return value === Object(value);
}
function makeArrayKey(key) {
if (key.length > 2 && key.lastIndexOf('[]') === key.length - 2) {
return key;
} else {
return key + '[]';
}
}
function generateKey(prefix, key) {
if (prefix == null || prefix.length === 0) {
return key;
} else {
return prefix + '[' + key + ']';
}
}
module.exports = function deconstructFormObject(object, prefix) {
return Object.keys(object).reduce(function (items, key) {
var value = object[key];
var newItems = [];
function transformValue(value, isInArray) {
var valueKey = void 0;
if (isInArray) {
valueKey = makeArrayKey(generateKey(prefix, key));
} else {
valueKey = generateKey(prefix, key);
}
if (Array.isArray(value)) {
value.forEach(function (arrayItem) {
transformValue(arrayItem, true);
});
} else if (isObject(value)) {
newItems = newItems.concat(deconstructFormObject(value, valueKey));
} else {
newItems.push({
name: valueKey,
value: value
});
}
}
transformValue(value);
return items.concat(newItems);
}, []);
};
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var deconstructFormObject = __webpack_require__(119);
module.exports = function objectToFormData(object) {
var formData = new FormData();
deconstructFormObject(object).forEach(function (item) {
formData.append(item.name, item.value);
});
return formData;
};
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var riotQuery = __webpack_require__(57);
var arrayDiff = __webpack_require__(122);
module.exports = {
init: function init() {
var _this = this;
var knownTags = [];
var listeners = {};
function triggerEvent(action, query, item) {
if (listeners[query] != null && listeners[query][action] != null) {
listeners[query][action].forEach(function (handler) {
handler(item);
});
}
}
this.on("updated", function () {
Object.keys(listeners).forEach(function (query) {
var currentTags = riotQuery(_this, query);
var diff = arrayDiff(knownTags, currentTags);
diff.forEach(function (item) {
if (item.type === "remove") {
for (var i = item.index; i < item.index + item.howMany; i++) {
triggerEvent("remove", query, knownTags[i]);
}
} else if (item.type === "move") {
for (var _i = item.index; _i < item.from + item.howMany; _i++) {
triggerEvent("move", query, knownTags[_i]);
}
} else if (item.type === "insert") {
item.values.forEach(function (value) {
triggerEvent("create", query, value);
});
}
});
knownTags = currentTags;
});
});
this.onChild = function (eventName, handler) {
var _eventName$split = eventName.split(":", 2),
action = _eventName$split[0],
query = _eventName$split[1];
if (listeners[query] == null) {
listeners[query] = {};
}
if (listeners[query][action] == null) {
listeners[query][action] = [];
}
listeners[query][action].push(handler);
};
}
};
/***/ }),
/* 122 */
/***/ (function(module, exports) {
'use strict';
module.exports = arrayDiff;
// Based on some rough benchmarking, this algorithm is about O(2n) worst case,
// and it can compute diffs on random arrays of length 1024 in about 34ms,
// though just a few changes on an array of length 1024 takes about 0.5ms
arrayDiff.InsertDiff = InsertDiff;
arrayDiff.RemoveDiff = RemoveDiff;
arrayDiff.MoveDiff = MoveDiff;
function InsertDiff(index, values) {
this.index = index;
this.values = values;
}
InsertDiff.prototype.type = 'insert';
InsertDiff.prototype.toJSON = function () {
return {
type: this.type,
index: this.index,
values: this.values
};
};
function RemoveDiff(index, howMany) {
this.index = index;
this.howMany = howMany;
}
RemoveDiff.prototype.type = 'remove';
RemoveDiff.prototype.toJSON = function () {
return {
type: this.type,
index: this.index,
howMany: this.howMany
};
};
function MoveDiff(from, to, howMany) {
this.from = from;
this.to = to;
this.howMany = howMany;
}
MoveDiff.prototype.type = 'move';
MoveDiff.prototype.toJSON = function () {
return {
type: this.type,
from: this.from,
to: this.to,
howMany: this.howMany
};
};
function strictEqual(a, b) {
return a === b;
}
function arrayDiff(before, after, equalFn) {
if (!equalFn) equalFn = strictEqual;
// Find all items in both the before and after array, and represent them
// as moves. Many of these "moves" may end up being discarded in the last
// pass if they are from an index to the same index, but we don't know this
// up front, since we haven't yet offset the indices.
//
// Also keep a map of all the indices accounted for in the before and after
// arrays. These maps are used next to create insert and remove diffs.
var beforeLength = before.length;
var afterLength = after.length;
var moves = [];
var beforeMarked = {};
var afterMarked = {};
for (var beforeIndex = 0; beforeIndex < beforeLength; beforeIndex++) {
var beforeItem = before[beforeIndex];
for (var afterIndex = 0; afterIndex < afterLength; afterIndex++) {
if (afterMarked[afterIndex]) continue;
if (!equalFn(beforeItem, after[afterIndex])) continue;
var from = beforeIndex;
var to = afterIndex;
var howMany = 0;
do {
beforeMarked[beforeIndex++] = afterMarked[afterIndex++] = true;
howMany++;
} while (beforeIndex < beforeLength && afterIndex < afterLength && equalFn(before[beforeIndex], after[afterIndex]) && !afterMarked[afterIndex]);
moves.push(new MoveDiff(from, to, howMany));
beforeIndex--;
break;
}
}
// Create a remove for all of the items in the before array that were
// not marked as being matched in the after array as well
var removes = [];
for (beforeIndex = 0; beforeIndex < beforeLength;) {
if (beforeMarked[beforeIndex]) {
beforeIndex++;
continue;
}
var index = beforeIndex;
var howMany = 0;
while (beforeIndex < beforeLength && !beforeMarked[beforeIndex++]) {
howMany++;
}
removes.push(new RemoveDiff(index, howMany));
}
// Create an insert for all of the items in the after array that were
// not marked as being matched in the before array as well
var inserts = [];
for (var afterIndex = 0; afterIndex < afterLength;) {
if (afterMarked[afterIndex]) {
afterIndex++;
continue;
}
var index = afterIndex;
var howMany = 0;
while (afterIndex < afterLength && !afterMarked[afterIndex++]) {
howMany++;
}
var values = after.slice(index, index + howMany);
inserts.push(new InsertDiff(index, values));
}
var insertsLength = inserts.length;
var removesLength = removes.length;
var movesLength = moves.length;
var i, j;
// Offset subsequent removes and moves by removes
var count = 0;
for (i = 0; i < removesLength; i++) {
var remove = removes[i];
remove.index -= count;
count += remove.howMany;
for (j = 0; j < movesLength; j++) {
var move = moves[j];
if (move.from >= remove.index) move.from -= remove.howMany;
}
}
// Offset moves by inserts
for (i = insertsLength; i--;) {
var insert = inserts[i];
var howMany = insert.values.length;
for (j = movesLength; j--;) {
var move = moves[j];
if (move.to >= insert.index) move.to -= howMany;
}
}
// Offset the to of moves by later moves
for (i = movesLength; i-- > 1;) {
var move = moves[i];
if (move.to === move.from) continue;
for (j = i; j--;) {
var earlier = moves[j];
if (earlier.to >= move.to) earlier.to -= move.howMany;
if (earlier.to >= move.from) earlier.to += move.howMany;
}
}
// Only output moves that end up having an effect after offsetting
var outputMoves = [];
// Offset the from of moves by earlier moves
for (i = 0; i < movesLength; i++) {
var move = moves[i];
if (move.to === move.from) continue;
outputMoves.push(move);
for (j = i + 1; j < movesLength; j++) {
var later = moves[j];
if (later.from >= move.from) later.from -= move.howMany;
if (later.from >= move.to) later.from += move.howMany;
}
}
return removes.concat(outputMoves, inserts);
}
/***/ })
/******/ ]);