path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
|---|---|---|
ajax/libs/webshim/1.14.5-RC1/dev/shims/es6.js
|
fredericksilva/cdnjs
|
// ES6-shim 0.8.0 (c) 2013 Paul Miller (paulmillr.com)
// ES6-shim may be freely distributed under the MIT license.
// For more details and documentation:
// https://github.com/paulmillr/es6-shim/
webshim.register('es6', function($, webshim, window, document, undefined){
'use strict';
var isCallableWithoutNew = function(func) {
try { func(); }
catch (e) { return false; }
return true;
};
var supportsSubclassing = function(C, f) {
/* jshint proto:true */
try {
var Sub = function() { C.apply(this, arguments); };
if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ }
Object.setPrototypeOf(Sub, C);
Sub.prototype = Object.create(C.prototype, {
constructor: { value: C }
});
return f(Sub);
} catch (e) {
return false;
}
};
var arePropertyDescriptorsSupported = function() {
try {
Object.defineProperty({}, 'x', {});
return true;
} catch (e) { /* this is IE 8. */
return false;
}
};
var startsWithRejectsRegex = function() {
var rejectsRegex = false;
if (String.prototype.startsWith) {
try {
'/a/'.startsWith(/a/);
} catch (e) { /* this is spec compliant */
rejectsRegex = true;
}
}
return rejectsRegex;
};
/*jshint evil: true */
var getGlobal = new Function('return this;');
/*jshint evil: false */
var main = function() {
var globals = getGlobal();
var global_isFinite = globals.isFinite;
var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported();
var startsWithIsCompliant = startsWithRejectsRegex();
var _slice = Array.prototype.slice;
var _indexOf = String.prototype.indexOf;
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var ArrayIterator; // make our implementation private
// Define configurable, writable and non-enumerable props
// if they don’t exist.
var defineProperties = function(object, map) {
Object.keys(map).forEach(function(name) {
var method = map[name];
if (name in object) return;
if (supportsDescriptors) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
} else {
object[name] = method;
}
});
};
// Simple shim for Object.create on ES3 browsers
// (unlike real shim, no attempt to support `prototype === null`)
var create = Object.create || function(prototype, properties) {
function Type() {}
Type.prototype = prototype;
var object = new Type();
if (typeof properties !== "undefined") {
defineProperties(object, properties);
}
return object;
};
// This is a private name in the es6 spec, equal to '[Symbol.iterator]'
// we're going to use an arbitrary _-prefixed name to make our shims
// work properly with each other, even though we don't have full Iterator
// support. That is, `Array.from(map.keys())` will work, but we don't
// pretend to export a "real" Iterator interface.
var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var addIterator = function(prototype, impl) {
if (!impl) { impl = function iterator() { return this; }; }
var o = {};
o[$iterator$] = impl;
defineProperties(prototype, o);
};
// taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
// can be replaced with require('is-arguments') if we ever use a build process instead
var isArguments = function isArguments(value) {
var str = _toString.call(value);
var result = str === '[object Arguments]';
if (!result) {
result = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
_toString.call(value.callee) === '[object Function]';
}
return result;
};
var emulateES6construct = function(o) {
if (!ES.TypeIsObject(o)) throw new TypeError('bad object');
// es5 approximation to es6 subclass semantics: in es6, 'new Foo'
// would invoke Foo.@@create to allocation/initialize the new object.
// In es5 we just get the plain object. So if we detect an
// uninitialized object, invoke o.constructor.@@create
if (!o._es6construct) {
if (o.constructor && ES.IsCallable(o.constructor['@@create'])) {
o = o.constructor['@@create'](o);
}
defineProperties(o, { _es6construct: true });
}
return o;
};
var ES = {
CheckObjectCoercible: function(x, optMessage) {
/* jshint eqnull:true */
if (x == null)
throw new TypeError(optMessage || ('Cannot call method on ' + x));
return x;
},
TypeIsObject: function(x) {
/* jshint eqnull:true */
// this is expensive when it returns false; use this function
// when you expect it to return true in the common case.
return x != null && Object(x) === x;
},
ToObject: function(o, optMessage) {
return Object(ES.CheckObjectCoercible(o, optMessage));
},
IsCallable: function(x) {
return typeof x === 'function' &&
// some versions of IE say that typeof /abc/ === 'function'
_toString.call(x) === '[object Function]';
},
ToInt32: function(x) {
return x >> 0;
},
ToUint32: function(x) {
return x >>> 0;
},
ToInteger: function(value) {
var number = +value;
if (Number.isNaN(number)) return 0;
if (number === 0 || !Number.isFinite(number)) return number;
return Math.sign(number) * Math.floor(Math.abs(number));
},
ToLength: function(value) {
var len = ES.ToInteger(value);
if (len <= 0) return 0; // includes converting -0 to +0
if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER;
return len;
},
SameValue: function(a, b) {
if (a === b) {
// 0 === -0, but they are not identical.
if (a === 0) return 1 / a === 1 / b;
return true;
}
return Number.isNaN(a) && Number.isNaN(b);
},
SameValueZero: function(a, b) {
// same as SameValue except for SameValueZero(+0, -0) == true
return (a === b) || (Number.isNaN(a) && Number.isNaN(b));
},
IsIterable: function(o) {
return ES.TypeIsObject(o) &&
(o[$iterator$] !== undefined || isArguments(o));
},
GetIterator: function(o) {
if (isArguments(o)) {
// special case support for `arguments`
return new ArrayIterator(o, "value");
}
var it = o[$iterator$]();
if (!ES.TypeIsObject(it)) {
throw new TypeError('bad iterator');
}
return it;
},
IteratorNext: function(it) {
var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next();
if (!ES.TypeIsObject(result)) {
throw new TypeError('bad iterator');
}
return result;
},
Construct: function(C, args) {
// CreateFromConstructor
var obj;
if (ES.IsCallable(C['@@create'])) {
obj = C['@@create']();
} else {
// OrdinaryCreateFromConstructor
obj = create(C.prototype || null);
}
// Mark that we've used the es6 construct path
// (see emulateES6construct)
defineProperties(obj, { _es6construct: true });
// Call the constructor.
var result = C.apply(obj, args);
return ES.TypeIsObject(result) ? result : obj;
}
};
var numberConversion = (function () {
// from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266
// with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200
function roundToEven(n) {
var w = Math.floor(n), f = n - w;
if (f < 0.5) {
return w;
}
if (f > 0.5) {
return w + 1;
}
return w % 2 ? w + 1 : w;
}
function packIEEE754(v, ebits, fbits) {
var bias = (1 << (ebits - 1)) - 1,
s, e, f, ln,
i, bits, str, bytes;
// Compute sign, exponent, fraction
if (v !== v) {
// NaN
// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
e = (1 << ebits) - 1;
f = Math.pow(2, fbits - 1);
s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1;
f = 0;
s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0;
f = 0;
s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = Math.abs(v);
if (v >= Math.pow(2, 1 - bias)) {
e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023);
f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits));
if (f / Math.pow(2, fbits) >= 2) {
e = e + 1;
f = 1;
}
if (e > bias) {
// Overflow
e = (1 << ebits) - 1;
f = 0;
} else {
// Normal
e = e + bias;
f = f - Math.pow(2, fbits);
}
} else {
// Subnormal
e = 0;
f = roundToEven(v / Math.pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
bits = [];
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = Math.floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = Math.floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
// Bits to bytes
bytes = [];
while (str.length) {
bytes.push(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
}
function unpackIEEE754(bytes, ebits, fbits) {
// Bytes to bits
var bits = [], i, j, b, str,
bias, s, e, f;
for (i = bytes.length; i; i -= 1) {
b = bytes[i - 1];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0);
b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
// Unpack sign, exponent, fraction
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
e = parseInt(str.substring(1, 1 + ebits), 2);
f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
// Normalized
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
} else if (f !== 0) {
// Denormalized
return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
}
function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); }
function packFloat64(v) { return packIEEE754(v, 11, 52); }
function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); }
function packFloat32(v) { return packIEEE754(v, 8, 23); }
var conversions = {
toFloat32: function (num) { return unpackFloat32(packFloat32(num)); }
};
if (typeof Float32Array !== 'undefined') {
var float32array = new Float32Array(1);
conversions.toFloat32 = function (num) {
float32array[0] = num;
return float32array[0];
};
}
return conversions;
}());
defineProperties(String, {
fromCodePoint: function() {
var points = _slice.call(arguments, 0, arguments.length);
var result = [];
var next;
for (var i = 0, length = points.length; i < length; i++) {
next = Number(points[i]);
if (!ES.SameValue(next, ES.ToInteger(next)) ||
next < 0 || next > 0x10FFFF) {
throw new RangeError('Invalid code point ' + next);
}
if (next < 0x10000) {
result.push(String.fromCharCode(next));
} else {
next -= 0x10000;
result.push(String.fromCharCode((next >> 10) + 0xD800));
result.push(String.fromCharCode((next % 0x400) + 0xDC00));
}
}
return result.join('');
},
raw: function(callSite) { // raw.length===1
var substitutions = _slice.call(arguments, 1, arguments.length);
var cooked = ES.ToObject(callSite, 'bad callSite');
var rawValue = cooked.raw;
var raw = ES.ToObject(rawValue, 'bad raw value');
var len = Object.keys(raw).length;
var literalsegments = ES.ToLength(len);
if (literalsegments === 0) {
return '';
}
var stringElements = [];
var nextIndex = 0;
var nextKey, next, nextSeg, nextSub;
while (nextIndex < literalsegments) {
nextKey = String(nextIndex);
next = raw[nextKey];
nextSeg = String(next);
stringElements.push(nextSeg);
if (nextIndex + 1 >= literalsegments) {
break;
}
next = substitutions[nextKey];
if (next === undefined) {
break;
}
nextSub = String(next);
stringElements.push(nextSub);
nextIndex++;
}
return stringElements.join('');
}
});
var StringShims = {
// Fast repeat, uses the `Exponentiation by squaring` algorithm.
// Perf: http://jsperf.com/string-repeat2/2
repeat: (function() {
var repeat = function(s, times) {
if (times < 1) return '';
if (times % 2) return repeat(s, times - 1) + s;
var half = repeat(s, times / 2);
return half + half;
};
return function(times) {
var thisStr = String(ES.CheckObjectCoercible(this));
times = ES.ToInteger(times);
if (times < 0 || times === Infinity) {
throw new RangeError('Invalid String#repeat value');
}
return repeat(thisStr, times);
};
})(),
startsWith: function(searchStr) {
var thisStr = String(ES.CheckObjectCoercible(this));
if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex');
searchStr = String(searchStr);
var startArg = arguments.length > 1 ? arguments[1] : undefined;
var start = Math.max(ES.ToInteger(startArg), 0);
return thisStr.slice(start, start + searchStr.length) === searchStr;
},
endsWith: function(searchStr) {
var thisStr = String(ES.CheckObjectCoercible(this));
if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex');
searchStr = String(searchStr);
var thisLen = thisStr.length;
var posArg = arguments.length > 1 ? arguments[1] : undefined;
var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg);
var end = Math.min(Math.max(pos, 0), thisLen);
return thisStr.slice(end - searchStr.length, end) === searchStr;
},
contains: function(searchString) {
var position = arguments.length > 1 ? arguments[1] : undefined;
// Somehow this trick makes method 100% compat with the spec.
return _indexOf.call(this, searchString, position) !== -1;
},
codePointAt: function(pos) {
var thisStr = String(ES.CheckObjectCoercible(this));
var position = ES.ToInteger(pos);
var length = thisStr.length;
if (position < 0 || position >= length) return undefined;
var first = thisStr.charCodeAt(position);
var isEnd = (position + 1 === length);
if (first < 0xD800 || first > 0xDBFF || isEnd) return first;
var second = thisStr.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) return first;
return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000;
}
};
defineProperties(String.prototype, StringShims);
var hasStringTrimBug = '\u0085'.trim().length !== 1;
if (hasStringTrimBug) {
var originalStringTrim = String.prototype.trim;
delete String.prototype.trim;
// whitespace from: http://es5.github.io/#x15.5.4.20
// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
var ws = [
'\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
'\u2029\uFEFF'
].join('');
var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*');
var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$');
defineProperties(String.prototype, {
trim: function() {
if (this === undefined || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
}
});
}
// see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator
var StringIterator = function(s) {
this._s = String(ES.CheckObjectCoercible(s));
this._i = 0;
};
StringIterator.prototype.next = function() {
var s = this._s, i = this._i;
if (s === undefined || i >= s.length) {
this._s = undefined;
return { value: undefined, done: true };
}
var first = s.charCodeAt(i), second, len;
if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) {
len = 1;
} else {
second = s.charCodeAt(i+1);
len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2;
}
this._i = i + len;
return { value: s.substr(i, len), done: false };
};
addIterator(StringIterator.prototype);
addIterator(String.prototype, function() {
return new StringIterator(this);
});
if (!startsWithIsCompliant) {
// Firefox has a noncompliant startsWith implementation
String.prototype.startsWith = StringShims.startsWith;
String.prototype.endsWith = StringShims.endsWith;
}
defineProperties(Array, {
from: function(iterable) {
var mapFn = arguments.length > 1 ? arguments[1] : undefined;
var thisArg = arguments.length > 2 ? arguments[2] : undefined;
var list = ES.ToObject(iterable, 'bad iterable');
if (mapFn !== undefined && !ES.IsCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
var usingIterator = ES.IsIterable(list);
// does the spec really mean that Arrays should use ArrayIterator?
// https://bugs.ecmascript.org/show_bug.cgi?id=2416
//if (Array.isArray(list)) { usingIterator=false; }
var length = usingIterator ? 0 : ES.ToLength(list.length);
var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length);
var it = usingIterator ? ES.GetIterator(list) : null;
var value;
for (var i = 0; usingIterator || (i < length); i++) {
if (usingIterator) {
value = ES.IteratorNext(it);
if (value.done) {
length = i;
break;
}
value = value.value;
} else {
value = list[i];
}
if (mapFn) {
result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i);
} else {
result[i] = value;
}
}
result.length = length;
return result;
},
of: function() {
return Array.from(arguments);
}
});
// Our ArrayIterator is private; see
// https://github.com/paulmillr/es6-shim/issues/252
ArrayIterator = function(array, kind) {
this.i = 0;
this.array = array;
this.kind = kind;
};
defineProperties(ArrayIterator.prototype, {
next: function() {
var i = this.i, array = this.array;
if (i === undefined || this.kind === undefined) {
throw new TypeError('Not an ArrayIterator');
}
if (array!==undefined) {
var len = ES.ToLength(array.length);
for (; i < len; i++) {
var kind = this.kind;
var retval;
if (kind === "key") {
retval = i;
} else if (kind === "value") {
retval = array[i];
} else if (kind === "entry") {
retval = [i, array[i]];
}
this.i = i + 1;
return { value: retval, done: false };
}
}
this.array = undefined;
return { value: undefined, done: true };
}
});
addIterator(ArrayIterator.prototype);
defineProperties(Array.prototype, {
copyWithin: function(target, start) {
var end = arguments[2]; // copyWithin.length must be 2
var o = ES.ToObject(this);
var len = ES.ToLength(o.length);
target = ES.ToInteger(target);
start = ES.ToInteger(start);
var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);
var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
end = (end===undefined) ? len : ES.ToInteger(end);
var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
var count = Math.min(fin - from, len - to);
var direction = 1;
if (from < to && to < (from + count)) {
direction = -1;
from += count - 1;
to += count - 1;
}
while (count > 0) {
if (_hasOwnProperty.call(o, from)) {
o[to] = o[from];
} else {
delete o[from];
}
from += direction;
to += direction;
count -= 1;
}
return o;
},
fill: function(value) {
var start = arguments[1], end = arguments[2]; // fill.length===1
var O = ES.ToObject(this);
var len = ES.ToLength(O.length);
start = ES.ToInteger(start===undefined ? 0 : start);
end = ES.ToInteger(end===undefined ? len : end);
var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
for (var i = relativeStart; i < len && i < end; ++i) {
O[i] = value;
}
return O;
},
find: function(predicate) {
var list = ES.ToObject(this);
var length = ES.ToLength(list.length);
if (!ES.IsCallable(predicate)) {
throw new TypeError('Array#find: predicate must be a function');
}
var thisArg = arguments[1];
for (var i = 0, value; i < length; i++) {
if (i in list) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) return value;
}
}
return undefined;
},
findIndex: function(predicate) {
var list = ES.ToObject(this);
var length = ES.ToLength(list.length);
if (!ES.IsCallable(predicate)) {
throw new TypeError('Array#findIndex: predicate must be a function');
}
var thisArg = arguments[1];
for (var i = 0; i < length; i++) {
if (i in list) {
if (predicate.call(thisArg, list[i], i, list)) return i;
}
}
return -1;
},
keys: function() {
return new ArrayIterator(this, "key");
},
values: function() {
return new ArrayIterator(this, "value");
},
entries: function() {
return new ArrayIterator(this, "entry");
}
});
addIterator(Array.prototype, function() { return this.values(); });
// Chrome defines keys/values/entries on Array, but doesn't give us
// any way to identify its iterator. So add our own shimmed field.
if (Object.getPrototypeOf) {
addIterator(Object.getPrototypeOf([].values()));
}
var maxSafeInteger = Math.pow(2, 53) - 1;
defineProperties(Number, {
MAX_SAFE_INTEGER: maxSafeInteger,
MIN_SAFE_INTEGER: -maxSafeInteger,
EPSILON: 2.220446049250313e-16,
parseInt: globals.parseInt,
parseFloat: globals.parseFloat,
isFinite: function(value) {
return typeof value === 'number' && global_isFinite(value);
},
isInteger: function(value) {
return typeof value === 'number' &&
!Number.isNaN(value) &&
Number.isFinite(value) &&
ES.ToInteger(value) === value;
},
isSafeInteger: function(value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
},
isNaN: function(value) {
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN('foo') => true
return value !== value;
}
});
if (supportsDescriptors) {
defineProperties(Object, {
getPropertyDescriptor: function(subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (pd === undefined && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
},
getPropertyNames: function(subject) {
var result = Object.getOwnPropertyNames(subject);
var proto = Object.getPrototypeOf(subject);
var addProperty = function(property) {
if (result.indexOf(property) === -1) {
result.push(property);
}
};
while (proto !== null) {
Object.getOwnPropertyNames(proto).forEach(addProperty);
proto = Object.getPrototypeOf(proto);
}
return result;
}
});
defineProperties(Object, {
// 19.1.3.1
assign: function(target, source) {
if (!ES.TypeIsObject(target)) {
throw new TypeError('target must be an object');
}
return Array.prototype.reduce.call(arguments, function(target, source) {
if (!ES.TypeIsObject(source)) {
throw new TypeError('source must be an object');
}
return Object.keys(source).reduce(function(target, key) {
target[key] = source[key];
return target;
}, target);
});
},
getOwnPropertyKeys: function(subject) {
return Object.keys(subject);
},
is: function(a, b) {
return ES.SameValue(a, b);
},
// 19.1.3.9
// shim from https://gist.github.com/WebReflection/5593554
setPrototypeOf: (function(Object, magic) {
var set;
var checkArgs = function(O, proto) {
if (!ES.TypeIsObject(O)) {
throw new TypeError('cannot set prototype on a non-object');
}
if (!(proto===null || ES.TypeIsObject(proto))) {
throw new TypeError('can only set prototype to an object or null'+proto);
}
};
var setPrototypeOf = function(O, proto) {
checkArgs(O, proto);
set.call(O, proto);
return O;
};
try {
// this works already in Firefox and Safari
set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set;
set.call({}, null);
} catch (e) {
if (Object.prototype !== {}[magic]) {
// IE < 11 cannot be shimmed
return;
}
// probably Chrome or some old Mobile stock browser
set = function(proto) {
this[magic] = proto;
};
// please note that this will **not** work
// in those browsers that do not inherit
// __proto__ by mistake from Object.prototype
// in these cases we should probably throw an error
// or at least be informed about the issue
setPrototypeOf.polyfill = setPrototypeOf(
setPrototypeOf({}, null),
Object.prototype
) instanceof Object;
// setPrototypeOf.polyfill === true means it works as meant
// setPrototypeOf.polyfill === false means it's not 100% reliable
// setPrototypeOf.polyfill === undefined
// or
// setPrototypeOf.polyfill == null means it's not a polyfill
// which means it works as expected
// we can even delete Object.prototype.__proto__;
}
return setPrototypeOf;
})(Object, '__proto__')
});
}
// Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work,
// but Object.create(null) does.
if (Object.setPrototypeOf && Object.getPrototypeOf &&
Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null &&
Object.getPrototypeOf(Object.create(null)) === null) {
(function() {
var FAKENULL = Object.create(null);
var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf;
Object.getPrototypeOf = function(o) {
var result = gpo(o);
return result === FAKENULL ? null : result;
};
Object.setPrototypeOf = function(o, p) {
if (p === null) { p = FAKENULL; }
return spo(o, p);
};
Object.setPrototypeOf.polyfill = false;
})();
}
try {
Object.keys('foo');
} catch (e) {
var originalObjectKeys = Object.keys;
Object.keys = function (obj) {
return originalObjectKeys(ES.ToObject(obj));
};
}
var MathShims = {
acosh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value < 1) return NaN;
if (value === 1) return 0;
if (value === Infinity) return value;
return Math.log(value + Math.sqrt(value * value - 1));
},
asinh: function(value) {
value = Number(value);
if (value === 0 || !global_isFinite(value)) {
return value;
}
return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1));
},
atanh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value < -1 || value > 1) {
return NaN;
}
if (value === -1) return -Infinity;
if (value === 1) return Infinity;
if (value === 0) return value;
return 0.5 * Math.log((1 + value) / (1 - value));
},
cbrt: function(value) {
value = Number(value);
if (value === 0) return value;
var negate = value < 0, result;
if (negate) value = -value;
result = Math.pow(value, 1/3);
return negate ? -result : result;
},
clz32: function(value) {
// See https://bugs.ecmascript.org/show_bug.cgi?id=2465
value = Number(value);
if (Number.isNaN(value)) return NaN;
var number = ES.ToUint32(value);
if (number === 0) {
return 32;
}
return 32 - (number).toString(2).length;
},
cosh: function(value) {
value = Number(value);
if (value === 0) return 1; // +0 or -0
if (Number.isNaN(value)) return NaN;
if (!global_isFinite(value)) return Infinity;
if (value < 0) value = -value;
if (value > 21) return Math.exp(value) / 2;
return (Math.exp(value) + Math.exp(-value)) / 2;
},
expm1: function(value) {
value = Number(value);
if (value === -Infinity) return -1;
if (!global_isFinite(value) || value === 0) return value;
return Math.exp(value) - 1;
},
hypot: function(x, y) {
var anyNaN = false;
var allZero = true;
var anyInfinity = false;
var numbers = [];
Array.prototype.every.call(arguments, function(arg) {
var num = Number(arg);
if (Number.isNaN(num)) anyNaN = true;
else if (num === Infinity || num === -Infinity) anyInfinity = true;
else if (num !== 0) allZero = false;
if (anyInfinity) {
return false;
} else if (!anyNaN) {
numbers.push(Math.abs(num));
}
return true;
});
if (anyInfinity) return Infinity;
if (anyNaN) return NaN;
if (allZero) return 0;
numbers.sort(function (a, b) { return b - a; });
var largest = numbers[0];
var divided = numbers.map(function (number) { return number / largest; });
var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0);
return largest * Math.sqrt(sum);
},
log2: function(value) {
return Math.log(value) * Math.LOG2E;
},
log10: function(value) {
return Math.log(value) * Math.LOG10E;
},
log1p: function(value) {
value = Number(value);
if (value < -1 || Number.isNaN(value)) return NaN;
if (value === 0 || value === Infinity) return value;
if (value === -1) return -Infinity;
var result = 0;
var n = 50;
if (value < 0 || value > 1) return Math.log(1 + value);
for (var i = 1; i < n; i++) {
if ((i % 2) === 0) {
result -= Math.pow(value, i) / i;
} else {
result += Math.pow(value, i) / i;
}
}
return result;
},
sign: function(value) {
var number = +value;
if (number === 0) return number;
if (Number.isNaN(number)) return number;
return number < 0 ? -1 : 1;
},
sinh: function(value) {
value = Number(value);
if (!global_isFinite(value) || value === 0) return value;
return (Math.exp(value) - Math.exp(-value)) / 2;
},
tanh: function(value) {
value = Number(value);
if (Number.isNaN(value) || value === 0) return value;
if (value === Infinity) return 1;
if (value === -Infinity) return -1;
return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value));
},
trunc: function(value) {
var number = Number(value);
return number < 0 ? -Math.floor(-number) : Math.floor(number);
},
imul: function(x, y) {
// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
var ah = (x >>> 16) & 0xffff;
var al = x & 0xffff;
var bh = (y >>> 16) & 0xffff;
var bl = y & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
},
fround: function(x) {
if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) {
return x;
}
var num = Number(x);
return numberConversion.toFloat32(num);
}
};
defineProperties(Math, MathShims);
if (Math.imul(0xffffffff, 5) !== -5) {
// Safari 6.1, at least, reports "0" for this value
Math.imul = MathShims.imul;
}
// Promises
// Simplest possible implementation; use a 3rd-party library if you
// want the best possible speed and/or long stack traces.
var PromiseShim = (function() {
var Promise, Promise$prototype;
ES.IsPromise = function(promise) {
if (!ES.TypeIsObject(promise)) {
return false;
}
if (!promise._promiseConstructor) {
// _promiseConstructor is a bit more unique than _status, so we'll
// check that instead of the [[PromiseStatus]] internal field.
return false;
}
if (promise._status === undefined) {
return false; // uninitialized
}
return true;
};
// "PromiseCapability" in the spec is what most promise implementations
// call a "deferred".
var PromiseCapability = function(C) {
if (!ES.IsCallable(C)) {
throw new TypeError('bad promise constructor');
}
var capability = this;
var resolver = function(resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
};
capability.promise = ES.Construct(C, [resolver]);
// see https://bugs.ecmascript.org/show_bug.cgi?id=2478
if (!capability.promise._es6construct) {
throw new TypeError('bad promise constructor');
}
if (!(ES.IsCallable(capability.resolve) &&
ES.IsCallable(capability.reject))) {
throw new TypeError('bad promise constructor');
}
};
// find an appropriate setImmediate-alike
var setTimeout = globals.setTimeout;
var makeZeroTimeout;
if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) {
makeZeroTimeout = function() {
// from http://dbaron.org/log/20100309-faster-timeouts
var timeouts = [];
var messageName = "zero-timeout-message";
var setZeroTimeout = function(fn) {
timeouts.push(fn);
window.postMessage(messageName, "*");
};
var handleMessage = function(event) {
if (event.source == window && event.data == messageName) {
event.stopPropagation();
if (timeouts.length === 0) { return; }
var fn = timeouts.shift();
fn();
}
};
window.addEventListener("message", handleMessage, true);
return setZeroTimeout;
};
}
var makePromiseAsap = function() {
// An efficient task-scheduler based on a pre-existing Promise
// implementation, which we can use even if we override the
// global Promise below (in order to workaround bugs)
// https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671
var P = globals.Promise;
return P && P.resolve && function(task) {
return P.resolve().then(task);
};
};
var enqueue = ES.IsCallable(globals.setImmediate) ?
globals.setImmediate.bind(globals) :
typeof process === 'object' && process.nextTick ? process.nextTick :
makePromiseAsap() ||
(ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() :
function(task) { setTimeout(task, 0); }); // fallback
var triggerPromiseReactions = function(reactions, x) {
reactions.forEach(function(reaction) {
enqueue(function() {
// PromiseReactionTask
var handler = reaction.handler;
var capability = reaction.capability;
var resolve = capability.resolve;
var reject = capability.reject;
try {
var result = handler(x);
if (result === capability.promise) {
throw new TypeError('self resolution');
}
var updateResult =
updatePromiseFromPotentialThenable(result, capability);
if (!updateResult) {
resolve(result);
}
} catch (e) {
reject(e);
}
});
});
};
var updatePromiseFromPotentialThenable = function(x, capability) {
if (!ES.TypeIsObject(x)) {
return false;
}
var resolve = capability.resolve;
var reject = capability.reject;
try {
var then = x.then; // only one invocation of accessor
if (!ES.IsCallable(then)) { return false; }
then.call(x, resolve, reject);
} catch(e) {
reject(e);
}
return true;
};
var promiseResolutionHandler = function(promise, onFulfilled, onRejected){
return function(x) {
if (x === promise) {
return onRejected(new TypeError('self resolution'));
}
var C = promise._promiseConstructor;
var capability = new PromiseCapability(C);
var updateResult = updatePromiseFromPotentialThenable(x, capability);
if (updateResult) {
return capability.promise.then(onFulfilled, onRejected);
} else {
return onFulfilled(x);
}
};
};
Promise = function(resolver) {
var promise = this;
promise = emulateES6construct(promise);
if (!promise._promiseConstructor) {
// we use _promiseConstructor as a stand-in for the internal
// [[PromiseStatus]] field; it's a little more unique.
throw new TypeError('bad promise');
}
if (promise._status !== undefined) {
throw new TypeError('promise already initialized');
}
// see https://bugs.ecmascript.org/show_bug.cgi?id=2482
if (!ES.IsCallable(resolver)) {
throw new TypeError('not a valid resolver');
}
promise._status = 'unresolved';
promise._resolveReactions = [];
promise._rejectReactions = [];
var resolve = function(resolution) {
if (promise._status !== 'unresolved') { return; }
var reactions = promise._resolveReactions;
promise._result = resolution;
promise._resolveReactions = undefined;
promise._rejectReactions = undefined;
promise._status = 'has-resolution';
triggerPromiseReactions(reactions, resolution);
};
var reject = function(reason) {
if (promise._status !== 'unresolved') { return; }
var reactions = promise._rejectReactions;
promise._result = reason;
promise._resolveReactions = undefined;
promise._rejectReactions = undefined;
promise._status = 'has-rejection';
triggerPromiseReactions(reactions, reason);
};
try {
resolver(resolve, reject);
} catch (e) {
reject(e);
}
return promise;
};
Promise$prototype = Promise.prototype;
defineProperties(Promise, {
'@@create': function(obj) {
var constructor = this;
// AllocatePromise
// The `obj` parameter is a hack we use for es5
// compatibility.
var prototype = constructor.prototype || Promise$prototype;
obj = obj || create(prototype);
defineProperties(obj, {
_status: undefined,
_result: undefined,
_resolveReactions: undefined,
_rejectReactions: undefined,
_promiseConstructor: undefined
});
obj._promiseConstructor = constructor;
return obj;
}
});
var _promiseAllResolver = function(index, values, capability, remaining) {
var done = false;
return function(x) {
if (done) { return; } // protect against being called multiple times
done = true;
values[index] = x;
if ((--remaining.count) === 0) {
var resolve = capability.resolve;
resolve(values); // call w/ this===undefined
}
};
};
Promise.all = function(iterable) {
var C = this;
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
try {
if (!ES.IsIterable(iterable)) {
throw new TypeError('bad iterable');
}
var it = ES.GetIterator(iterable);
var values = [], remaining = { count: 1 };
for (var index = 0; ; index++) {
var next = ES.IteratorNext(it);
if (next.done) {
break;
}
var nextPromise = C.resolve(next.value);
var resolveElement = _promiseAllResolver(
index, values, capability, remaining
);
remaining.count++;
nextPromise.then(resolveElement, capability.reject);
}
if ((--remaining.count) === 0) {
resolve(values); // call w/ this===undefined
}
} catch (e) {
reject(e);
}
return capability.promise;
};
Promise.race = function(iterable) {
var C = this;
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
try {
if (!ES.IsIterable(iterable)) {
throw new TypeError('bad iterable');
}
var it = ES.GetIterator(iterable);
while (true) {
var next = ES.IteratorNext(it);
if (next.done) {
// If iterable has no items, resulting promise will never
// resolve; see:
// https://github.com/domenic/promises-unwrapping/issues/75
// https://bugs.ecmascript.org/show_bug.cgi?id=2515
break;
}
var nextPromise = C.resolve(next.value);
nextPromise.then(resolve, reject);
}
} catch (e) {
reject(e);
}
return capability.promise;
};
Promise.reject = function(reason) {
var C = this;
var capability = new PromiseCapability(C);
var reject = capability.reject;
reject(reason); // call with this===undefined
return capability.promise;
};
Promise.resolve = function(v) {
var C = this;
if (ES.IsPromise(v)) {
var constructor = v._promiseConstructor;
if (constructor === C) { return v; }
}
var capability = new PromiseCapability(C);
var resolve = capability.resolve;
resolve(v); // call with this===undefined
return capability.promise;
};
Promise.prototype['catch'] = function( onRejected ) {
return this.then(undefined, onRejected);
};
Promise.prototype.then = function( onFulfilled, onRejected ) {
var promise = this;
if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); }
// this.constructor not this._promiseConstructor; see
// https://bugs.ecmascript.org/show_bug.cgi?id=2513
var C = this.constructor;
var capability = new PromiseCapability(C);
if (!ES.IsCallable(onRejected)) {
onRejected = function(e) { throw e; };
}
if (!ES.IsCallable(onFulfilled)) {
onFulfilled = function(x) { return x; };
}
var resolutionHandler =
promiseResolutionHandler(promise, onFulfilled, onRejected);
var resolveReaction =
{ capability: capability, handler: resolutionHandler };
var rejectReaction =
{ capability: capability, handler: onRejected };
switch (promise._status) {
case 'unresolved':
promise._resolveReactions.push(resolveReaction);
promise._rejectReactions.push(rejectReaction);
break;
case 'has-resolution':
triggerPromiseReactions([resolveReaction], promise._result);
break;
case 'has-rejection':
triggerPromiseReactions([rejectReaction], promise._result);
break;
default:
throw new TypeError('unexpected');
}
return capability.promise;
};
return Promise;
})();
// export the Promise constructor.
defineProperties(globals, { Promise: PromiseShim });
// In Chrome 33 (and thereabouts) Promise is defined, but the
// implementation is buggy in a number of ways. Let's check subclassing
// support to see if we have a buggy implementation.
var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) {
return S.resolve(42) instanceof S;
});
var promiseIgnoresNonFunctionThenCallbacks = (function () {
try {
globals.Promise.reject(42).then(null, 5).then(null, function () {});
return true;
} catch (ex) {
return false;
}
}());
if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) {
globals.Promise = PromiseShim;
}
// Map and Set require a true ES5 environment
if (supportsDescriptors) {
var fastkey = function fastkey(key) {
var type = typeof key;
if (type === 'string') {
return '$' + key;
} else if (type === 'number') {
// note that -0 will get coerced to "0" when used as a property key
return key;
}
return null;
};
var emptyObject = function emptyObject() {
// accomodate some older not-quite-ES5 browsers
return Object.create ? Object.create(null) : {};
};
var collectionShims = {
Map: (function() {
var empty = {};
function MapEntry(key, value) {
this.key = key;
this.value = value;
this.next = null;
this.prev = null;
}
MapEntry.prototype.isRemoved = function() {
return this.key === empty;
};
function MapIterator(map, kind) {
this.head = map._head;
this.i = this.head;
this.kind = kind;
}
MapIterator.prototype = {
next: function() {
var i = this.i, kind = this.kind, head = this.head, result;
if (this.i === undefined) {
return { value: undefined, done: true };
}
while (i.isRemoved() && i !== head) {
// back up off of removed entries
i = i.prev;
}
// advance to next unreturned element.
while (i.next !== head) {
i = i.next;
if (!i.isRemoved()) {
if (kind === "key") {
result = i.key;
} else if (kind === "value") {
result = i.value;
} else {
result = [i.key, i.value];
}
this.i = i;
return { value: result, done: false };
}
}
// once the iterator is done, it is done forever.
this.i = undefined;
return { value: undefined, done: true };
}
};
addIterator(MapIterator.prototype);
function Map() {
var map = this;
map = emulateES6construct(map);
if (!map._es6map) {
throw new TypeError('bad map');
}
var head = new MapEntry(null, null);
// circular doubly-linked list.
head.next = head.prev = head;
defineProperties(map, {
'_head': head,
'_storage': emptyObject(),
'_size': 0
});
// Optionally initialize map from iterable
var iterable = arguments[0];
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = map.set;
if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
if (!ES.TypeIsObject(nextItem)) {
throw new TypeError('expected iterable of pairs');
}
adder.call(map, nextItem[0], nextItem[1]);
}
}
return map;
}
var Map$prototype = Map.prototype;
defineProperties(Map, {
'@@create': function(obj) {
var constructor = this;
var prototype = constructor.prototype || Map$prototype;
obj = obj || create(prototype);
defineProperties(obj, { _es6map: true });
return obj;
}
});
Object.defineProperty(Map.prototype, 'size', {
configurable: true,
enumerable: false,
get: function() {
if (typeof this._size === 'undefined') {
throw new TypeError('size method called on incompatible Map');
}
return this._size;
}
});
defineProperties(Map.prototype, {
get: function(key) {
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
var entry = this._storage[fkey];
return entry ? entry.value : undefined;
}
var head = this._head, i = head;
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
return i.value;
}
}
return undefined;
},
has: function(key) {
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
return typeof this._storage[fkey] !== 'undefined';
}
var head = this._head, i = head;
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
return true;
}
}
return false;
},
set: function(key, value) {
var head = this._head, i = head, entry;
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
if (typeof this._storage[fkey] !== 'undefined') {
this._storage[fkey].value = value;
return;
} else {
entry = this._storage[fkey] = new MapEntry(key, value);
i = head.prev;
// fall through
}
}
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
i.value = value;
return;
}
}
entry = entry || new MapEntry(key, value);
if (ES.SameValue(-0, key)) {
entry.key = +0; // coerce -0 to +0 in entry
}
entry.next = this._head;
entry.prev = this._head.prev;
entry.prev.next = entry;
entry.next.prev = entry;
this._size += 1;
},
'delete': function(key) {
var head = this._head, i = head;
var fkey = fastkey(key);
if (fkey !== null) {
// fast O(1) path
if (typeof this._storage[fkey] === 'undefined') {
return false;
}
i = this._storage[fkey].prev;
delete this._storage[fkey];
// fall through
}
while ((i = i.next) !== head) {
if (ES.SameValueZero(i.key, key)) {
i.key = i.value = empty;
i.prev.next = i.next;
i.next.prev = i.prev;
this._size -= 1;
return true;
}
}
return false;
},
clear: function() {
this._size = 0;
this._storage = emptyObject();
var head = this._head, i = head, p = i.next;
while ((i = p) !== head) {
i.key = i.value = empty;
p = i.next;
i.next = i.prev = head;
}
head.next = head.prev = head;
},
keys: function() {
return new MapIterator(this, "key");
},
values: function() {
return new MapIterator(this, "value");
},
entries: function() {
return new MapIterator(this, "key+value");
},
forEach: function(callback) {
var context = arguments.length > 1 ? arguments[1] : null;
var it = this.entries();
for (var entry = it.next(); !entry.done; entry = it.next()) {
callback.call(context, entry.value[1], entry.value[0], this);
}
}
});
addIterator(Map.prototype, function() { return this.entries(); });
return Map;
})(),
Set: (function() {
// Creating a Map is expensive. To speed up the common case of
// Sets containing only string or numeric keys, we use an object
// as backing storage and lazily create a full Map only when
// required.
var SetShim = function Set() {
var set = this;
set = emulateES6construct(set);
if (!set._es6set) {
throw new TypeError('bad set');
}
defineProperties(set, {
'[[SetData]]': null,
'_storage': emptyObject()
});
// Optionally initialize map from iterable
var iterable = arguments[0];
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = set.add;
if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
adder.call(set, nextItem);
}
}
return set;
};
var Set$prototype = SetShim.prototype;
defineProperties(SetShim, {
'@@create': function(obj) {
var constructor = this;
var prototype = constructor.prototype || Set$prototype;
obj = obj || create(prototype);
defineProperties(obj, { _es6set: true });
return obj;
}
});
// Switch from the object backing storage to a full Map.
var ensureMap = function ensureMap(set) {
if (!set['[[SetData]]']) {
var m = set['[[SetData]]'] = new collectionShims.Map();
Object.keys(set._storage).forEach(function(k) {
// fast check for leading '$'
if (k.charCodeAt(0) === 36) {
k = k.substring(1);
} else {
k = +k;
}
m.set(k, k);
});
set._storage = null; // free old backing storage
}
};
Object.defineProperty(SetShim.prototype, 'size', {
configurable: true,
enumerable: false,
get: function() {
if (typeof this._storage === 'undefined') {
// https://github.com/paulmillr/es6-shim/issues/176
throw new TypeError('size method called on incompatible Set');
}
ensureMap(this);
return this['[[SetData]]'].size;
}
});
defineProperties(SetShim.prototype, {
has: function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
return !!this._storage[fkey];
}
ensureMap(this);
return this['[[SetData]]'].has(key);
},
add: function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
this._storage[fkey]=true;
return;
}
ensureMap(this);
return this['[[SetData]]'].set(key, key);
},
'delete': function(key) {
var fkey;
if (this._storage && (fkey = fastkey(key)) !== null) {
delete this._storage[fkey];
return;
}
ensureMap(this);
return this['[[SetData]]']['delete'](key);
},
clear: function() {
if (this._storage) {
this._storage = emptyObject();
return;
}
return this['[[SetData]]'].clear();
},
keys: function() {
ensureMap(this);
return this['[[SetData]]'].keys();
},
values: function() {
ensureMap(this);
return this['[[SetData]]'].values();
},
entries: function() {
ensureMap(this);
return this['[[SetData]]'].entries();
},
forEach: function(callback) {
var context = arguments.length > 1 ? arguments[1] : null;
var entireSet = this;
ensureMap(this);
this['[[SetData]]'].forEach(function(value, key) {
callback.call(context, key, key, entireSet);
});
}
});
addIterator(SetShim.prototype, function() { return this.values(); });
return SetShim;
})()
};
defineProperties(globals, collectionShims);
if (globals.Map || globals.Set) {
/*
- In Firefox < 23, Map#size is a function.
- In all current Firefox, Set#entries/keys/values & Map#clear do not exist
- https://bugzilla.mozilla.org/show_bug.cgi?id=869996
- In Firefox 24, Map and Set do not implement forEach
- In Firefox 25 at least, Map and Set are callable without "new"
*/
if (
typeof globals.Map.prototype.clear !== 'function' ||
new globals.Set().size !== 0 ||
new globals.Map().size !== 0 ||
typeof globals.Map.prototype.keys !== 'function' ||
typeof globals.Set.prototype.keys !== 'function' ||
typeof globals.Map.prototype.forEach !== 'function' ||
typeof globals.Set.prototype.forEach !== 'function' ||
isCallableWithoutNew(globals.Map) ||
isCallableWithoutNew(globals.Set) ||
!supportsSubclassing(globals.Map, function(M) {
return (new M([])) instanceof M;
})
) {
globals.Map = collectionShims.Map;
globals.Set = collectionShims.Set;
}
}
// Shim incomplete iterator implementations.
addIterator(Object.getPrototypeOf((new globals.Map()).keys()));
addIterator(Object.getPrototypeOf((new globals.Set()).keys()));
}
};
if (typeof define === 'function' && define.amd) {
define(main); // RequireJS
} else {
main(); // CommonJS and <script>
}
});
|
ajax/libs/jointjs/0.9.4/joint.clean.js
|
taydakov/cdnjs
|
/*! JointJS v0.9.3 - JavaScript diagramming library 2015-07-23
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// JointJS library.
// (c) 2011-2013 client IO
// Global namespace.
var joint = {
version: '0.9.3',
// `joint.dia` namespace.
dia: {},
// `joint.ui` namespace.
ui: {},
// `joint.layout` namespace.
layout: {},
// `joint.shapes` namespace.
shapes: {},
// `joint.format` namespace.
format: {},
// `joint.connectors` namespace.
connectors: {},
// `joint.routers` namespace.
routers: {},
util: {
// Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/.
hashCode: function(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
hash = ((hash << 5) - hash) + c;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
},
getByPath: function(obj, path, delim) {
delim = delim || '/';
var keys = path.split(delim);
var key;
while (keys.length) {
key = keys.shift();
if (Object(obj) === obj && key in obj) {
obj = obj[key];
} else {
return undefined;
}
}
return obj;
},
setByPath: function(obj, path, value, delim) {
delim = delim || '/';
var keys = path.split(delim);
var diver = obj;
var i = 0;
if (path.indexOf(delim) > -1) {
for (var len = keys.length; i < len - 1; i++) {
// diver creates an empty object if there is no nested object under such a key.
// This means that one can populate an empty nested object with setByPath().
diver = diver[keys[i]] || (diver[keys[i]] = {});
}
diver[keys[len - 1]] = value;
} else {
obj[path] = value;
}
return obj;
},
unsetByPath: function(obj, path, delim) {
delim = delim || '/';
// index of the last delimiter
var i = path.lastIndexOf(delim);
if (i > -1) {
// unsetting a nested attribute
var parent = joint.util.getByPath(obj, path.substr(0, i), delim);
if (parent) {
delete parent[path.slice(i + 1)];
}
} else {
// unsetting a primitive attribute
delete obj[path];
}
return obj;
},
flattenObject: function(obj, delim, stop) {
delim = delim || '/';
var ret = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
var shouldGoDeeper = typeof obj[key] === 'object';
if (shouldGoDeeper && stop && stop(obj[key])) {
shouldGoDeeper = false;
}
if (shouldGoDeeper) {
var flatObject = this.flattenObject(obj[key], delim, stop);
for (var flatKey in flatObject) {
if (!flatObject.hasOwnProperty(flatKey)) continue;
ret[key + delim + flatKey] = flatObject[flatKey];
}
} else {
ret[key] = obj[key];
}
}
return ret;
},
uuid: function() {
// credit: http://stackoverflow.com/posts/2117523/revisions
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16|0;
var v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
// Generate global unique id for obj and store it as a property of the object.
guid: function(obj) {
this.guid.id = this.guid.id || 1;
obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id);
return obj.id;
},
// Copy all the properties to the first argument from the following arguments.
// All the properties will be overwritten by the properties from the following
// arguments. Inherited properties are ignored.
mixin: function() {
var target = arguments[0];
for (var i = 1, l = arguments.length; i < l; i++) {
var extension = arguments[i];
// Only functions and objects can be mixined.
if ((Object(extension) !== extension) &&
!_.isFunction(extension) &&
(extension === null || extension === undefined)) {
continue;
}
_.each(extension, function(copy, key) {
if (this.mixin.deep && (Object(copy) === copy)) {
if (!target[key]) {
target[key] = _.isArray(copy) ? [] : {};
}
this.mixin(target[key], copy);
return;
}
if (target[key] !== copy) {
if (!this.mixin.supplement || !target.hasOwnProperty(key)) {
target[key] = copy;
}
}
}, this);
}
return target;
},
// Copy all properties to the first argument from the following
// arguments only in case if they don't exists in the first argument.
// All the function propererties in the first argument will get
// additional property base pointing to the extenders same named
// property function's call method.
supplement: function() {
this.mixin.supplement = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.supplement = false;
return ret;
},
// Same as `mixin()` but deep version.
deepMixin: function() {
this.mixin.deep = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.deep = false;
return ret;
},
// Same as `supplement()` but deep version.
deepSupplement: function() {
this.mixin.deep = this.mixin.supplement = true;
var ret = this.mixin.apply(this, arguments);
this.mixin.deep = this.mixin.supplement = false;
return ret;
},
normalizeEvent: function(evt) {
return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt;
},
nextFrame:(function() {
var raf;
var client = typeof window != 'undefined';
if (client) {
raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
}
if (!raf) {
var lastTime = 0;
raf = function(callback) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
return client ? _.bind(raf, window) : raf;
})(),
cancelFrame: (function() {
var caf;
var client = typeof window != 'undefined';
if (client) {
caf = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.oCancelAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame ||
window.mozCancelRequestAnimationFrame;
}
caf = caf || clearTimeout;
return client ? _.bind(caf, window) : caf;
})(),
shapePerimeterConnectionPoint: function(linkView, view, magnet, reference) {
var bbox;
var spot;
if (!magnet) {
// There is no magnet, try to make the best guess what is the
// wrapping SVG element. This is because we want this "smart"
// connection points to work out of the box without the
// programmer to put magnet marks to any of the subelements.
// For example, we want the functoin to work on basic.Path elements
// without any special treatment of such elements.
// The code below guesses the wrapping element based on
// one simple assumption. The wrapping elemnet is the
// first child of the scalable group if such a group exists
// or the first child of the rotatable group if not.
// This makese sense because usually the wrapping element
// is below any other sub element in the shapes.
var scalable = view.$('.scalable')[0];
var rotatable = view.$('.rotatable')[0];
if (scalable && scalable.firstChild) {
magnet = scalable.firstChild;
} else if (rotatable && rotatable.firstChild) {
magnet = rotatable.firstChild;
}
}
if (magnet) {
spot = V(magnet).findIntersection(reference, linkView.paper.viewport);
if (!spot) {
bbox = g.rect(V(magnet).bbox(false, linkView.paper.viewport));
}
} else {
bbox = view.model.getBBox();
spot = bbox.intersectionWithLineFromCenterToPoint(reference);
}
return spot || bbox.center();
},
breakText: function(text, size, styles, opt) {
opt = opt || {};
var width = size.width;
var height = size.height;
var svgDocument = opt.svgDocument || V('svg').node;
var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node;
var textSpan = textElement.firstChild;
var textNode = document.createTextNode('');
textSpan.appendChild(textNode);
svgDocument.appendChild(textElement);
if (!opt.svgDocument) {
document.body.appendChild(svgDocument);
}
var words = text.split(' ');
var full = [];
var lines = [];
var p;
for (var i = 0, l = 0, len = words.length; i < len; i++) {
var word = words[i];
textNode.data = lines[l] ? lines[l] + ' ' + word : word;
if (textSpan.getComputedTextLength() <= width) {
// the current line fits
lines[l] = textNode.data;
if (p) {
// We were partitioning. Put rest of the word onto next line
full[l++] = true;
// cancel partitioning
p = 0;
}
} else {
if (!lines[l] || p) {
var partition = !!p;
p = word.length - 1;
if (partition || !p) {
// word has only one character.
if (!p) {
if (!lines[l]) {
// we won't fit this text within our rect
lines = [];
break;
}
// partitioning didn't help on the non-empty line
// try again, but this time start with a new line
// cancel partitions created
words.splice(i, 2, word + words[i + 1]);
// adjust word length
len--;
full[l++] = true;
i--;
continue;
}
// move last letter to the beginning of the next word
words[i] = word.substring(0, p);
words[i + 1] = word.substring(p) + words[i + 1];
} else {
// We initiate partitioning
// split the long word into two words
words.splice(i, 1, word.substring(0, p), word.substring(p));
// adjust words length
len++;
if (l && !full[l - 1]) {
// if the previous line is not full, try to fit max part of
// the current word there
l--;
}
}
i--;
continue;
}
l++;
i--;
}
// if size.height is defined we have to check whether the height of the entire
// text exceeds the rect height
if (typeof height !== 'undefined') {
// get line height as text height / 0.8 (as text height is approx. 0.8em
// and line height is 1em. See vectorizer.text())
var lh = lh || textElement.getBBox().height * 1.25;
if (lh * lines.length > height) {
// remove overflowing lines
lines.splice(Math.floor(height / lh));
break;
}
}
}
if (opt.svgDocument) {
// svg document was provided, remove the text element only
svgDocument.removeChild(textElement);
} else {
// clean svg document
document.body.removeChild(svgDocument);
}
return lines.join('\n');
},
imageToDataUri: function(url, callback) {
if (!url || url.substr(0, 'data:'.length) === 'data:') {
// No need to convert to data uri if it is already in data uri.
// This not only convenient but desired. For example,
// IE throws a security error if data:image/svg+xml is used to render
// an image to the canvas and an attempt is made to read out data uri.
// Now if our image is already in data uri, there is no need to render it to the canvas
// and so we can bypass this error.
// Keep the async nature of the function.
return setTimeout(function() { callback(null, url); }, 0);
}
var canvas = document.createElement('canvas');
var img = document.createElement('img');
img.onload = function() {
var ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
try {
// Guess the type of the image from the url suffix.
var suffix = (url.split('.').pop()) || 'png';
// A little correction for JPEGs. There is no image/jpg mime type but image/jpeg.
var type = 'image/' + (suffix === 'jpg') ? 'jpeg' : suffix;
var dataUri = canvas.toDataURL(type);
} catch (e) {
if (/\.svg$/.test(url)) {
// IE throws a security error if we try to render an SVG into the canvas.
// Luckily for us, we don't need canvas at all to convert
// SVG to data uri. We can just use AJAX to load the SVG string
// and construct the data uri ourselves.
var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url, false);
xhr.send(null);
var svg = xhr.responseText;
return callback(null, 'data:image/svg+xml,' + encodeURIComponent(svg));
}
console.error(img.src, 'fails to convert', e);
}
callback(null, dataUri);
};
img.ononerror = function() {
callback(new Error('Failed to load image.'));
};
img.src = url;
},
getElementBBox: function(el) {
var $el = $(el);
var offset = $el.offset();
var bbox;
if (el.ownerSVGElement) {
// Use Vectorizer to get the dimensions of the element if it is an SVG element.
bbox = V(el).bbox();
// getBoundingClientRect() used in jQuery.fn.offset() takes into account `stroke-width`
// in Firefox only. So clientRect width/height and getBBox width/height in FF don't match.
// To unify this across all browsers we add the `stroke-width` (left & top) back to
// the calculated offset.
var crect = el.getBoundingClientRect();
var strokeWidthX = (crect.width - bbox.width) / 2;
var strokeWidthY = (crect.height - bbox.height) / 2;
// The `bbox()` returns coordinates relative to the SVG viewport, therefore, use the
// ones returned from the `offset()` method that are relative to the document.
bbox.x = offset.left + strokeWidthX;
bbox.y = offset.top + strokeWidthY;
} else {
bbox = { x: offset.left, y: offset.top, width: $el.outerWidth(), height: $el.outerHeight() };
}
return bbox;
},
// Highly inspired by the jquery.sortElements plugin by Padolsey.
// See http://james.padolsey.com/javascript/sorting-elements-with-jquery/.
sortElements: function(elements, comparator) {
var $elements = $(elements);
var placements = $elements.map(function() {
var sortElement = this;
var parentNode = sortElement.parentNode;
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
var nextSibling = parentNode.insertBefore(document.createTextNode(''), sortElement.nextSibling);
return function() {
if (parentNode === this) {
throw new Error('You can\'t sort elements if any one is a descendant of another.');
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return Array.prototype.sort.call($elements, comparator).each(function(i) {
placements[i].call(this);
});
},
// Return a new object with all for sides (top, bottom, left and right) in it.
// Value of each side is taken from the given argument (either number or object).
// Default value for a side is 0.
// Examples:
// joint.util.normalizeSides(5) --> { top: 5, left: 5, right: 5, bottom: 5 }
// joint.util.normalizeSides({ left: 5 }) --> { top: 0, left: 5, right: 0, bottom: 0 }
normalizeSides: function(box) {
if (Object(box) !== box) {
box = box || 0;
return { top: box, bottom: box, left: box, right: box };
}
return {
top: box.top || 0,
bottom: box.bottom || 0,
left: box.left || 0,
right: box.right || 0
};
},
timing: {
linear: function(t) {
return t;
},
quad: function(t) {
return t * t;
},
cubic: function(t) {
return t * t * t;
},
inout: function(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t;
var t3 = t2 * t;
return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
},
exponential: function(t) {
return Math.pow(2, 10 * (t - 1));
},
bounce: function(t) {
for (var a = 0, b = 1; 1; a += b, b /= 2) {
if (t >= (7 - 4 * a) / 11) {
var q = (11 - 6 * a - 11 * t) / 4;
return -q * q + b * b;
}
}
},
reverse: function(f) {
return function(t) {
return 1 - f(1 - t);
};
},
reflect: function(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
};
},
clamp: function(f, n, x) {
n = n || 0;
x = x || 1;
return function(t) {
var r = f(t);
return r < n ? n : r > x ? x : r;
};
},
back: function(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
},
elastic: function(x) {
if (!x) x = 1.5;
return function(t) {
return Math.pow(2, 10 * (t - 1)) * Math.cos(20 * Math.PI * x / 3 * t);
};
}
},
interpolate: {
number: function(a, b) {
var d = b - a;
return function(t) { return a + d * t; };
},
object: function(a, b) {
var s = _.keys(a);
return function(t) {
var i, p;
var r = {};
for (i = s.length - 1; i != -1; i--) {
p = s[i];
r[p] = a[p] + (b[p] - a[p]) * t;
}
return r;
};
},
hexColor: function(a, b) {
var ca = parseInt(a.slice(1), 16);
var cb = parseInt(b.slice(1), 16);
var ra = ca & 0x0000ff;
var rd = (cb & 0x0000ff) - ra;
var ga = ca & 0x00ff00;
var gd = (cb & 0x00ff00) - ga;
var ba = ca & 0xff0000;
var bd = (cb & 0xff0000) - ba;
return function(t) {
var r = (ra + rd * t) & 0x000000ff;
var g = (ga + gd * t) & 0x0000ff00;
var b = (ba + bd * t) & 0x00ff0000;
return '#' + (1 << 24 | r | g | b ).toString(16).slice(1);
};
},
unit: function(a, b) {
var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/;
var ma = r.exec(a);
var mb = r.exec(b);
var p = mb[1].indexOf('.');
var f = p > 0 ? mb[1].length - p - 1 : 0;
a = +ma[1];
var d = +mb[1] - a;
var u = ma[2];
return function(t) {
return (a + d * t).toFixed(f) + u;
};
}
},
// SVG filters.
filter: {
// `color` ... outline color
// `width`... outline width
// `opacity` ... outline opacity
// `margin` ... gap between outline and the element
outline: function(args) {
var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology in="SourceAlpha" result="morphedOuter" operator="dilate" radius="${outerRadius}" /><feMorphology in="SourceAlpha" result="morphedInner" operator="dilate" radius="${innerRadius}" /><feComposite result="morphedOuterColored" in="colored" in2="morphedOuter" operator="in"/><feComposite operator="xor" in="morphedOuterColored" in2="morphedInner" result="outline"/><feMerge><feMergeNode in="outline"/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
var margin = _.isFinite(args.margin) ? args.margin : 2;
var width = _.isFinite(args.width) ? args.width : 1;
return _.template(tpl, {
color: args.color || 'blue',
opacity: _.isFinite(args.opacity) ? args.opacity : 1,
outerRadius: margin + width,
innerRadius: margin
});
},
// `color` ... color
// `width`... width
// `blur` ... blur
// `opacity` ... opacity
highlight: function(args) {
var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology result="morphed" in="SourceGraphic" operator="dilate" radius="${width}"/><feComposite result="composed" in="colored" in2="morphed" operator="in"/><feGaussianBlur result="blured" in="composed" stdDeviation="${blur}"/><feBlend in="SourceGraphic" in2="blured" mode="normal"/></filter>';
return _.template(tpl, {
color: args.color || 'red',
width: _.isFinite(args.width) ? args.width : 1,
blur: _.isFinite(args.blur) ? args.blur : 0,
opacity: _.isFinite(args.opacity) ? args.opacity : 1
});
},
// `x` ... horizontal blur
// `y` ... vertical blur (optional)
blur: function(args) {
var x = _.isFinite(args.x) ? args.x : 2;
return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', {
stdDeviation: _.isFinite(args.y) ? [x, args.y] : x
});
},
// `dx` ... horizontal shift
// `dy` ... vertical shift
// `blur` ... blur
// `color` ... color
// `opacity` ... opacity
dropShadow: function(args) {
var tpl = 'SVGFEDropShadowElement' in window
? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>'
: '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
return _.template(tpl, {
dx: args.dx || 0,
dy: args.dy || 0,
opacity: _.isFinite(args.opacity) ? args.opacity : 1,
color: args.color || 'black',
blur: _.isFinite(args.blur) ? args.blur : 4
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged.
grayscale: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', {
a: 0.2126 + 0.7874 * (1 - amount),
b: 0.7152 - 0.7152 * (1 - amount),
c: 0.0722 - 0.0722 * (1 - amount),
d: 0.2126 - 0.2126 * (1 - amount),
e: 0.7152 + 0.2848 * (1 - amount),
f: 0.0722 - 0.0722 * (1 - amount),
g: 0.2126 - 0.2126 * (1 - amount),
h: 0.0722 + 0.9278 * (1 - amount)
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged.
sepia: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', {
a: 0.393 + 0.607 * (1 - amount),
b: 0.769 - 0.769 * (1 - amount),
c: 0.189 - 0.189 * (1 - amount),
d: 0.349 - 0.349 * (1 - amount),
e: 0.686 + 0.314 * (1 - amount),
f: 0.168 - 0.168 * (1 - amount),
g: 0.272 - 0.272 * (1 - amount),
h: 0.534 - 0.534 * (1 - amount),
i: 0.131 + 0.869 * (1 - amount)
});
},
// `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged.
saturate: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', {
amount: 1 - amount
});
},
// `angle` ... the number of degrees around the color circle the input samples will be adjusted.
hueRotate: function(args) {
return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', {
angle: args.angle || 0
});
},
// `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged.
invert: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', {
amount: amount,
amount2: 1 - amount
});
},
// `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
brightness: function(args) {
return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', {
amount: _.isFinite(args.amount) ? args.amount : 1
});
},
// `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged.
contrast: function(args) {
var amount = _.isFinite(args.amount) ? args.amount : 1;
return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', {
amount: amount,
amount2: .5 - amount / 2
});
}
},
format: {
// Formatting numbers via the Python Format Specification Mini-language.
// See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
// Heavilly inspired by the D3.js library implementation.
number: function(specifier, value, locale) {
locale = locale || {
currency: ['$', ''],
decimal: '.',
thousands: ',',
grouping: [3]
};
// See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language.
// [[fill]align][sign][symbol][0][width][,][.precision][type]
var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
var match = re.exec(specifier);
var fill = match[1] || ' ';
var align = match[2] || '>';
var sign = match[3] || '';
var symbol = match[4] || '';
var zfill = match[5];
var width = +match[6];
var comma = match[7];
var precision = match[8];
var type = match[9];
var scale = 1;
var prefix = '';
var suffix = '';
var integer = false;
if (precision) precision = +precision.substring(1);
if (zfill || fill === '0' && align === '=') {
zfill = fill = '0';
align = '=';
if (comma) width -= Math.floor((width - 1) / 4);
}
switch (type) {
case 'n': comma = true; type = 'g'; break;
case '%': scale = 100; suffix = '%'; type = 'f'; break;
case 'p': scale = 100; suffix = '%'; type = 'r'; break;
case 'b':
case 'o':
case 'x':
case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase();
case 'c':
case 'd': integer = true; precision = 0; break;
case 's': scale = -1; type = 'r'; break;
}
if (symbol === '$') {
prefix = locale.currency[0];
suffix = locale.currency[1];
}
// If no precision is specified for `'r'`, fallback to general notation.
if (type == 'r' && !precision) type = 'g';
// Ensure that the requested precision is in the supported range.
if (precision != null) {
if (type == 'g') precision = Math.max(1, Math.min(21, precision));
else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision));
}
var zcomma = zfill && comma;
// Return the empty string for floats formatted as ints.
if (integer && (value % 1)) return '';
// Convert negative to positive, and record the sign prefix.
var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign;
var fullSuffix = suffix;
// Apply the scale, computing it from the value's exponent for si format.
// Preserve the existing suffix, if any, such as the currency symbol.
if (scale < 0) {
var unit = this.prefix(value, precision);
value = unit.scale(value);
fullSuffix = unit.symbol + suffix;
} else {
value *= scale;
}
// Convert to the desired precision.
value = this.convert(type, value, precision);
// Break the value into the integer part (before) and decimal part (after).
var i = value.lastIndexOf('.');
var before = i < 0 ? value : value.substring(0, i);
var after = i < 0 ? '' : locale.decimal + value.substring(i + 1);
function formatGroup(value) {
var i = value.length;
var t = [];
var j = 0;
var g = locale.grouping[0];
while (i > 0 && g > 0) {
t.push(value.substring(i -= g, i + g));
g = locale.grouping[j = (j + 1) % locale.grouping.length];
}
return t.reverse().join(locale.thousands);
}
// If the fill character is not `'0'`, grouping is applied before padding.
if (!zfill && comma && locale.grouping) {
before = formatGroup(before);
}
var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length);
var padding = length < width ? new Array(length = width - length + 1).join(fill) : '';
// If the fill character is `'0'`, grouping is applied after padding.
if (zcomma) before = formatGroup(padding + before);
// Apply prefix.
negative += prefix;
// Rejoin integer and decimal parts.
value = before + after;
return (align === '<' ? negative + value + padding
: align === '>' ? padding + negative + value
: align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length)
: negative + (zcomma ? value : padding + value)) + fullSuffix;
},
// Formatting string via the Python Format string.
// See https://docs.python.org/2/library/string.html#format-string-syntax)
string: function(formatString, value) {
var fieldDelimiterIndex;
var fieldDelimiter = '{';
var endPlaceholder = false;
var formattedStringArray = [];
while ((fieldDelimiterIndex = formatString.indexOf(fieldDelimiter)) !== -1) {
var pieceFormatedString, formatSpec, fieldName;
pieceFormatedString = formatString.slice(0, fieldDelimiterIndex);
if (endPlaceholder) {
formatSpec = pieceFormatedString.split(':');
fieldName = formatSpec.shift().split('.');
pieceFormatedString = value;
for (var i = 0; i < fieldName.length; i++)
pieceFormatedString = pieceFormatedString[fieldName[i]];
if (formatSpec.length)
pieceFormatedString = this.number(formatSpec, pieceFormatedString);
}
formattedStringArray.push(pieceFormatedString);
formatString = formatString.slice(fieldDelimiterIndex + 1);
fieldDelimiter = (endPlaceholder = !endPlaceholder) ? '}' : '{';
}
formattedStringArray.push(formatString);
return formattedStringArray.join('');
},
convert: function(type, value, precision) {
switch (type) {
case 'b': return value.toString(2);
case 'c': return String.fromCharCode(value);
case 'o': return value.toString(8);
case 'x': return value.toString(16);
case 'X': return value.toString(16).toUpperCase();
case 'g': return value.toPrecision(precision);
case 'e': return value.toExponential(precision);
case 'f': return value.toFixed(precision);
case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision))));
default: return value + '';
}
},
round: function(value, precision) {
return precision
? Math.round(value * (precision = Math.pow(10, precision))) / precision
: Math.round(value);
},
precision: function(value, precision) {
return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1);
},
prefix: function(value, precision) {
var prefixes = _.map(['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], function(d, i) {
var k = Math.pow(10, abs(8 - i) * 3);
return {
scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; },
symbol: d
};
});
var i = 0;
if (value) {
if (value < 0) value *= -1;
if (precision) value = this.round(value, this.precision(value, precision));
i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
}
return prefixes[8 + i / 3];
}
}
}
};
// JointJS, the JavaScript diagramming library.
// (c) 2011-2013 client IO
joint.dia.GraphCells = Backbone.Collection.extend({
initialize: function() {
// Backbone automatically doesn't trigger re-sort if models attributes are changed later when
// they're already in the collection. Therefore, we're triggering sort manually here.
this.on('change:z', this.sort, this);
},
model: function(attrs, options) {
if (attrs.type === 'link') {
return new joint.dia.Link(attrs, options);
}
var module = attrs.type.split('.')[0];
var entity = attrs.type.split('.')[1];
if (joint.shapes[module] && joint.shapes[module][entity]) {
return new joint.shapes[module][entity](attrs, options);
}
return new joint.dia.Element(attrs, options);
},
// `comparator` makes it easy to sort cells based on their `z` index.
comparator: function(model) {
return model.get('z') || 0;
},
// Get all inbound and outbound links connected to the cell `model`.
getConnectedLinks: function(model, opt) {
opt = opt || {};
if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) {
opt.inbound = opt.outbound = true;
}
var links = this.filter(function(cell) {
var source = cell.get('source');
var target = cell.get('target');
return (source && source.id === model.id && opt.outbound) ||
(target && target.id === model.id && opt.inbound);
});
// option 'deep' returns all links that are connected to any of the descendent cell
// and are not descendents itself
if (opt.deep) {
var embeddedCells = model.getEmbeddedCells({ deep: true });
_.each(this.difference(links, embeddedCells), function(cell) {
if (opt.outbound) {
var source = cell.get('source');
if (source && source.id && _.find(embeddedCells, { id: source.id })) {
links.push(cell);
return; // prevent a loop link to be pushed twice
}
}
if (opt.inbound) {
var target = cell.get('target');
if (target && target.id && _.find(embeddedCells, { id: target.id })) {
links.push(cell);
}
}
});
}
return links;
},
getCommonAncestor: function(/* cells */) {
var cellsAncestors = _.map(arguments, function(cell) {
var ancestors = [cell.id];
var parentId = cell.get('parent');
while (parentId) {
ancestors.push(parentId);
parentId = this.get(parentId).get('parent');
}
return ancestors;
}, this);
cellsAncestors = _.sortBy(cellsAncestors, 'length');
var commonAncestor = _.find(cellsAncestors.shift(), function(ancestor) {
return _.every(cellsAncestors, function(cellAncestors) {
return _.contains(cellAncestors, ancestor);
});
});
return this.get(commonAncestor);
},
// Return the bounding box of all cells in array provided. If no array
// provided returns bounding box of all cells. Links are being ignored.
getBBox: function(cells) {
cells = cells || this.models;
var origin = { x: Infinity, y: Infinity };
var corner = { x: -Infinity, y: -Infinity };
_.each(cells, function(cell) {
// Links has no bounding box defined on the model.
if (cell.isLink()) return;
var bbox = cell.getBBox();
origin.x = Math.min(origin.x, bbox.x);
origin.y = Math.min(origin.y, bbox.y);
corner.x = Math.max(corner.x, bbox.x + bbox.width);
corner.y = Math.max(corner.y, bbox.y + bbox.height);
});
return g.rect(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}
});
joint.dia.Graph = Backbone.Model.extend({
initialize: function(attrs, opt) {
// Passing `cellModel` function in the options object to graph allows for
// setting models based on attribute objects. This is especially handy
// when processing JSON graphs that are in a different than JointJS format.
this.set('cells', new joint.dia.GraphCells([], { model: opt && opt.cellModel }));
// Make all the events fired in the `cells` collection available.
// to the outside world.
this.get('cells').on('all', this.trigger, this);
this.get('cells').on('remove', this.removeCell, this);
},
toJSON: function() {
// Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections.
// It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely.
var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
json.cells = this.get('cells').toJSON();
return json;
},
fromJSON: function(json, opt) {
if (!json.cells) {
throw new Error('Graph JSON must contain cells array.');
}
this.set(_.omit(json, 'cells'), opt);
this.resetCells(json.cells, opt);
},
clear: function(opt) {
this.trigger('batch:start');
this.get('cells').remove(this.get('cells').models, opt);
this.trigger('batch:stop');
},
_prepareCell: function(cell) {
if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) {
cell.set('z', this.maxZIndex() + 1, { silent: true });
} else if (_.isUndefined(cell.z)) {
cell.z = this.maxZIndex() + 1;
}
return cell;
},
maxZIndex: function() {
var lastCell = this.get('cells').last();
return lastCell ? (lastCell.get('z') || 0) : 0;
},
addCell: function(cell, options) {
if (_.isArray(cell)) {
return this.addCells(cell, options);
}
this.get('cells').add(this._prepareCell(cell), options || {});
return this;
},
addCells: function(cells, options) {
options = options || {};
options.position = cells.length;
_.each(cells, function(cell) {
options.position--;
this.addCell(cell, options);
}, this);
return this;
},
// When adding a lot of cells, it is much more efficient to
// reset the entire cells collection in one go.
// Useful for bulk operations and optimizations.
resetCells: function(cells, opt) {
this.get('cells').reset(_.map(cells, this._prepareCell, this), opt);
return this;
},
removeCell: function(cell, collection, options) {
// Applications might provide a `disconnectLinks` option set to `true` in order to
// disconnect links when a cell is removed rather then removing them. The default
// is to remove all the associated links.
if (options && options.disconnectLinks) {
this.disconnectLinks(cell, options);
} else {
this.removeLinks(cell, options);
}
// Silently remove the cell from the cells collection. Silently, because
// `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is
// then propagated to the graph model. If we didn't remove the cell silently, two `remove` events
// would be triggered on the graph model.
this.get('cells').remove(cell, { silent: true });
},
// Get a cell by `id`.
getCell: function(id) {
return this.get('cells').get(id);
},
getElements: function() {
return this.get('cells').filter(function(cell) {
return cell instanceof joint.dia.Element;
});
},
getLinks: function() {
return this.get('cells').filter(function(cell) {
return cell instanceof joint.dia.Link;
});
},
// Get all inbound and outbound links connected to the cell `model`.
getConnectedLinks: function(model, opt) {
return this.get('cells').getConnectedLinks(model, opt);
},
getNeighbors: function(el) {
var links = this.getConnectedLinks(el);
var neighbors = [];
var cells = this.get('cells');
_.each(links, function(link) {
var source = link.get('source');
var target = link.get('target');
// Discard if it is a point.
if (!source.x) {
var sourceElement = cells.get(source.id);
if (sourceElement !== el) {
neighbors.push(sourceElement);
}
}
if (!target.x) {
var targetElement = cells.get(target.id);
if (targetElement !== el) {
neighbors.push(targetElement);
}
}
});
return neighbors;
},
// Disconnect links connected to the cell `model`.
disconnectLinks: function(model, options) {
_.each(this.getConnectedLinks(model), function(link) {
link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0), options);
});
},
// Remove links connected to the cell `model` completely.
removeLinks: function(model, options) {
_.invoke(this.getConnectedLinks(model), 'remove', options);
},
// Find all views at given point
findModelsFromPoint: function(p) {
return _.filter(this.getElements(), function(el) {
return el.getBBox().containsPoint(p);
});
},
// Find all views in given area
findModelsInArea: function(r) {
return _.filter(this.getElements(), function(el) {
return el.getBBox().intersect(r);
});
},
// Return the bounding box of all `elements`.
getBBox: function(/* elements */) {
var collection = this.get('cells');
return collection.getBBox.apply(collection, arguments);
},
getCommonAncestor: function(/* cells */) {
var collection = this.get('cells');
return collection.getCommonAncestor.apply(collection, arguments);
}
});
// JointJS.
// (c) 2011-2013 client IO
// joint.dia.Cell base model.
// --------------------------
joint.dia.Cell = Backbone.Model.extend({
// This is the same as Backbone.Model with the only difference that is uses _.merge
// instead of just _.extend. The reason is that we want to mixin attributes set in upper classes.
constructor: function(attributes, options) {
var defaults;
var attrs = attributes || {};
this.cid = _.uniqueId('c');
this.attributes = {};
if (options && options.collection) this.collection = options.collection;
if (options && options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
//<custom code>
// Replaced the call to _.defaults with _.merge.
attrs = _.merge({}, defaults, attrs);
//</custom code>
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
},
toJSON: function() {
var defaultAttrs = this.constructor.prototype.defaults.attrs || {};
var attrs = this.attributes.attrs;
var finalAttrs = {};
// Loop through all the attributes and
// omit the default attributes as they are implicitly reconstructable by the cell 'type'.
_.each(attrs, function(attr, selector) {
var defaultAttr = defaultAttrs[selector];
_.each(attr, function(value, name) {
// attr is mainly flat though it might have one more level (consider the `style` attribute).
// Check if the `value` is object and if yes, go one level deep.
if (_.isObject(value) && !_.isArray(value)) {
_.each(value, function(value2, name2) {
if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) {
finalAttrs[selector] = finalAttrs[selector] || {};
(finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2;
}
});
} else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) {
// `value` is not an object, default attribute for such a selector does not exist
// or it is different than the attribute value set on the model.
finalAttrs[selector] = finalAttrs[selector] || {};
finalAttrs[selector][name] = value;
}
});
});
var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs'));
//var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs')));
attributes.attrs = finalAttrs;
return attributes;
},
initialize: function(options) {
if (!options || !options.id) {
this.set('id', joint.util.uuid(), { silent: true });
}
this._transitionIds = {};
// Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes.
this.processPorts();
this.on('change:attrs', this.processPorts, this);
},
processPorts: function() {
// Whenever `attrs` changes, we extract ports from the `attrs` object and store it
// in a more accessible way. Also, if any port got removed and there were links that had `target`/`source`
// set to that port, we remove those links as well (to follow the same behaviour as
// with a removed element).
var previousPorts = this.ports;
// Collect ports from the `attrs` object.
var ports = {};
_.each(this.get('attrs'), function(attrs, selector) {
if (attrs && attrs.port) {
// `port` can either be directly an `id` or an object containing an `id` (and potentially other data).
if (!_.isUndefined(attrs.port.id)) {
ports[attrs.port.id] = attrs.port;
} else {
ports[attrs.port] = { id: attrs.port };
}
}
});
// Collect ports that have been removed (compared to the previous ports) - if any.
// Use hash table for quick lookup.
var removedPorts = {};
_.each(previousPorts, function(port, id) {
if (!ports[id]) removedPorts[id] = true;
});
// Remove all the incoming/outgoing links that have source/target port set to any of the removed ports.
if (this.collection && !_.isEmpty(removedPorts)) {
var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true });
_.each(inboundLinks, function(link) {
if (removedPorts[link.get('target').port]) link.remove();
});
var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true });
_.each(outboundLinks, function(link) {
if (removedPorts[link.get('source').port]) link.remove();
});
}
// Update the `ports` object.
this.ports = ports;
},
remove: function(opt) {
opt = opt || {};
var collection = this.collection;
if (collection) {
collection.trigger('batch:start', { batchName: 'remove' });
}
// First, unembed this cell from its parent cell if there is one.
var parentCellId = this.get('parent');
if (parentCellId) {
var parentCell = this.collection && this.collection.get(parentCellId);
parentCell.unembed(this);
}
_.invoke(this.getEmbeddedCells(), 'remove', opt);
this.trigger('remove', this, this.collection, opt);
if (collection) {
collection.trigger('batch:stop', { batchName: 'remove' });
}
return this;
},
toFront: function(opt) {
if (this.collection) {
opt = opt || {};
var z = (this.collection.last().get('z') || 0) + 1;
this.trigger('batch:start', { batchName: 'to-front' }).set('z', z, opt);
if (opt.deep) {
var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true });
_.each(cells, function(cell) { cell.set('z', ++z, opt); });
}
this.trigger('batch:stop', { batchName: 'to-front' });
}
return this;
},
toBack: function(opt) {
if (this.collection) {
opt = opt || {};
var z = (this.collection.first().get('z') || 0) - 1;
this.trigger('batch:start', { batchName: 'to-back' });
if (opt.deep) {
var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true });
_.eachRight(cells, function(cell) { cell.set('z', z--, opt); });
}
this.set('z', z, opt).trigger('batch:stop', { batchName: 'to-back' });
}
return this;
},
embed: function(cell, opt) {
if (this == cell || this.isEmbeddedIn(cell)) {
throw new Error('Recursive embedding not allowed.');
} else {
this.trigger('batch:start', { batchName: 'embed' });
var embeds = _.clone(this.get('embeds') || []);
// We keep all element ids after links ids.
embeds[cell.isLink() ? 'unshift' : 'push'](cell.id);
cell.set('parent', this.id, opt);
this.set('embeds', _.uniq(embeds), opt);
this.trigger('batch:stop', { batchName: 'embed' });
}
return this;
},
unembed: function(cell, opt) {
this.trigger('batch:start', { batchName: 'unembed' });
cell.unset('parent', opt);
this.set('embeds', _.without(this.get('embeds'), cell.id), opt);
this.trigger('batch:stop', { batchName: 'unembed' });
return this;
},
// Return an array of ancestor cells.
// The array is ordered from the parent of the cell
// to the most distant ancestor.
getAncestors: function() {
var ancestors = [];
var parentId = this.get('parent');
if (this.collection === undefined)
return ancestors;
while (parentId !== undefined) {
var parent = this.collection.get(parentId);
if (parent !== undefined) {
ancestors.push(parent);
parentId = parent.get('parent');
} else {
break;
}
}
return ancestors;
},
getEmbeddedCells: function(opt) {
opt = opt || {};
// Cell models can only be retrieved when this element is part of a collection.
// There is no way this element knows about other cells otherwise.
// This also means that calling e.g. `translate()` on an element with embeds before
// adding it to a graph does not translate its embeds.
if (this.collection) {
var cells;
if (opt.deep) {
if (opt.breadthFirst) {
// breadthFirst algorithm
cells = [];
var queue = this.getEmbeddedCells();
while (queue.length > 0) {
var parent = queue.shift();
cells.push(parent);
queue.push.apply(queue, parent.getEmbeddedCells());
}
} else {
// depthFirst algorithm
cells = this.getEmbeddedCells();
_.each(cells, function(cell) {
cells.push.apply(cells, cell.getEmbeddedCells(opt));
});
}
} else {
cells = _.map(this.get('embeds'), this.collection.get, this.collection);
}
return cells;
}
return [];
},
isEmbeddedIn: function(cell, opt) {
var cellId = _.isString(cell) ? cell : cell.id;
var parentId = this.get('parent');
opt = _.defaults({ deep: true }, opt);
// See getEmbeddedCells().
if (this.collection && opt.deep) {
while (parentId) {
if (parentId == cellId) {
return true;
}
parentId = this.collection.get(parentId).get('parent');
}
return false;
} else {
// When this cell is not part of a collection check
// at least whether it's a direct child of given cell.
return parentId == cellId;
}
},
clone: function(opt) {
opt = opt || {};
var clone = Backbone.Model.prototype.clone.apply(this, arguments);
// We don't want the clone to have the same ID as the original.
clone.set('id', joint.util.uuid(), { silent: true });
clone.set('embeds', '');
if (!opt.deep) return clone;
// The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`,
// the return value is an array of all the embedded clones created.
var embeds = _.sortBy(this.getEmbeddedCells(), function(cell) {
// Sort embeds that links come before elements.
return cell instanceof joint.dia.Element;
});
var clones = [clone];
// This mapping stores cloned links under the `id`s of they originals.
// This prevents cloning a link more then once. Consider a link 'self loop' for example.
var linkCloneMapping = {};
_.each(embeds, function(embed) {
var embedClones = embed.clone({ deep: true });
// Embed the first clone returned from `clone({ deep: true })` above. The first
// cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case.
clone.embed(embedClones[0]);
_.each(embedClones, function(embedClone) {
if (embedClone instanceof joint.dia.Link) {
if (embedClone.get('source').id == this.id) {
embedClone.prop('source', { id: clone.id });
}
if (embedClone.get('target').id == this.id) {
embedClone.prop('target', { id: clone.id });
}
linkCloneMapping[embed.id] = embedClone;
// Skip links. Inbound/outbound links are not relevant for them.
return;
}
clones.push(embedClone);
// Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`.
var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true });
_.each(inboundLinks, function(link) {
var linkClone = linkCloneMapping[link.id] || link.clone();
// Make sure we don't clone a link more then once.
linkCloneMapping[link.id] = linkClone;
linkClone.prop('target', { id: embedClone.id });
});
// Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`.
var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true });
_.each(outboundLinks, function(link) {
var linkClone = linkCloneMapping[link.id] || link.clone();
// Make sure we don't clone a link more then once.
linkCloneMapping[link.id] = linkClone;
linkClone.prop('source', { id: embedClone.id });
});
}, this);
}, this);
// Add link clones to the array of all the new clones.
clones = clones.concat(_.values(linkCloneMapping));
return clones;
},
// A convenient way to set nested properties.
// This method merges the properties you'd like to set with the ones
// stored in the cell and makes sure change events are properly triggered.
// You can either set a nested property with one object
// or use a property path.
// The most simple use case is:
// `cell.prop('name/first', 'John')` or
// `cell.prop({ name: { first: 'John' } })`.
// Nested arrays are supported too:
// `cell.prop('series/0/data/0/degree', 50)` or
// `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`.
prop: function(props, value, opt) {
var delim = '/';
if (_.isString(props)) {
// Get/set an attribute by a special path syntax that delimits
// nested objects by the colon character.
if (arguments.length > 1) {
var path = props;
var pathArray = path.split('/');
var property = pathArray[0];
opt = opt || {};
opt.propertyPath = path;
opt.propertyValue = value;
if (pathArray.length == 1) {
// Property is not nested. We can simply use `set()`.
return this.set(property, value, opt);
}
var update = {};
// Initialize the nested object. Subobjects are either arrays or objects.
// An empty array is created if the sub-key is an integer. Otherwise, an empty object is created.
// Note that this imposes a limitation on object keys one can use with Inspector.
// Pure integer keys will cause issues and are therefore not allowed.
var initializer = update;
var prevProperty = property;
_.each(_.rest(pathArray), function(key) {
initializer = initializer[prevProperty] = (_.isFinite(Number(key)) ? [] : {});
prevProperty = key;
});
// Fill update with the `value` on `path`.
update = joint.util.setByPath(update, path, value, '/');
var baseAttributes = _.merge({}, this.attributes);
// if rewrite mode enabled, we replace value referenced by path with
// the new one (we don't merge).
opt.rewrite && joint.util.unsetByPath(baseAttributes, path, '/');
// Merge update with the model attributes.
var attributes = _.merge(baseAttributes, update);
// Finally, set the property to the updated attributes.
return this.set(property, attributes[property], opt);
} else {
return joint.util.getByPath(this.attributes, props, delim);
}
}
return this.set(_.merge({}, this.attributes, props), value);
},
// A convient way to unset nested properties
removeProp: function(path, opt) {
// Once a property is removed from the `attrs` attribute
// the cellView will recognize a `dirty` flag and rerender itself
// in order to remove the attribute from SVG element.
opt = opt || {};
opt.dirty = true;
var pathArray = path.split('/');
if (pathArray.length === 1) {
// A top level property
return this.unset(path, opt);
}
// A nested property
var property = pathArray[0];
var nestedPath = pathArray.slice(1).join('/');
var propertyValue = _.merge({}, this.get(property));
joint.util.unsetByPath(propertyValue, nestedPath, '/');
return this.set(property, propertyValue, opt);
},
// A convenient way to set nested attributes.
attr: function(attrs, value, opt) {
var args = Array.prototype.slice.call(arguments);
if (_.isString(attrs)) {
// Get/set an attribute by a special path syntax that delimits
// nested objects by the colon character.
args[0] = 'attrs/' + attrs;
} else {
args[0] = { 'attrs' : attrs };
}
return this.prop.apply(this, args);
},
// A convenient way to unset nested attributes
removeAttr: function(path, opt) {
if (_.isArray(path)) {
_.each(path, function(p) { this.removeAttr(p, opt); }, this);
return this;
}
return this.removeProp('attrs/' + path, opt);
},
transition: function(path, value, opt, delim) {
delim = delim || '/';
var defaults = {
duration: 100,
delay: 10,
timingFunction: joint.util.timing.linear,
valueFunction: joint.util.interpolate.number
};
opt = _.extend(defaults, opt);
var firstFrameTime = 0;
var interpolatingFunction;
var setter = _.bind(function(runtime) {
var id, progress, propertyValue, status;
firstFrameTime = firstFrameTime || runtime;
runtime -= firstFrameTime;
progress = runtime / opt.duration;
if (progress < 1) {
this._transitionIds[path] = id = joint.util.nextFrame(setter);
} else {
progress = 1;
delete this._transitionIds[path];
}
propertyValue = interpolatingFunction(opt.timingFunction(progress));
opt.transitionId = id;
this.prop(path, propertyValue, opt);
if (!id) this.trigger('transition:end', this, path);
}, this);
var initiator = _.bind(function(callback) {
this.stopTransitions(path);
interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value);
this._transitionIds[path] = joint.util.nextFrame(callback);
this.trigger('transition:start', this, path);
}, this);
return _.delay(initiator, opt.delay, setter);
},
getTransitions: function() {
return _.keys(this._transitionIds);
},
stopTransitions: function(path, delim) {
delim = delim || '/';
var pathArray = path && path.split(delim);
_(this._transitionIds).keys().filter(pathArray && function(key) {
return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length));
}).each(function(key) {
joint.util.cancelFrame(this._transitionIds[key]);
delete this._transitionIds[key];
this.trigger('transition:end', this, key);
}, this);
return this;
},
// A shorcut making it easy to create constructs like the following:
// `var el = (new joint.shapes.basic.Rect).addTo(graph)`.
addTo: function(graph, opt) {
graph.addCell(this, opt);
return this;
},
// A shortcut for an equivalent call: `paper.findViewByModel(cell)`
// making it easy to create constructs like the following:
// `cell.findView(paper).highlight()`
findView: function(paper) {
return paper.findViewByModel(this);
},
isLink: function() {
return false;
}
});
// joint.dia.CellView base view and controller.
// --------------------------------------------
// This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`.
joint.dia.CellView = Backbone.View.extend({
tagName: 'g',
attributes: function() {
return { 'model-id': this.model.id };
},
constructor: function(options) {
this._configure(options);
Backbone.View.apply(this, arguments);
},
_configure: function(options) {
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
this.options = options;
// Make sure a global unique id is assigned to this view. Store this id also to the properties object.
// The global unique id makes sure that the same view can be rendered on e.g. different machines and
// still be associated to the same object among all those clients. This is necessary for real-time
// collaboration mechanism.
this.options.id = this.options.id || joint.util.guid(this);
},
initialize: function() {
_.bindAll(this, 'remove', 'update');
// Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree.
this.$el.data('view', this);
this.listenTo(this.model, 'remove', this.remove);
this.listenTo(this.model, 'change:attrs', this.onChangeAttrs);
},
onChangeAttrs: function(cell, attrs, opt) {
if (opt.dirty) {
// dirty flag could be set when a model attribute was removed and it needs to be cleared
// also from the DOM element. See cell.removeAttr().
return this.render();
}
return this.update();
},
// Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps
// all the nodes of the Cell view.
_ensureElement: function() {
var el;
if (!this.el) {
var attrs = _.extend({ id: this.id }, _.result(this, 'attributes'));
if (this.className) attrs['class'] = _.result(this, 'className');
el = V(_.result(this, 'tagName'), attrs).node;
} else {
el = _.result(this, 'el');
}
this.setElement(el, false);
},
// Utilize an alternative DOM manipulation API by
// adding an element reference wrapped in Vectorizer.
_setElement: function(el) {
this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
this.el = this.$el[0];
this.vel = V(this.el);
},
findBySelector: function(selector) {
// These are either descendants of `this.$el` of `this.$el` itself.
// `.` is a special selector used to select the wrapping `<g>` element.
var $selected = selector === '.' ? this.$el : this.$el.find(selector);
return $selected;
},
notify: function(evt) {
if (this.paper) {
var args = Array.prototype.slice.call(arguments, 1);
// Trigger the event on both the element itself and also on the paper.
this.trigger.apply(this, [evt].concat(args));
// Paper event handlers receive the view object as the first argument.
this.paper.trigger.apply(this.paper, [evt, this].concat(args));
}
},
getStrokeBBox: function(el) {
// Return a bounding box rectangle that takes into account stroke.
// Note that this is a naive and ad-hoc implementation that does not
// works only in certain cases and should be replaced as soon as browsers will
// start supporting the getStrokeBBox() SVG method.
// @TODO any better solution is very welcome!
var isMagnet = !!el;
el = el || this.el;
var bbox = V(el).bbox(false, this.paper.viewport);
var strokeWidth;
if (isMagnet) {
strokeWidth = V(el).attr('stroke-width');
} else {
strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width');
}
strokeWidth = parseFloat(strokeWidth) || 0;
return g.rect(bbox).moveAndExpand({ x: -strokeWidth / 2, y: -strokeWidth / 2, width: strokeWidth, height: strokeWidth });
},
getBBox: function() {
return g.rect(this.vel.bbox());
},
highlight: function(el, opt) {
el = !el ? this.el : this.$(el)[0] || this.el;
// set partial flag if the highlighted element is not the entire view.
opt = opt || {};
opt.partial = el != this.el;
this.notify('cell:highlight', el, opt);
return this;
},
unhighlight: function(el, opt) {
el = !el ? this.el : this.$(el)[0] || this.el;
opt = opt || {};
opt.partial = el != this.el;
this.notify('cell:unhighlight', el, opt);
return this;
},
// Find the closest element that has the `magnet` attribute set to `true`. If there was not such
// an element found, return the root element of the cell view.
findMagnet: function(el) {
var $el = this.$(el);
if ($el.length === 0 || $el[0] === this.el) {
// If the overall cell has set `magnet === false`, then return `undefined` to
// announce there is no magnet found for this cell.
// This is especially useful to set on cells that have 'ports'. In this case,
// only the ports have set `magnet === true` and the overall element has `magnet === false`.
var attrs = this.model.get('attrs') || {};
if (attrs['.'] && attrs['.']['magnet'] === false) {
return undefined;
}
return this.el;
}
if ($el.attr('magnet')) {
return $el[0];
}
return this.findMagnet($el.parent());
},
// `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format:
// `{ name: <name of the filter>, args: { <arguments>, ... }`.
// An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`.
applyFilter: function(selector, filter) {
var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector);
// Generate a hash code from the stringified filter definition. This gives us
// a unique filter ID for different definitions.
var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter));
// If the filter already exists in the document,
// we're done and we can just use it (reference it using `url()`).
// If not, create one.
if (!this.paper.svg.getElementById(filterId)) {
var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {});
if (!filterSVGString) {
throw new Error('Non-existing filter ' + filter.name);
}
var filterElement = V(filterSVGString);
// Set the filter area to be 3x the bounding box of the cell
// and center the filter around the cell.
filterElement.attr({
filterUnits: 'objectBoundingBox',
x: -1, y: -1, width: 3, height: 3
});
if (filter.attrs) filterElement.attr(filter.attrs);
filterElement.node.id = filterId;
V(this.paper.svg).defs().append(filterElement);
}
$selected.each(function() {
V(this).attr('filter', 'url(#' + filterId + ')');
});
},
// `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`.
// `gradient` must be in the special JointJS gradient format:
// `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`.
// An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`.
applyGradient: function(selector, attr, gradient) {
var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector);
// Generate a hash code from the stringified filter definition. This gives us
// a unique filter ID for different definitions.
var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient));
// If the gradient already exists in the document,
// we're done and we can just use it (reference it using `url()`).
// If not, create one.
if (!this.paper.svg.getElementById(gradientId)) {
var gradientSVGString = [
'<' + gradient.type + '>',
_.map(gradient.stops, function(stop) {
return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />';
}).join(''),
'</' + gradient.type + '>'
].join('');
var gradientElement = V(gradientSVGString);
if (gradient.attrs) { gradientElement.attr(gradient.attrs); }
gradientElement.node.id = gradientId;
V(this.paper.svg).defs().append(gradientElement);
}
$selected.each(function() {
V(this).attr(attr, 'url(#' + gradientId + ')');
});
},
// Construct a unique selector for the `el` element within this view.
// `prevSelector` is being collected through the recursive call.
// No value for `prevSelector` is expected when using this method.
getSelector: function(el, prevSelector) {
if (el === this.el) {
return prevSelector;
}
var nthChild = V(el).index() + 1;
var selector = el.tagName + ':nth-child(' + nthChild + ')';
if (prevSelector) {
selector += ' > ' + prevSelector;
}
return this.getSelector(el.parentNode, selector);
},
// Interaction. The controller part.
// ---------------------------------
// Interaction is handled by the paper and delegated to the view in interest.
// `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid.
// If necessary, real coordinates can be obtained from the `evt` event object.
// These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`,
// i.e. `joint.dia.Element` and `joint.dia.Link`.
pointerdblclick: function(evt, x, y) {
this.notify('cell:pointerdblclick', evt, x, y);
},
pointerclick: function(evt, x, y) {
this.notify('cell:pointerclick', evt, x, y);
},
pointerdown: function(evt, x, y) {
if (this.model.collection) {
this.model.trigger('batch:start', { batchName: 'pointer' });
this._collection = this.model.collection;
}
this.notify('cell:pointerdown', evt, x, y);
},
pointermove: function(evt, x, y) {
this.notify('cell:pointermove', evt, x, y);
},
pointerup: function(evt, x, y) {
this.notify('cell:pointerup', evt, x, y);
if (this._collection) {
// we don't want to trigger event on model as model doesn't
// need to be member of collection anymore (remove)
this._collection.trigger('batch:stop', { batchName: 'pointer' });
delete this._collection;
}
},
mouseover: function(evt) {
this.notify('cell:mouseover', evt);
},
mouseout: function(evt) {
this.notify('cell:mouseout', evt);
},
contextmenu: function(evt, x, y) {
this.notify('cell:contextmenu', evt, x, y);
}
});
// JointJS library.
// (c) 2011-2013 client IO
// joint.dia.Element base model.
// -----------------------------
joint.dia.Element = joint.dia.Cell.extend({
defaults: {
position: { x: 0, y: 0 },
size: { width: 1, height: 1 },
angle: 0
},
position: function(x, y, opt) {
var isSetter = _.isNumber(y);
opt = (isSetter ? opt : x) || {};
// option `parentRelative` for setting the position relative to the element's parent.
if (opt.parentRelative) {
// Getting the parent's position requires the collection.
// Cell.get('parent') helds cell id only.
if (!this.collection) throw new Error('Element must be part of a collection.');
var parent = this.collection.get(this.get('parent'));
var parentPosition = parent && !parent.isLink()
? parent.get('position')
: { x: 0, y: 0 };
}
if (isSetter) {
if (opt.parentRelative) {
x += parentPosition.x;
y += parentPosition.y;
}
return this.set('position', { x: x, y: y }, opt);
} else { // Getter returns a geometry point.
var elementPosition = g.point(this.get('position'));
return opt.parentRelative
? elementPosition.difference(parentPosition)
: elementPosition;
}
},
translate: function(tx, ty, opt) {
ty = ty || 0;
if (tx === 0 && ty === 0) {
// Like nothing has happened.
return this;
}
opt = opt || {};
// Pass the initiator of the translation.
opt.translateBy = opt.translateBy || this.id;
// To find out by how much an element was translated in event 'change:position' handlers.
opt.tx = tx;
opt.ty = ty;
var position = this.get('position') || { x: 0, y: 0 };
var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 };
if (opt.transition) {
if (!_.isObject(opt.transition)) opt.transition = {};
this.transition('position', translatedPosition, _.extend({}, opt.transition, {
valueFunction: joint.util.interpolate.object
}));
} else {
this.set('position', translatedPosition, opt);
// Recursively call `translate()` on all the embeds cells.
_.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt);
}
return this;
},
resize: function(width, height, opt) {
this.trigger('batch:start', { batchName: 'resize' });
this.set('size', { width: width, height: height }, opt);
this.trigger('batch:stop', { batchName: 'resize' });
return this;
},
fitEmbeds: function(opt) {
opt = opt || 0;
var collection = this.collection;
// Getting the children's size and position requires the collection.
// Cell.get('embdes') helds an array of cell ids only.
if (!collection) throw new Error('Element must be part of a collection.');
var embeddedCells = this.getEmbeddedCells();
if (embeddedCells.length > 0) {
this.trigger('batch:start', { batchName: 'fit-embeds' });
if (opt.deep) {
// Recursively apply fitEmbeds on all embeds first.
_.invoke(embeddedCells, 'fitEmbeds', opt);
}
// Compute cell's size and position based on the children bbox
// and given padding.
var bbox = collection.getBBox(embeddedCells);
var padding = joint.util.normalizeSides(opt.padding);
// Apply padding computed above to the bbox.
bbox.moveAndExpand({
x: - padding.left,
y: - padding.top,
width: padding.right + padding.left,
height: padding.bottom + padding.top
});
// Set new element dimensions finally.
this.set({
position: { x: bbox.x, y: bbox.y },
size: { width: bbox.width, height: bbox.height }
}, opt);
this.trigger('batch:stop', { batchName: 'fit-embeds' });
}
return this;
},
// Rotate element by `angle` degrees, optionally around `origin` point.
// If `origin` is not provided, it is considered to be the center of the element.
// If `absolute` is `true`, the `angle` is considered is abslute, i.e. it is not
// the difference from the previous angle.
rotate: function(angle, absolute, origin) {
if (origin) {
var center = this.getBBox().center();
var size = this.get('size');
var position = this.get('position');
center.rotate(origin, this.get('angle') - angle);
var dx = center.x - size.width / 2 - position.x;
var dy = center.y - size.height / 2 - position.y;
this.trigger('batch:start', { batchName: 'rotate' });
this.translate(dx, dy);
this.rotate(angle, absolute);
this.trigger('batch:stop', { batchName: 'rotate' });
} else {
this.set('angle', absolute ? angle : (this.get('angle') + angle) % 360);
}
return this;
},
getBBox: function() {
var position = this.get('position');
var size = this.get('size');
return g.rect(position.x, position.y, size.width, size.height);
}
});
// joint.dia.Element base view and controller.
// -------------------------------------------
joint.dia.ElementView = joint.dia.CellView.extend({
SPECIAL_ATTRIBUTES: [
'style',
'text',
'html',
'ref-x',
'ref-y',
'ref-dx',
'ref-dy',
'ref-width',
'ref-height',
'ref',
'x-alignment',
'y-alignment',
'port'
],
className: function() {
return 'element ' + this.model.get('type').replace('.', ' ', 'g');
},
initialize: function() {
_.bindAll(this, 'translate', 'resize', 'rotate');
joint.dia.CellView.prototype.initialize.apply(this, arguments);
this.listenTo(this.model, 'change:position', this.translate);
this.listenTo(this.model, 'change:size', this.resize);
this.listenTo(this.model, 'change:angle', this.rotate);
},
// Default is to process the `attrs` object and set attributes on subelements based on the selectors.
update: function(cell, renderingOnlyAttrs) {
var allAttrs = this.model.get('attrs');
var rotatable = this.rotatableNode;
if (rotatable) {
var rotation = rotatable.attr('transform');
rotatable.attr('transform', '');
}
var relativelyPositioned = [];
var nodesBySelector = {};
_.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) {
// Elements that should be updated.
var $selected = this.findBySelector(selector);
// No element matched by the `selector` was found. We're done then.
if ($selected.length === 0) return;
nodesBySelector[selector] = $selected;
// Special attributes are treated by JointJS, not by SVG.
var specialAttributes = this.SPECIAL_ATTRIBUTES.slice();
// If the `filter` attribute is an object, it is in the special JointJS filter format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.filter)) {
specialAttributes.push('filter');
this.applyFilter($selected, attrs.filter);
}
// If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.fill)) {
specialAttributes.push('fill');
this.applyGradient($selected, 'fill', attrs.fill);
}
if (_.isObject(attrs.stroke)) {
specialAttributes.push('stroke');
this.applyGradient($selected, 'stroke', attrs.stroke);
}
// Make special case for `text` attribute. So that we can set text content of the `<text>` element
// via the `attrs` object as well.
// Note that it's important to set text before applying the rest of the final attributes.
// Vectorizer `text()` method sets on the element its own attributes and it has to be possible
// to rewrite them, if needed. (i.e display: 'none')
if (!_.isUndefined(attrs.text)) {
$selected.each(function() {
V(this).text(attrs.text + '', { lineHeight: attrs.lineHeight, textPath: attrs.textPath, annotations: attrs.annotations });
});
specialAttributes.push('lineHeight', 'textPath', 'annotations');
}
// Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr()
// method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr().
var finalAttributes = _.omit(attrs, specialAttributes);
$selected.each(function() {
V(this).attr(finalAttributes);
});
// `port` attribute contains the `id` of the port that the underlying magnet represents.
if (attrs.port) {
$selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id);
}
// `style` attribute is special in the sense that it sets the CSS style of the subelement.
if (attrs.style) {
$selected.css(attrs.style);
}
if (!_.isUndefined(attrs.html)) {
$selected.each(function() {
$(this).html(attrs.html + '');
});
}
// Special `ref-x` and `ref-y` attributes make it possible to set both absolute or
// relative positioning of subelements.
if (!_.isUndefined(attrs['ref-x']) ||
!_.isUndefined(attrs['ref-y']) ||
!_.isUndefined(attrs['ref-dx']) ||
!_.isUndefined(attrs['ref-dy']) ||
!_.isUndefined(attrs['x-alignment']) ||
!_.isUndefined(attrs['y-alignment']) ||
!_.isUndefined(attrs['ref-width']) ||
!_.isUndefined(attrs['ref-height'])
) {
_.each($selected, function(el, index, list) {
var $el = $(el);
// copy original list selector to the element
$el.selector = list.selector;
relativelyPositioned.push($el);
});
}
}, this);
// We don't want the sub elements to affect the bounding box of the root element when
// positioning the sub elements relatively to the bounding box.
//_.invoke(relativelyPositioned, 'hide');
//_.invoke(relativelyPositioned, 'show');
// Note that we're using the bounding box without transformation because we are already inside
// a transformed coordinate system.
var size = this.model.get('size');
var bbox = { x: 0, y: 0, width: size.width, height: size.height };
renderingOnlyAttrs = renderingOnlyAttrs || {};
_.each(relativelyPositioned, function($el) {
// if there was a special attribute affecting the position amongst renderingOnlyAttributes
// we have to merge it with rest of the element's attributes as they are necessary
// to update the position relatively (i.e `ref`)
var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector];
var elAttrs = renderingOnlyElAttrs
? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs)
: allAttrs[$el.selector];
this.positionRelative(V($el[0]), bbox, elAttrs, nodesBySelector);
}, this);
if (rotatable) {
rotatable.attr('transform', rotation || '');
}
},
positionRelative: function(vel, bbox, attributes, nodesBySelector) {
var ref = attributes['ref'];
var refDx = parseFloat(attributes['ref-dx']);
var refDy = parseFloat(attributes['ref-dy']);
var yAlignment = attributes['y-alignment'];
var xAlignment = attributes['x-alignment'];
// 'ref-y', 'ref-x', 'ref-width', 'ref-height' can be defined
// by value or by percentage e.g 4, 0.5, '200%'.
var refY = attributes['ref-y'];
var refYPercentage = _.isString(refY) && refY.slice(-1) === '%';
refY = parseFloat(refY);
if (refYPercentage) {
refY /= 100;
}
var refX = attributes['ref-x'];
var refXPercentage = _.isString(refX) && refX.slice(-1) === '%';
refX = parseFloat(refX);
if (refXPercentage) {
refX /= 100;
}
var refWidth = attributes['ref-width'];
var refWidthPercentage = _.isString(refWidth) && refWidth.slice(-1) === '%';
refWidth = parseFloat(refWidth);
if (refWidthPercentage) {
refWidth /= 100;
}
var refHeight = attributes['ref-height'];
var refHeightPercentage = _.isString(refHeight) && refHeight.slice(-1) === '%';
refHeight = parseFloat(refHeight);
if (refHeightPercentage) {
refHeight /= 100;
}
// Check if the node is a descendant of the scalable group.
var scalable = vel.findParentByClass('scalable', this.el);
// `ref` is the selector of the reference element. If no `ref` is passed, reference
// element is the root element.
if (ref) {
var vref;
if (nodesBySelector && nodesBySelector[ref]) {
// First we check if the same selector has been already used.
vref = V(nodesBySelector[ref][0]);
} else {
// Other wise we find the ref ourselves.
vref = ref === '.' ? this.vel : this.vel.findOne(ref);
}
if (!vref) {
throw new Error('dia.ElementView: reference does not exists.');
}
// Get the bounding box of the reference element relative to the root `<g>` element.
bbox = vref.bbox(false, this.el);
}
// Remove the previous translate() from the transform attribute and translate the element
// relative to the root bounding box following the `ref-x` and `ref-y` attributes.
if (vel.attr('transform')) {
vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '').trim() || '');
}
// 'ref-width'/'ref-height' defines the width/height of the subelement relatively to
// the reference element size
// val in 0..1 ref-width = 0.75 sets the width to 75% of the ref. el. width
// val < 0 || val > 1 ref-height = -20 sets the height to the the ref. el. height shorter by 20
if (isFinite(refWidth)) {
if (refWidthPercentage || refWidth >= 0 && refWidth <= 1) {
vel.attr('width', refWidth * bbox.width);
} else {
vel.attr('width', Math.max(refWidth + bbox.width, 0));
}
}
if (isFinite(refHeight)) {
if (refHeightPercentage || refHeight >= 0 && refHeight <= 1) {
vel.attr('height', refHeight * bbox.height);
} else {
vel.attr('height', Math.max(refHeight + bbox.height, 0));
}
}
// The final translation of the subelement.
var tx = 0;
var ty = 0;
var scale;
// `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom
// coordinate of the reference element.
if (isFinite(refDx)) {
if (scalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
scale = scale || scalable.scale();
tx = bbox.x + bbox.width + refDx / scale.sx;
} else {
tx = bbox.x + bbox.width + refDx;
}
}
if (isFinite(refDy)) {
if (scalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
scale = scale || scalable.scale();
ty = bbox.y + bbox.height + refDy / scale.sy;
} else {
ty = bbox.y + bbox.height + refDy;
}
}
// if `refX` is in [0, 1] then `refX` is a fraction of bounding box width
// if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box
// otherwise, `refX` is the left coordinate of the bounding box
// Analogical rules apply for `refY`.
if (isFinite(refX)) {
if (refXPercentage || refX > 0 && refX < 1) {
tx = bbox.x + bbox.width * refX;
} else if (scalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
scale = scale || scalable.scale();
tx = bbox.x + refX / scale.sx;
} else {
tx = bbox.x + refX;
}
}
if (isFinite(refY)) {
if (refXPercentage || refY > 0 && refY < 1) {
ty = bbox.y + bbox.height * refY;
} else if (scalable) {
// Compensate for the scale grid in case the elemnt is in the scalable group.
scale = scale || scalable.scale();
ty = bbox.y + refY / scale.sy;
} else {
ty = bbox.y + refY;
}
}
if (!_.isUndefined(yAlignment) || !_.isUndefined(xAlignment)) {
var velBBox = vel.bbox(false, this.paper.viewport);
// `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate.
if (yAlignment === 'middle') {
ty -= velBBox.height / 2;
} else if (isFinite(yAlignment)) {
ty += (yAlignment > -1 && yAlignment < 1) ? velBBox.height * yAlignment : yAlignment;
}
// `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate.
if (xAlignment === 'middle') {
tx -= velBBox.width / 2;
} else if (isFinite(xAlignment)) {
tx += (xAlignment > -1 && xAlignment < 1) ? velBBox.width * xAlignment : xAlignment;
}
}
vel.translate(tx, ty);
},
// `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the
// default markup is not desirable.
renderMarkup: function() {
var markup = this.model.markup || this.model.get('markup');
if (markup) {
var nodes = V(markup);
this.vel.append(nodes);
} else {
throw new Error('properties.markup is missing while the default render() implementation is used.');
}
},
render: function() {
this.$el.empty();
this.renderMarkup();
this.rotatableNode = this.vel.findOne('.rotatable');
this.scalableNode = this.vel.findOne('.scalable');
this.update();
this.resize();
this.rotate();
this.translate();
return this;
},
// Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here.
// `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only.
// `update()` is then responsible for scaling only those elements that have the `follow-scale`
// attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement
// that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed
// be be scaled.
scale: function(sx, sy) {
// TODO: take into account the origin coordinates `ox` and `oy`.
this.vel.scale(sx, sy);
},
resize: function() {
var size = this.model.get('size') || { width: 1, height: 1 };
var angle = this.model.get('angle') || 0;
var scalable = this.scalableNode;
if (!scalable) {
// If there is no scalable elements, than there is nothing to resize.
return;
}
var scalableBbox = scalable.bbox(true);
// Make sure `scalableBbox.width` and `scalableBbox.height` are not zero which can happen if the element does not have any content. By making
// the width/height 1, we prevent HTML errors of the type `scale(Infinity, Infinity)`.
scalable.attr('transform', 'scale(' + (size.width / (scalableBbox.width || 1)) + ',' + (size.height / (scalableBbox.height || 1)) + ')');
// Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height`
// Order of transformations is significant but we want to reconstruct the object always in the order:
// resize(), rotate(), translate() no matter of how the object was transformed. For that to work,
// we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the
// rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation
// around the center of the resized object (which is a different origin then the origin of the previous rotation)
// and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was.
// Cancel the rotation but now around a different origin, which is the center of the scaled object.
var rotatable = this.rotatableNode;
var rotation = rotatable && rotatable.attr('transform');
if (rotation && rotation !== 'null') {
rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width / 2) + ',' + (size.height / 2) + ')');
var rotatableBbox = scalable.bbox(false, this.paper.viewport);
// Store new x, y and perform rotate() again against the new rotation origin.
this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y });
this.rotate();
}
// Update must always be called on non-rotated element. Otherwise, relative positioning
// would work with wrong (rotated) bounding boxes.
this.update();
},
translate: function(model, changes, opt) {
var position = this.model.get('position') || { x: 0, y: 0 };
this.vel.attr('transform', 'translate(' + position.x + ',' + position.y + ')');
},
rotate: function() {
var rotatable = this.rotatableNode;
if (!rotatable) {
// If there is no rotatable elements, then there is nothing to rotate.
return;
}
var angle = this.model.get('angle') || 0;
var size = this.model.get('size') || { width: 1, height: 1 };
var ox = size.width / 2;
var oy = size.height / 2;
rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')');
},
getBBox: function(opt) {
if (opt && opt.useModelGeometry) {
var noTransformationBBox = this.model.getBBox().bbox(this.model.get('angle'));
var transformationMatrix = this.paper.viewport.getCTM();
return g.rect(V.transformRect(noTransformationBBox, transformationMatrix));
}
return joint.dia.CellView.prototype.getBBox.apply(this, arguments);
},
// Embedding mode methods
// ----------------------
findParentsByKey: function(key) {
var bbox = this.model.getBBox();
return key == 'bbox'
? this.paper.model.findModelsInArea(bbox)
: this.paper.model.findModelsFromPoint(bbox[key]());
},
prepareEmbedding: function() {
// Bring the model to the front with all his embeds.
this.model.toFront({ deep: true, ui: true });
// Move to front also all the inbound and outbound links that are connected
// to any of the element descendant. If we bring to front only embedded elements,
// links connected to them would stay in the background.
_.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'toFront', { ui: true });
// Before we start looking for suitable parent we remove the current one.
var parentId = this.model.get('parent');
parentId && this.paper.model.getCell(parentId).unembed(this.model, { ui: true });
},
processEmbedding: function(opt) {
opt = opt || this.paper.options;
var candidates = this.findParentsByKey(opt.findParentBy);
// don't account element itself or any of its descendents
candidates = _.reject(candidates, function(el) {
return this.model.id == el.id || el.isEmbeddedIn(this.model);
}, this);
if (opt.frontParentOnly) {
// pick the element with the highest `z` index
candidates = candidates.slice(-1);
}
var newCandidateView = null;
var prevCandidateView = this._candidateEmbedView;
// iterate over all candidates starting from the last one (has the highest z-index).
for (var i = candidates.length - 1; i >= 0; i--) {
var candidate = candidates[i];
if (prevCandidateView && prevCandidateView.model.id == candidate.id) {
// candidate remains the same
newCandidateView = prevCandidateView;
break;
} else {
var view = candidate.findView(this.paper);
if (opt.validateEmbedding.call(this.paper, this, view)) {
// flip to the new candidate
newCandidateView = view;
break;
}
}
}
if (newCandidateView && newCandidateView != prevCandidateView) {
// A new candidate view found. Highlight the new one.
prevCandidateView && prevCandidateView.unhighlight(null, { embedding: true });
this._candidateEmbedView = newCandidateView.highlight(null, { embedding: true });
}
if (!newCandidateView && prevCandidateView) {
// No candidate view found. Unhighlight the previous candidate.
prevCandidateView.unhighlight(null, { embedding: true });
delete this._candidateEmbedView;
}
},
finalizeEmbedding: function() {
var candidateView = this._candidateEmbedView;
if (candidateView) {
// We finished embedding. Candidate view is chosen to become the parent of the model.
candidateView.model.embed(this.model, { ui: true });
candidateView.unhighlight(null, { embedding: true });
delete this._candidateEmbedView;
}
_.invoke(this.paper.model.getConnectedLinks(this.model, { deep: true }), 'reparent', { ui: true });
},
// Interaction. The controller part.
// ---------------------------------
pointerdown: function(evt, x, y) {
// target is a valid magnet start linking
if (evt.target.getAttribute('magnet') && this.paper.options.validateMagnet.call(this.paper, this, evt.target)) {
this.model.trigger('batch:start', { batchName: 'add-link' });
var link = this.paper.getDefaultLink(this, evt.target);
link.set({
source: {
id: this.model.id,
selector: this.getSelector(evt.target),
port: $(evt.target).attr('port')
},
target: { x: x, y: y }
});
this.paper.model.addCell(link);
this._linkView = this.paper.findViewByModel(link);
this._linkView.pointerdown(evt, x, y);
this._linkView.startArrowheadMove('target');
} else {
this._dx = x;
this._dy = y;
joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
this.notify('element:pointerdown', evt, x, y);
}
},
pointermove: function(evt, x, y) {
if (this._linkView) {
// let the linkview deal with this event
this._linkView.pointermove(evt, x, y);
} else {
var grid = this.paper.options.gridSize;
var interactive = _.isFunction(this.options.interactive)
? this.options.interactive(this, 'pointermove')
: this.options.interactive;
if (interactive !== false) {
var position = this.model.get('position');
// Make sure the new element's position always snaps to the current grid after
// translate as the previous one could be calculated with a different grid size.
this.model.translate(
g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid),
g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid)
);
if (this.paper.options.embeddingMode) {
if (!this._inProcessOfEmbedding) {
// Prepare the element for embedding only if the pointer moves.
// We don't want to do unnecessary action with the element
// if an user only clicks/dblclicks on it.
this.prepareEmbedding();
this._inProcessOfEmbedding = true;
}
this.processEmbedding();
}
}
this._dx = g.snapToGrid(x, grid);
this._dy = g.snapToGrid(y, grid);
joint.dia.CellView.prototype.pointermove.apply(this, arguments);
this.notify('element:pointermove', evt, x, y);
}
},
pointerup: function(evt, x, y) {
if (this._linkView) {
// let the linkview deal with this event
this._linkView.pointerup(evt, x, y);
delete this._linkView;
this.model.trigger('batch:stop', { batchName: 'add-link' });
} else {
if (this._inProcessOfEmbedding) {
this.finalizeEmbedding();
this._inProcessOfEmbedding = false;
}
this.notify('element:pointerup', evt, x, y);
joint.dia.CellView.prototype.pointerup.apply(this, arguments);
}
}
});
// JointJS diagramming library.
// (c) 2011-2013 client IO
// joint.dia.Link base model.
// --------------------------
joint.dia.Link = joint.dia.Cell.extend({
// The default markup for links.
markup: [
'<path class="connection" stroke="black"/>',
'<path class="marker-source" fill="black" stroke="black" />',
'<path class="marker-target" fill="black" stroke="black" />',
'<path class="connection-wrap"/>',
'<g class="labels"/>',
'<g class="marker-vertices"/>',
'<g class="marker-arrowheads"/>',
'<g class="link-tools"/>'
].join(''),
labelMarkup: [
'<g class="label">',
'<rect />',
'<text />',
'</g>'
].join(''),
toolMarkup: [
'<g class="link-tool">',
'<g class="tool-remove" event="remove">',
'<circle r="11" />',
'<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>',
'<title>Remove link.</title>',
'</g>',
'<g class="tool-options" event="link:options">',
'<circle r="11" transform="translate(25)"/>',
'<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>',
'<title>Link options.</title>',
'</g>',
'</g>'
].join(''),
// The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`).
// Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for
// dragging vertices (changin their position). The latter is used for removing vertices.
vertexMarkup: [
'<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">',
'<circle class="marker-vertex" idx="<%= idx %>" r="10" />',
'<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>',
'<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">',
'<title>Remove vertex.</title>',
'</path>',
'</g>'
].join(''),
arrowheadMarkup: [
'<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">',
'<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />',
'</g>'
].join(''),
defaults: {
type: 'link',
source: {},
target: {}
},
disconnect: function() {
return this.set({ source: g.point(0, 0), target: g.point(0, 0) });
},
// A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter.
label: function(idx, value) {
idx = idx || 0;
var labels = this.get('labels') || [];
// Is it a getter?
if (arguments.length === 0 || arguments.length === 1) {
return labels[idx];
}
var newValue = _.merge({}, labels[idx], value);
var newLabels = labels.slice();
newLabels[idx] = newValue;
return this.set({ labels: newLabels });
},
translate: function(tx, ty, opt) {
var attrs = {};
var source = this.get('source');
var target = this.get('target');
var vertices = this.get('vertices');
if (!source.id) {
attrs.source = { x: source.x + tx, y: source.y + ty };
}
if (!target.id) {
attrs.target = { x: target.x + tx, y: target.y + ty };
}
if (vertices && vertices.length) {
attrs.vertices = _.map(vertices, function(vertex) {
return { x: vertex.x + tx, y: vertex.y + ty };
});
}
return this.set(attrs, opt);
},
reparent: function(opt) {
var newParent;
if (this.collection) {
var source = this.collection.get(this.get('source').id);
var target = this.collection.get(this.get('target').id);
var prevParent = this.collection.get(this.get('parent'));
if (source && target) {
newParent = this.collection.getCommonAncestor(source, target);
}
if (prevParent && (!newParent || newParent.id != prevParent.id)) {
// Unembed the link if source and target has no common ancestor
// or common ancestor changed
prevParent.unembed(this, opt);
}
if (newParent) {
newParent.embed(this, opt);
}
}
return newParent;
},
isLink: function() {
return true;
},
hasLoop: function() {
var sourceId = this.get('source').id;
var targetId = this.get('target').id;
return sourceId && targetId && sourceId == targetId;
}
});
// joint.dia.Link base view and controller.
// ----------------------------------------
joint.dia.LinkView = joint.dia.CellView.extend({
className: function() {
return _.unique(this.model.get('type').split('.').concat('link')).join(' ');
},
options: {
shortLinkLength: 100,
doubleLinkTools: false,
longLinkLength: 160,
linkToolsOffset: 40,
doubleLinkToolsOffset: 60,
sampleInterval: 50
},
initialize: function(options) {
joint.dia.CellView.prototype.initialize.apply(this, arguments);
// create methods in prototype, so they can be accessed from any instance and
// don't need to be create over and over
if (typeof this.constructor.prototype.watchSource !== 'function') {
this.constructor.prototype.watchSource = this.createWatcher('source');
this.constructor.prototype.watchTarget = this.createWatcher('target');
}
// `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to
// `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the
// nodes in `updateLabelPosition()` in order to update the label positions.
this._labelCache = {};
// keeps markers bboxes and positions again for quicker access
this._markerCache = {};
// bind events
this.startListening();
},
startListening: function() {
var model = this.model;
this.listenTo(model, 'change:markup', this.render);
this.listenTo(model, 'change:smooth change:manhattan change:router change:connector', this.update);
this.listenTo(model, 'change:toolMarkup', this.onToolsChange);
this.listenTo(model, 'change:labels change:labelMarkup', this.onLabelsChange);
this.listenTo(model, 'change:vertices change:vertexMarkup', this.onVerticesChange);
this.listenTo(model, 'change:source', this.onSourceChange);
this.listenTo(model, 'change:target', this.onTargetChange);
},
onSourceChange: function(cell, source) {
this.watchSource(cell, source).update();
},
onTargetChange: function(cell, target) {
this.watchTarget(cell, target).update();
},
onVerticesChange: function(cell, changed, opt) {
this.renderVertexMarkers();
// If the vertices have been changed by a translation we do update only if the link was
// the only link that was translated. If the link was translated via another element which the link
// is embedded in, this element will be translated as well and that triggers an update.
// Note that all embeds in a model are sorted - first comes links, then elements.
if (!opt.translateBy || opt.translateBy === this.model.id || this.model.hasLoop()) {
// Vertices were changed (not as a reaction on translate) or link.translate() was called or
// we're dealing with a loop link that is embedded.
this.update();
}
},
onToolsChange: function() {
this.renderTools().updateToolsPosition();
},
onLabelsChange: function() {
this.renderLabels().updateLabelPositions();
},
// Rendering
//----------
render: function() {
this.$el.empty();
// A special markup can be given in the `properties.markup` property. This might be handy
// if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s.
// `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors
// of elements with special meaning though. Therefore, those classes should be preserved in any
// special markup passed in `properties.markup`.
var children = V(this.model.get('markup') || this.model.markup);
// custom markup may contain only one children
if (!_.isArray(children)) children = [children];
// Cache all children elements for quicker access.
this._V = {}; // vectorized markup;
_.each(children, function(child) {
var c = child.attr('class');
c && (this._V[$.camelCase(c)] = child);
}, this);
// Only the connection path is mandatory
if (!this._V.connection) throw new Error('link: no connection path in the markup');
// partial rendering
this.renderTools();
this.renderVertexMarkers();
this.renderArrowheadMarkers();
this.vel.append(children);
// rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox
// returns zero values)
this.renderLabels();
// start watching the ends of the link for changes
this.watchSource(this.model, this.model.get('source'))
.watchTarget(this.model, this.model.get('target'))
.update();
return this;
},
renderLabels: function() {
if (!this._V.labels) return this;
this._labelCache = {};
var $labels = $(this._V.labels.node).empty();
var labels = this.model.get('labels') || [];
if (!labels.length) return this;
var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup);
// This is a prepared instance of a vectorized SVGDOM node for the label element resulting from
// compilation of the labelTemplate. The purpose is that all labels will just `clone()` this
// node to create a duplicate.
var labelNodeInstance = V(labelTemplate());
var canLabelMove = this.can('labelMove');
_.each(labels, function(label, idx) {
var labelNode = labelNodeInstance.clone().node;
V(labelNode).attr('label-idx', idx);
if (canLabelMove) {
V(labelNode).attr('cursor', 'move');
}
// Cache label nodes so that the `updateLabels()` can just update the label node positions.
this._labelCache[idx] = V(labelNode);
var $text = $(labelNode).find('text');
var $rect = $(labelNode).find('rect');
// Text attributes with the default `text-anchor` and font-size set.
var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/'));
$text.attr(_.omit(textAttributes, 'text'));
if (!_.isUndefined(textAttributes.text)) {
V($text[0]).text(textAttributes.text + '');
}
// Note that we first need to append the `<text>` element to the DOM in order to
// get its bounding box.
$labels.append(labelNode);
// `y-alignment` - center the text element around its y coordinate.
var textBbox = V($text[0]).bbox(true, $labels[0]);
V($text[0]).translate(0, -textBbox.height / 2);
// Add default values.
var rectAttributes = _.extend({
fill: 'white',
rx: 3,
ry: 3
}, joint.util.getByPath(label, 'attrs/rect', '/'));
$rect.attr(_.extend(rectAttributes, {
x: textBbox.x,
y: textBbox.y - textBbox.height / 2, // Take into account the y-alignment translation.
width: textBbox.width,
height: textBbox.height
}));
}, this);
return this;
},
renderTools: function() {
if (!this._V.linkTools) return this;
// Tools are a group of clickable elements that manipulate the whole link.
// A good example of this is the remove tool that removes the whole link.
// Tools appear after hovering the link close to the `source` element/point of the link
// but are offset a bit so that they don't cover the `marker-arrowhead`.
var $tools = $(this._V.linkTools.node).empty();
var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup);
var tool = V(toolTemplate());
$tools.append(tool.node);
// Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly.
this._toolCache = tool;
// If `doubleLinkTools` is enabled, we render copy of the tools on the other side of the
// link as well but only if the link is longer than `longLinkLength`.
if (this.options.doubleLinkTools) {
var tool2 = tool.clone();
$tools.append(tool2.node);
this._tool2Cache = tool2;
}
return this;
},
renderVertexMarkers: function() {
if (!this._V.markerVertices) return this;
var $markerVertices = $(this._V.markerVertices.node).empty();
// A special markup can be given in the `properties.vertexMarkup` property. This might be handy
// if default styling (elements) are not desired. This makes it possible to use any
// SVG elements for .marker-vertex and .marker-vertex-remove tools.
var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup);
_.each(this.model.get('vertices'), function(vertex, idx) {
$markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node);
});
return this;
},
renderArrowheadMarkers: function() {
// Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case.
if (!this._V.markerArrowheads) return this;
var $markerArrowheads = $(this._V.markerArrowheads.node);
$markerArrowheads.empty();
// A special markup can be given in the `properties.vertexMarkup` property. This might be handy
// if default styling (elements) are not desired. This makes it possible to use any
// SVG elements for .marker-vertex and .marker-vertex-remove tools.
var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup);
this._V.sourceArrowhead = V(markupTemplate({ end: 'source' }));
this._V.targetArrowhead = V(markupTemplate({ end: 'target' }));
$markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node);
return this;
},
// Updating
//---------
// Default is to process the `attrs` object and set attributes on subelements based on the selectors.
update: function() {
// Update attributes.
_.each(this.model.get('attrs'), function(attrs, selector) {
var processedAttributes = [];
// If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.fill)) {
this.applyGradient(selector, 'fill', attrs.fill);
processedAttributes.push('fill');
}
if (_.isObject(attrs.stroke)) {
this.applyGradient(selector, 'stroke', attrs.stroke);
processedAttributes.push('stroke');
}
// If the `filter` attribute is an object, it is in the special JointJS filter format and so
// it becomes a special attribute and is treated separately.
if (_.isObject(attrs.filter)) {
this.applyFilter(selector, attrs.filter);
processedAttributes.push('filter');
}
// remove processed special attributes from attrs
if (processedAttributes.length > 0) {
processedAttributes.unshift(attrs);
attrs = _.omit.apply(_, processedAttributes);
}
this.findBySelector(selector).attr(attrs);
}, this);
// Path finding
var vertices = this.route = this.findRoute(this.model.get('vertices') || []);
// finds all the connection points taking new vertices into account
this._findConnectionPoints(vertices);
var pathData = this.getPathData(vertices);
// The markup needs to contain a `.connection`
this._V.connection.attr('d', pathData);
this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData);
this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget);
//partials updates
this.updateLabelPositions();
this.updateToolsPosition();
this.updateArrowheadMarkers();
delete this.options.perpendicular;
// Mark that postponed update has been already executed.
this.updatePostponed = false;
return this;
},
_findConnectionPoints: function(vertices) {
// cache source and target points
var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint;
var firstVertex = _.first(vertices);
sourcePoint = this.getConnectionPoint(
'source', this.model.get('source'), firstVertex || this.model.get('target')
).round();
var lastVertex = _.last(vertices);
targetPoint = this.getConnectionPoint(
'target', this.model.get('target'), lastVertex || sourcePoint
).round();
// Move the source point by the width of the marker taking into account
// its scale around x-axis. Note that scale is the only transform that
// makes sense to be set in `.marker-source` attributes object
// as all other transforms (translate/rotate) will be replaced
// by the `translateAndAutoOrient()` function.
var cache = this._markerCache;
if (this._V.markerSource) {
cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true);
sourceMarkerPoint = g.point(sourcePoint).move(
firstVertex || targetPoint,
cache.sourceBBox.width * this._V.markerSource.scale().sx * -1
).round();
}
if (this._V.markerTarget) {
cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true);
targetMarkerPoint = g.point(targetPoint).move(
lastVertex || sourcePoint,
cache.targetBBox.width * this._V.markerTarget.scale().sx * -1
).round();
}
// if there was no markup for the marker, use the connection point.
cache.sourcePoint = sourceMarkerPoint || sourcePoint;
cache.targetPoint = targetMarkerPoint || targetPoint;
// make connection points public
this.sourcePoint = sourcePoint;
this.targetPoint = targetPoint;
},
updateLabelPositions: function() {
if (!this._V.labels) return this;
// This method assumes all the label nodes are stored in the `this._labelCache` hash table
// by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method.
var labels = this.model.get('labels') || [];
if (!labels.length) return this;
var connectionElement = this._V.connection.node;
var connectionLength = connectionElement.getTotalLength();
// Firefox returns connectionLength=NaN in odd cases (for bezier curves).
// In that case we won't update labels at all.
if (!_.isNaN(connectionLength)) {
var samples;
_.each(labels, function(label, idx) {
var position = label.position;
var distance = _.isObject(position) ? position.distance : position;
var offset = _.isObject(position) ? position.offset : { x: 0, y: 0 };
distance = (distance > connectionLength) ? connectionLength : distance; // sanity check
distance = (distance < 0) ? connectionLength + distance : distance;
distance = (distance > 1) ? distance : connectionLength * distance;
var labelCoordinates = connectionElement.getPointAtLength(distance);
if (_.isObject(offset)) {
// Just offset the label by the x,y provided in the offset object.
labelCoordinates = g.point(labelCoordinates).offset(offset.x, offset.y);
} else if (_.isNumber(offset)) {
if (!samples) {
samples = this._samples || this._V.connection.sample(this.options.sampleInterval);
}
// Offset the label by the amount provided in `offset` to an either
// side of the link.
// 1. Find the closest sample & its left and right neighbours.
var minSqDistance = Infinity;
var closestSample;
var closestSampleIndex;
var p;
var sqDistance;
for (var i = 0, len = samples.length; i < len; i++) {
p = samples[i];
sqDistance = g.line(p, labelCoordinates).squaredLength();
if (sqDistance < minSqDistance) {
minSqDistance = sqDistance;
closestSample = p;
closestSampleIndex = i;
}
}
var prevSample = samples[closestSampleIndex - 1];
var nextSample = samples[closestSampleIndex + 1];
// 2. Offset the label on the perpendicular line between
// the current label coordinate ("at `distance`") and
// the next sample.
var angle = 0;
if (nextSample) {
angle = g.point(labelCoordinates).theta(nextSample);
} else if (prevSample) {
angle = g.point(prevSample).theta(labelCoordinates);
}
labelCoordinates = g.point(labelCoordinates).offset(offset).rotate(labelCoordinates, angle - 90);
}
this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')');
}, this);
}
return this;
},
updateToolsPosition: function() {
if (!this._V.linkTools) return this;
// Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker.
// Note that the offset is hardcoded here. The offset should be always
// more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking
// this up all the time would be slow.
var scale = '';
var offset = this.options.linkToolsOffset;
var connectionLength = this.getConnectionLength();
// Firefox returns connectionLength=NaN in odd cases (for bezier curves).
// In that case we won't update tools position at all.
if (!_.isNaN(connectionLength)) {
// If the link is too short, make the tools half the size and the offset twice as low.
if (connectionLength < this.options.shortLinkLength) {
scale = 'scale(.5)';
offset /= 2;
}
var toolPosition = this.getPointAtLength(offset);
this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
if (this.options.doubleLinkTools && connectionLength >= this.options.longLinkLength) {
var doubleLinkToolsOffset = this.options.doubleLinkToolsOffset || offset;
toolPosition = this.getPointAtLength(connectionLength - doubleLinkToolsOffset);
this._tool2Cache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale);
this._tool2Cache.attr('visibility', 'visible');
} else if (this.options.doubleLinkTools) {
this._tool2Cache.attr('visibility', 'hidden');
}
}
return this;
},
updateArrowheadMarkers: function() {
if (!this._V.markerArrowheads) return this;
// getting bbox of an element with `display="none"` in IE9 ends up with access violation
if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this;
var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1;
this._V.sourceArrowhead.scale(sx);
this._V.targetArrowhead.scale(sx);
this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead);
return this;
},
// Returns a function observing changes on an end of the link. If a change happens and new end is a new model,
// it stops listening on the previous one and starts listening to the new one.
createWatcher: function(endType) {
// create handler for specific end type (source|target).
var onModelChange = _.partial(this.onEndModelChange, endType);
function watchEndModel(link, end) {
end = end || {};
var endModel = null;
var previousEnd = link.previous(endType) || {};
if (previousEnd.id) {
this.stopListening(this.paper.getModelById(previousEnd.id), 'change', onModelChange);
}
if (end.id) {
// If the observed model changes, it caches a new bbox and do the link update.
endModel = this.paper.getModelById(end.id);
this.listenTo(endModel, 'change', onModelChange);
}
onModelChange.call(this, endModel, { cacheOnly: true });
return this;
}
return watchEndModel;
},
onEndModelChange: function(endType, endModel, opt) {
var doUpdate = !opt.cacheOnly;
var end = this.model.get(endType) || {};
if (endModel) {
var selector = this.constructor.makeSelector(end);
var oppositeEndType = endType == 'source' ? 'target' : 'source';
var oppositeEnd = this.model.get(oppositeEndType) || {};
var oppositeSelector = oppositeEnd.id && this.constructor.makeSelector(oppositeEnd);
// Caching end models bounding boxes.
// If `opt.handleBy` equals the client-side ID of this link view and it is a loop link, then we already cached
// the bounding boxes in the previous turn (e.g. for loop link, the change:source event is followed
// by change:target and so on change:source, we already chached the bounding boxes of - the same - element).
if (opt.handleBy === this.cid && selector == oppositeSelector) {
// Source and target elements are identical. We're dealing with a loop link. We are handling `change` event for the
// second time now. There is no need to calculate bbox and find magnet element again.
// It was calculated already for opposite link end.
this[endType + 'BBox'] = this[oppositeEndType + 'BBox'];
this[endType + 'View'] = this[oppositeEndType + 'View'];
this[endType + 'Magnet'] = this[oppositeEndType + 'Magnet'];
} else if (opt.translateBy) {
// `opt.translateBy` optimizes the way we calculate bounding box of the source/target element.
// If `opt.translateBy` is an ID of the element that was originally translated. This allows us
// to just offset the cached bounding box by the translation instead of calculating the bounding
// box from scratch on every translate.
var bbox = this[endType + 'BBox'];
bbox.x += opt.tx;
bbox.y += opt.ty;
} else {
// The slowest path, source/target could have been rotated or resized or any attribute
// that affects the bounding box of the view might have been changed.
var view = this.paper.findViewByModel(end.id);
var magnetElement = view.el.querySelector(selector);
this[endType + 'BBox'] = view.getStrokeBBox(magnetElement);
this[endType + 'View'] = view;
this[endType + 'Magnet'] = magnetElement;
}
if (opt.handleBy === this.cid && opt.translateBy &&
this.model.isEmbeddedIn(endModel) &&
!_.isEmpty(this.model.get('vertices'))) {
// Loop link whose element was translated and that has vertices (that need to be translated with
// the parent in which my element is embedded).
// If the link is embedded, has a loop and vertices and the end model
// has been translated, do not update yet. There are vertices still to be updated (change:vertices
// event will come in the next turn).
doUpdate = false;
}
if (!this.updatePostponed && oppositeEnd.id) {
// The update was not postponed (that can happen e.g. on the first change event) and the opposite
// end is a model (opposite end is the opposite end of the link we're just updating, e.g. if
// we're reacting on change:source event, the oppositeEnd is the target model).
var oppositeEndModel = this.paper.getModelById(oppositeEnd.id);
// Passing `handleBy` flag via event option.
// Note that if we are listening to the same model for event 'change' twice.
// The same event will be handled by this method also twice.
if (end.id === oppositeEnd.id) {
// We're dealing with a loop link. Tell the handlers in the next turn that they should update
// the link instead of me. (We know for sure there will be a next turn because
// loop links react on at least two events: change on the source model followed by a change on
// the target model).
opt.handleBy = this.cid;
}
if (opt.handleBy === this.cid || (opt.translateBy && oppositeEndModel.isEmbeddedIn(opt.translateBy))) {
// Here are two options:
// - Source and target are connected to the same model (not necessarily the same port).
// - Both end models are translated by the same ancestor. We know that opposite end
// model will be translated in the next turn as well.
// In both situations there will be more changes on the model that trigger an
// update. So there is no need to update the linkView yet.
this.updatePostponed = true;
doUpdate = false;
}
}
} else {
// the link end is a point ~ rect 1x1
this[endType + 'BBox'] = g.rect(end.x || 0, end.y || 0, 1, 1);
this[endType + 'View'] = this[endType + 'Magnet'] = null;
}
// keep track which end had been changed very last
this.lastEndChange = endType;
doUpdate && this.update();
},
_translateAndAutoOrientArrows: function(sourceArrow, targetArrow) {
// Make the markers "point" to their sticky points being auto-oriented towards
// `targetPosition`/`sourcePosition`. And do so only if there is a markup for them.
if (sourceArrow) {
sourceArrow.translateAndAutoOrient(
this.sourcePoint,
_.first(this.route) || this.targetPoint,
this.paper.viewport
);
}
if (targetArrow) {
targetArrow.translateAndAutoOrient(
this.targetPoint,
_.last(this.route) || this.sourcePoint,
this.paper.viewport
);
}
},
removeVertex: function(idx) {
var vertices = _.clone(this.model.get('vertices'));
if (vertices && vertices.length) {
vertices.splice(idx, 1);
this.model.set('vertices', vertices, { ui: true });
}
return this;
},
// This method ads a new vertex to the `vertices` array of `.connection`. This method
// uses a heuristic to find the index at which the new `vertex` should be placed at assuming
// the new vertex is somewhere on the path.
addVertex: function(vertex) {
// As it is very hard to find a correct index of the newly created vertex,
// a little heuristics is taking place here.
// The heuristics checks if length of the newly created
// path is lot more than length of the old path. If this is the case,
// new vertex was probably put into a wrong index.
// Try to put it into another index and repeat the heuristics again.
var vertices = (this.model.get('vertices') || []).slice();
// Store the original vertices for a later revert if needed.
var originalVertices = vertices.slice();
// A `<path>` element used to compute the length of the path during heuristics.
var path = this._V.connection.node.cloneNode(false);
// Length of the original path.
var originalPathLength = path.getTotalLength();
// Current path length.
var pathLength;
// Tolerance determines the highest possible difference between the length
// of the old and new path. The number has been chosen heuristically.
var pathLengthTolerance = 20;
// Total number of vertices including source and target points.
var idx = vertices.length + 1;
// Loop through all possible indexes and check if the difference between
// path lengths changes significantly. If not, the found index is
// most probably the right one.
while (idx--) {
vertices.splice(idx, 0, vertex);
V(path).attr('d', this.getPathData(this.findRoute(vertices)));
pathLength = path.getTotalLength();
// Check if the path lengths changed significantly.
if (pathLength - originalPathLength > pathLengthTolerance) {
// Revert vertices to the original array. The path length has changed too much
// so that the index was not found yet.
vertices = originalVertices.slice();
} else {
break;
}
}
if (idx === -1) {
// If no suitable index was found for such a vertex, make the vertex the first one.
idx = 0;
vertices.splice(idx, 0, vertex);
}
this.model.set('vertices', vertices, { ui: true });
return idx;
},
// Send a token (an SVG element, usually a circle) along the connection path.
// Example: `paper.findViewByModel(link).sendToken(V('circle', { r: 7, fill: 'green' }).node)`
// `duration` is optional and is a time in milliseconds that the token travels from the source to the target of the link. Default is `1000`.
// `callback` is optional and is a function to be called once the token reaches the target.
sendToken: function(token, duration, callback) {
duration = duration || 1000;
V(this.paper.viewport).append(token);
V(token).animateAlongPath({ dur: duration + 'ms', repeatCount: 1 }, this._V.connection.node);
_.delay(function() { V(token).remove(); callback && callback(); }, duration);
},
findRoute: function(oldVertices) {
var router = this.model.get('router');
if (!router) {
if (this.model.get('manhattan')) {
// backwards compability
router = { name: 'orthogonal' };
} else {
return oldVertices;
}
}
var fn = joint.routers[router.name];
if (!_.isFunction(fn)) {
throw 'unknown router: ' + router.name;
}
var newVertices = fn.call(this, oldVertices || [], router.args || {}, this);
return newVertices;
},
// Return the `d` attribute value of the `<path>` element representing the link
// between `source` and `target`.
getPathData: function(vertices) {
var connector = this.model.get('connector');
if (!connector) {
// backwards compability
connector = this.model.get('smooth') ? { name: 'smooth' } : { name: 'normal' };
}
if (!_.isFunction(joint.connectors[connector.name])) {
throw 'unknown connector: ' + connector.name;
}
var pathData = joint.connectors[connector.name].call(
this,
this._markerCache.sourcePoint, // Note that the value is translated by the size
this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint)
vertices || (this.model.get('vertices') || {}),
connector.args || {}, // options
this
);
return pathData;
},
// Find a point that is the start of the connection.
// If `selectorOrPoint` is a point, then we're done and that point is the start of the connection.
// If the `selectorOrPoint` is an element however, we need to know a reference point (or element)
// that the link leads to in order to determine the start of the connection on the original element.
getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) {
var spot;
// If the `selectorOrPoint` (or `referenceSelectorOrPoint`) is `undefined`, the `source`/`target` of the link model is `undefined`.
// We want to allow this however so that one can create links such as `var link = new joint.dia.Link` and
// set the `source`/`target` later.
_.isEmpty(selectorOrPoint) && (selectorOrPoint = { x: 0, y: 0 });
_.isEmpty(referenceSelectorOrPoint) && (referenceSelectorOrPoint = { x: 0, y: 0 });
if (!selectorOrPoint.id) {
// If the source is a point, we don't need a reference point to find the sticky point of connection.
spot = g.point(selectorOrPoint);
} else {
// If the source is an element, we need to find a point on the element boundary that is closest
// to the reference point (or reference element).
// Get the bounding box of the spot relative to the paper viewport. This is necessary
// in order to follow paper viewport transformations (scale/rotate).
// `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`)
// method, it exists since first render and are automatically updated
var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox;
var reference;
if (!referenceSelectorOrPoint.id) {
// Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element.
reference = g.point(referenceSelectorOrPoint);
} else {
// Reference was passed as an element, therefore we need to find a point on the reference
// element boundary closest to the source element.
// Get the bounding box of the spot relative to the paper viewport. This is necessary
// in order to follow paper viewport transformations (scale/rotate).
var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox;
reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center());
reference = reference || g.rect(referenceBbox).center();
}
// If `perpendicularLinks` flag is set on the paper and there are vertices
// on the link, then try to find a connection point that makes the link perpendicular
// even though the link won't point to the center of the targeted object.
if (this.paper.options.perpendicularLinks || this.options.perpendicular) {
var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1);
var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height);
var nearestSide;
if (horizontalLineRect.intersect(g.rect(spotBbox))) {
nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
switch (nearestSide) {
case 'left':
spot = g.point(spotBbox.x, reference.y);
break;
case 'right':
spot = g.point(spotBbox.x + spotBbox.width, reference.y);
break;
default:
spot = g.rect(spotBbox).center();
break;
}
} else if (verticalLineRect.intersect(g.rect(spotBbox))) {
nearestSide = g.rect(spotBbox).sideNearestToPoint(reference);
switch (nearestSide) {
case 'top':
spot = g.point(reference.x, spotBbox.y);
break;
case 'bottom':
spot = g.point(reference.x, spotBbox.y + spotBbox.height);
break;
default:
spot = g.rect(spotBbox).center();
break;
}
} else {
// If there is no intersection horizontally or vertically with the object bounding box,
// then we fall back to the regular situation finding straight line (not perpendicular)
// between the object and the reference point.
spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
spot = spot || g.rect(spotBbox).center();
}
} else if (this.paper.options.linkConnectionPoint) {
var view = end === 'target' ? this.targetView : this.sourceView;
var magnet = end === 'target' ? this.targetMagnet : this.sourceMagnet;
spot = this.paper.options.linkConnectionPoint(this, view, magnet, reference);
} else {
spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference);
spot = spot || g.rect(spotBbox).center();
}
}
return spot;
},
// Public API
// ----------
getConnectionLength: function() {
return this._V.connection.node.getTotalLength();
},
getPointAtLength: function(length) {
return this._V.connection.node.getPointAtLength(length);
},
// Interaction. The controller part.
// ---------------------------------
_beforeArrowheadMove: function() {
this._z = this.model.get('z');
this.model.toFront();
// Let the pointer propagate throught the link view elements so that
// the `evt.target` is another element under the pointer, not the link itself.
this.el.style.pointerEvents = 'none';
if (this.paper.options.markAvailable) {
this._markAvailableMagnets();
}
},
_afterArrowheadMove: function() {
if (this._z) {
this.model.set('z', this._z, { ui: true });
delete this._z;
}
// Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation.
// Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead.
// See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`.
this.el.style.pointerEvents = 'visiblePainted';
if (this.paper.options.markAvailable) {
this._unmarkAvailableMagnets();
}
},
_createValidateConnectionArgs: function(arrowhead) {
// It makes sure the arguments for validateConnection have the following form:
// (source view, source magnet, target view, target magnet and link view)
var args = [];
args[4] = arrowhead;
args[5] = this;
var oppositeArrowhead;
var i = 0;
var j = 0;
if (arrowhead === 'source') {
i = 2;
oppositeArrowhead = 'target';
} else {
j = 2;
oppositeArrowhead = 'source';
}
var end = this.model.get(oppositeArrowhead);
if (end.id) {
args[i] = this.paper.findViewByModel(end.id);
args[i + 1] = end.selector && args[i].el.querySelector(end.selector);
}
function validateConnectionArgs(cellView, magnet) {
args[j] = cellView;
args[j + 1] = cellView.el === magnet ? undefined : magnet;
return args;
}
return validateConnectionArgs;
},
_markAvailableMagnets: function() {
var elements = this.paper.model.getElements();
var validate = this.paper.options.validateConnection;
_.chain(elements).map(this.paper.findViewByModel, this.paper).each(function(view) {
var isElementAvailable = view.el.getAttribute('magnet') !== 'false' &&
validate.apply(this.paper, this._validateConnectionArgs(view, null));
var availableMagnets = _.filter(view.el.querySelectorAll('[magnet]'), function(magnet) {
return validate.apply(this.paper, this._validateConnectionArgs(view, magnet));
}, this);
if (isElementAvailable) {
V(view.el).addClass('available-magnet');
}
_.each(availableMagnets, function(magnet) {
V(magnet).addClass('available-magnet');
});
if (isElementAvailable || availableMagnets.length) {
V(view.el).addClass('available-cell');
}
}, this);
},
_unmarkAvailableMagnets: function() {
_.each(this.paper.el.querySelectorAll('.available-cell, .available-magnet'), function(magnet) {
V(magnet).removeClass('available-magnet').removeClass('available-cell');
});
},
startArrowheadMove: function(end) {
// Allow to delegate events from an another view to this linkView in order to trigger arrowhead
// move without need to click on the actual arrowhead dom element.
this._action = 'arrowhead-move';
this._arrowhead = end;
this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead);
this._beforeArrowheadMove();
},
// Return `true` if the link is allowed to perform a certain UI `feature`.
// Example: `can('vertexMove')`, `can('labelMove')`.
can: function(feature) {
var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointerdown') : this.options.interactive;
if (!_.isObject(interactive) || interactive[feature] !== false) return true;
return false;
},
pointerdown: function(evt, x, y) {
joint.dia.CellView.prototype.pointerdown.apply(this, arguments);
this.notify('link:pointerdown', evt, x, y);
this._dx = x;
this._dy = y;
// if are simulating pointerdown on a link during a magnet click, skip link interactions
if (evt.target.getAttribute('magnet') != null) return;
var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointerdown') : this.options.interactive;
if (interactive === false) return;
var className = evt.target.getAttribute('class');
var parentClassName = evt.target.parentNode.getAttribute('class');
var labelNode;
if (parentClassName === 'label') {
className = parentClassName;
labelNode = evt.target.parentNode;
} else {
labelNode = evt.target;
}
switch (className) {
case 'marker-vertex':
if (this.can('vertexMove')) {
this._action = 'vertex-move';
this._vertexIdx = evt.target.getAttribute('idx');
}
break;
case 'marker-vertex-remove':
case 'marker-vertex-remove-area':
if (this.can('vertexRemove')) {
this.removeVertex(evt.target.getAttribute('idx'));
}
break;
case 'marker-arrowhead':
if (this.can('arrowheadMove')) {
this.startArrowheadMove(evt.target.getAttribute('end'));
}
break;
case 'label':
if (this.can('labelMove')) {
this._action = 'label-move';
this._labelIdx = parseInt(V(labelNode).attr('label-idx'), 10);
// Precalculate samples so that we don't have to do that
// over and over again while dragging the label.
this._samples = this._V.connection.sample(1);
this._linkLength = this._V.connection.node.getTotalLength();
}
break;
default:
var targetParentEvent = evt.target.parentNode.getAttribute('event');
if (targetParentEvent) {
// `remove` event is built-in. Other custom events are triggered on the paper.
if (targetParentEvent === 'remove') {
this.model.remove();
} else {
this.paper.trigger(targetParentEvent, evt, this, x, y);
}
} else {
if (this.can('vertexAdd')) {
// Store the index at which the new vertex has just been placed.
// We'll be update the very same vertex position in `pointermove()`.
this._vertexIdx = this.addVertex({ x: x, y: y });
this._action = 'vertex-move';
}
}
}
},
pointermove: function(evt, x, y) {
switch (this._action) {
case 'vertex-move':
var vertices = _.clone(this.model.get('vertices'));
vertices[this._vertexIdx] = { x: x, y: y };
this.model.set('vertices', vertices, { ui: true });
break;
case 'label-move':
var dragPoint = { x: x, y: y };
var label = this.model.get('labels')[this._labelIdx];
var samples = this._samples;
var minSqDistance = Infinity;
var closestSample;
var closestSampleIndex;
var p;
var sqDistance;
for (var i = 0, len = samples.length; i < len; i++) {
p = samples[i];
sqDistance = g.line(p, dragPoint).squaredLength();
if (sqDistance < minSqDistance) {
minSqDistance = sqDistance;
closestSample = p;
closestSampleIndex = i;
}
}
var prevSample = samples[closestSampleIndex - 1];
var nextSample = samples[closestSampleIndex + 1];
var closestSampleDistance = g.point(closestSample).distance(dragPoint);
var offset = 0;
if (prevSample && nextSample) {
offset = g.line(prevSample, nextSample).pointOffset(dragPoint);
} else if (prevSample) {
offset = g.line(prevSample, closestSample).pointOffset(dragPoint);
} else if (nextSample) {
offset = g.line(closestSample, nextSample).pointOffset(dragPoint);
}
this.model.label(this._labelIdx, {
position: {
distance: closestSample.distance / this._linkLength,
offset: offset
}
});
break;
case 'arrowhead-move':
if (this.paper.options.snapLinks) {
// checking view in close area of the pointer
var r = this.paper.options.snapLinks.radius || 50;
var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r });
this._closestView && this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true });
this._closestView = this._closestEnd = null;
var distance;
var minDistance = Number.MAX_VALUE;
var pointer = g.point(x, y);
_.each(viewsInArea, function(view) {
// skip connecting to the element in case '.': { magnet: false } attribute present
if (view.el.getAttribute('magnet') !== 'false') {
// find distance from the center of the model to pointer coordinates
distance = view.model.getBBox().center().distance(pointer);
// the connection is looked up in a circle area by `distance < r`
if (distance < r && distance < minDistance) {
if (this.paper.options.validateConnection.apply(
this.paper, this._validateConnectionArgs(view, null)
)) {
minDistance = distance;
this._closestView = view;
this._closestEnd = { id: view.model.id };
}
}
}
view.$('[magnet]').each(_.bind(function(index, magnet) {
var bbox = V(magnet).bbox(false, this.paper.viewport);
distance = pointer.distance({
x: bbox.x + bbox.width / 2,
y: bbox.y + bbox.height / 2
});
if (distance < r && distance < minDistance) {
if (this.paper.options.validateConnection.apply(
this.paper, this._validateConnectionArgs(view, magnet)
)) {
minDistance = distance;
this._closestView = view;
this._closestEnd = {
id: view.model.id,
selector: view.getSelector(magnet),
port: magnet.getAttribute('port')
};
}
}
}, this));
}, this);
this._closestView && this._closestView.highlight(this._closestEnd.selector, { connecting: true, snapping: true });
this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y }, { ui: true });
} else {
// checking views right under the pointer
// Touchmove event's target is not reflecting the element under the coordinates as mousemove does.
// It holds the element when a touchstart triggered.
var target = (evt.type === 'mousemove')
? evt.target
: document.elementFromPoint(evt.clientX, evt.clientY);
if (this._targetEvent !== target) {
// Unhighlight the previous view under pointer if there was one.
this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true });
this._viewUnderPointer = this.paper.findView(target);
if (this._viewUnderPointer) {
// If we found a view that is under the pointer, we need to find the closest
// magnet based on the real target element of the event.
this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target);
if (this._magnetUnderPointer && this.paper.options.validateConnection.apply(
this.paper,
this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer)
)) {
// If there was no magnet found, do not highlight anything and assume there
// is no view under pointer we're interested in reconnecting to.
// This can only happen if the overall element has the attribute `'.': { magnet: false }`.
this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer, { connecting: true });
} else {
// This type of connection is not valid. Disregard this magnet.
this._magnetUnderPointer = null;
}
} else {
// Make sure we'll delete previous magnet
this._magnetUnderPointer = null;
}
}
this._targetEvent = target;
this.model.set(this._arrowhead, { x: x, y: y }, { ui: true });
}
break;
}
this._dx = x;
this._dy = y;
joint.dia.CellView.prototype.pointermove.apply(this, arguments);
this.notify('link:pointermove', evt, x, y);
},
pointerup: function(evt, x, y) {
if (this._action === 'label-move') {
this._samples = null;
} else if (this._action === 'arrowhead-move') {
if (this.paper.options.snapLinks) {
this._closestView && this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true });
this._closestView = this._closestEnd = null;
} else {
if (this._magnetUnderPointer) {
this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true });
// Find a unique `selector` of the element under pointer that is a magnet. If the
// `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself,
// the returned `selector` will be `undefined`. That means we can directly pass it to the
// `source`/`target` attribute of the link model below.
this.model.set(this._arrowhead, {
id: this._viewUnderPointer.model.id,
selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer),
port: $(this._magnetUnderPointer).attr('port')
}, { ui: true });
}
delete this._viewUnderPointer;
delete this._magnetUnderPointer;
}
// Reparent the link if embedding is enabled
if (this.paper.options.embeddingMode && this.model.reparent()) {
// Make sure we don't reverse to the original 'z' index (see afterArrowheadMove()).
delete this._z;
}
this._afterArrowheadMove();
}
delete this._action;
this.notify('link:pointerup', evt, x, y);
joint.dia.CellView.prototype.pointerup.apply(this, arguments);
}
}, {
makeSelector: function(end) {
var selector = '[model-id="' + end.id + '"]';
// `port` has a higher precendence over `selector`. This is because the selector to the magnet
// might change while the name of the port can stay the same.
if (end.port) {
selector += ' [port="' + end.port + '"]';
} else if (end.selector) {
selector += ' ' + end.selector;
}
return selector;
}
});
// JointJS library.
// (c) 2011-2013 client IO
joint.dia.Paper = Backbone.View.extend({
className: 'paper',
options: {
width: 800,
height: 600,
origin: { x: 0, y: 0 }, // x,y coordinates in top-left corner
gridSize: 50,
perpendicularLinks: false,
elementView: joint.dia.ElementView,
linkView: joint.dia.LinkView,
snapLinks: false, // false, true, { radius: value }
// Marks all available magnets with 'available-magnet' class name and all available cells with
// 'available-cell' class name. Marks them when dragging a link is started and unmark
// when the dragging is stopped.
markAvailable: false,
// Defines what link model is added to the graph after an user clicks on an active magnet.
// Value could be the Backbone.model or a function returning the Backbone.model
// defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() }
defaultLink: new joint.dia.Link,
/* CONNECTING */
// Check whether to add a new link to the graph when user clicks on an a magnet.
validateMagnet: function(cellView, magnet) {
return magnet.getAttribute('magnet') !== 'passive';
},
// Check whether to allow or disallow the link connection while an arrowhead end (source/target)
// being changed.
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView;
},
/* EMBEDDING */
// Enables embedding. Reparents the dragged element with elements under it and makes sure that
// all links and elements are visible taken the level of embedding into account.
embeddingMode: false,
// Check whether to allow or disallow the element embedding while an element being translated.
validateEmbedding: function(childView, parentView) {
// by default all elements can be in relation child-parent
return true;
},
// Determines the way how a cell finds a suitable parent when it's dragged over the paper.
// The cell with the highest z-index (visually on the top) will be choosen.
findParentBy: 'bbox', // 'bbox'|'center'|'origin'|'corner'|'topRight'|'bottomLeft'
// If enabled only the element on the very front is taken into account for the embedding.
// If disabled the elements under the dragged view are tested one by one
// (from front to back) until a valid parent found.
frontParentOnly: true,
// Interactive flags. See online docs for the complete list of interactive flags.
interactive: {
labelMove: false
}
},
events: {
'mousedown': 'pointerdown',
'dblclick': 'mousedblclick',
'click': 'mouseclick',
'touchstart': 'pointerdown',
'mousemove': 'pointermove',
'touchmove': 'pointermove',
'mouseover .element': 'cellMouseover',
'mouseover .link': 'cellMouseover',
'mouseout .element': 'cellMouseout',
'mouseout .link': 'cellMouseout',
'contextmenu': 'contextmenu'
},
constructor: function(options) {
this._configure(options);
Backbone.View.apply(this, arguments);
},
_configure: function(options) {
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
this.options = options;
},
initialize: function() {
_.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup', 'asyncRenderCells');
this.svg = V('svg').node;
this.viewport = V('g').addClass('viewport').node;
this.defs = V('defs').node;
// Append `<defs>` element to the SVG document. This is useful for filters and gradients.
V(this.svg).append([this.viewport, this.defs]);
this.$el.append(this.svg);
this.setOrigin();
this.setDimensions();
this.listenTo(this.model, 'add', this.onAddCell);
this.listenTo(this.model, 'reset', this.resetCells);
this.listenTo(this.model, 'sort', this.sortCells);
$(document).on('mouseup touchend', this.pointerup);
// Hold the value when mouse has been moved: when mouse moved, no click event will be triggered.
this._mousemoved = false;
// default cell highlighting
this.on({ 'cell:highlight': this.onCellHighlight, 'cell:unhighlight': this.onCellUnhighlight });
},
remove: function() {
//clean up all DOM elements/views to prevent memory leaks
this.removeCells();
$(document).off('mouseup touchend', this.pointerup);
Backbone.View.prototype.remove.call(this);
},
setDimensions: function(width, height) {
width = this.options.width = width || this.options.width;
height = this.options.height = height || this.options.height;
V(this.svg).attr({ width: width, height: height });
this.trigger('resize', width, height);
},
setOrigin: function(ox, oy) {
this.options.origin.x = ox || 0;
this.options.origin.y = oy || 0;
V(this.viewport).translate(ox, oy, { absolute: true });
this.trigger('translate', ox, oy);
},
// Expand/shrink the paper to fit the content. Snap the width/height to the grid
// defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper.
// When options { fitNegative: true } it also translates the viewport in order to make all
// the content visible.
fitToContent: function(gridWidth, gridHeight, padding, opt) { // alternatively function(opt)
if (_.isObject(gridWidth)) {
// first parameter is an option object
opt = gridWidth;
gridWidth = opt.gridWidth || 1;
gridHeight = opt.gridHeight || 1;
padding = opt.padding || 0;
} else {
opt = opt || {};
gridWidth = gridWidth || 1;
gridHeight = gridHeight || 1;
padding = padding || 0;
}
padding = joint.util.normalizeSides(padding);
// Calculate the paper size to accomodate all the graph's elements.
var bbox = V(this.viewport).bbox(true, this.svg);
var currentScale = V(this.viewport).scale();
bbox.x *= currentScale.sx;
bbox.y *= currentScale.sy;
bbox.width *= currentScale.sx;
bbox.height *= currentScale.sy;
var calcWidth = Math.max(Math.ceil((bbox.width + bbox.x) / gridWidth), 1) * gridWidth;
var calcHeight = Math.max(Math.ceil((bbox.height + bbox.y) / gridHeight), 1) * gridHeight;
var tx = 0;
var ty = 0;
if ((opt.allowNewOrigin == 'negative' && bbox.x < 0) || (opt.allowNewOrigin == 'positive' && bbox.x >= 0) || opt.allowNewOrigin == 'any') {
tx = Math.ceil(-bbox.x / gridWidth) * gridWidth;
tx += padding.left;
calcWidth += tx;
}
if ((opt.allowNewOrigin == 'negative' && bbox.y < 0) || (opt.allowNewOrigin == 'positive' && bbox.y >= 0) || opt.allowNewOrigin == 'any') {
ty = Math.ceil(-bbox.y / gridHeight) * gridHeight;
ty += padding.top;
calcHeight += ty;
}
calcWidth += padding.right;
calcHeight += padding.bottom;
// Make sure the resulting width and height are greater than minimum.
calcWidth = Math.max(calcWidth, opt.minWidth || 0);
calcHeight = Math.max(calcHeight, opt.minHeight || 0);
// Make sure the resulting width and height are lesser than maximum.
calcWidth = Math.min(calcWidth, opt.maxWidth || Number.MAX_VALUE);
calcHeight = Math.min(calcHeight, opt.maxHeight || Number.MAX_VALUE);
var dimensionChange = calcWidth != this.options.width || calcHeight != this.options.height;
var originChange = tx != this.options.origin.x || ty != this.options.origin.y;
// Change the dimensions only if there is a size discrepency or an origin change
if (originChange) {
this.setOrigin(tx, ty);
}
if (dimensionChange) {
this.setDimensions(calcWidth, calcHeight);
}
},
scaleContentToFit: function(opt) {
var contentBBox = this.getContentBBox();
if (!contentBBox.width || !contentBBox.height) return;
opt = opt || {};
_.defaults(opt, {
padding: 0,
preserveAspectRatio: true,
scaleGrid: null,
minScale: 0,
maxScale: Number.MAX_VALUE
//minScaleX
//minScaleY
//maxScaleX
//maxScaleY
//fittingBBox
});
var padding = opt.padding;
var minScaleX = opt.minScaleX || opt.minScale;
var maxScaleX = opt.maxScaleX || opt.maxScale;
var minScaleY = opt.minScaleY || opt.minScale;
var maxScaleY = opt.maxScaleY || opt.maxScale;
var fittingBBox = opt.fittingBBox || ({
x: this.options.origin.x,
y: this.options.origin.y,
width: this.options.width,
height: this.options.height
});
fittingBBox = g.rect(fittingBBox).moveAndExpand({
x: padding,
y: padding,
width: -2 * padding,
height: -2 * padding
});
var currentScale = V(this.viewport).scale();
var newSx = fittingBBox.width / contentBBox.width * currentScale.sx;
var newSy = fittingBBox.height / contentBBox.height * currentScale.sy;
if (opt.preserveAspectRatio) {
newSx = newSy = Math.min(newSx, newSy);
}
// snap scale to a grid
if (opt.scaleGrid) {
var gridSize = opt.scaleGrid;
newSx = gridSize * Math.floor(newSx / gridSize);
newSy = gridSize * Math.floor(newSy / gridSize);
}
// scale min/max boundaries
newSx = Math.min(maxScaleX, Math.max(minScaleX, newSx));
newSy = Math.min(maxScaleY, Math.max(minScaleY, newSy));
this.scale(newSx, newSy);
var contentTranslation = this.getContentBBox();
var newOx = fittingBBox.x - contentTranslation.x;
var newOy = fittingBBox.y - contentTranslation.y;
this.setOrigin(newOx, newOy);
},
getContentBBox: function() {
var crect = this.viewport.getBoundingClientRect();
// Using Screen CTM was the only way to get the real viewport bounding box working in both
// Google Chrome and Firefox.
var screenCTM = this.viewport.getScreenCTM();
// for non-default origin we need to take the viewport translation into account
var viewportCTM = this.viewport.getCTM();
var bbox = g.rect({
x: crect.left - screenCTM.e + viewportCTM.e,
y: crect.top - screenCTM.f + viewportCTM.f,
width: crect.width,
height: crect.height
});
return bbox;
},
createViewForModel: function(cell) {
var view;
var type = cell.get('type');
var module = type.split('.')[0];
var entity = type.split('.')[1];
// If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`.
if (joint.shapes[module] && joint.shapes[module][entity + 'View']) {
view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive });
} else if (cell instanceof joint.dia.Element) {
view = new this.options.elementView({ model: cell, interactive: this.options.interactive });
} else {
view = new this.options.linkView({ model: cell, interactive: this.options.interactive });
}
return view;
},
onAddCell: function(cell, graph, options) {
if (this.options.async && options.async !== false && _.isNumber(options.position)) {
this._asyncCells = this._asyncCells || [];
this._asyncCells.push(cell);
if (options.position == 0) {
if (this._frameId) throw 'another asynchronous rendering in progress';
this.asyncRenderCells(this._asyncCells);
delete this._asyncCells;
}
} else {
this.addCell(cell);
}
},
addCell: function(cell) {
var view = this.createViewForModel(cell);
V(this.viewport).append(view.el);
view.paper = this;
view.render();
// This is the only way to prevent image dragging in Firefox that works.
// Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help.
$(view.el).find('image').on('dragstart', function() { return false; });
},
beforeRenderCells: function(cells) {
// Make sure links are always added AFTER elements.
// They wouldn't find their sources/targets in the DOM otherwise.
cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; });
return cells;
},
afterRenderCells: function() {
this.sortCells();
},
resetCells: function(cellsCollection, opt) {
$(this.viewport).empty();
var cells = cellsCollection.models.slice();
cells = this.beforeRenderCells(cells, opt);
if (this._frameId) {
joint.util.cancelFrame(this._frameId);
delete this._frameId;
}
if (this.options.async) {
this.asyncRenderCells(cells, opt);
// Sort the cells once all elements rendered (see asyncRenderCells()).
} else {
_.each(cells, this.addCell, this);
// Sort the cells in the DOM manually as we might have changed the order they
// were added to the DOM (see above).
this.sortCells();
}
},
removeCells: function() {
this.model.get('cells').each(function(cell) {
var view = this.findViewByModel(cell);
view && view.remove();
}, this);
},
asyncBatchAdded: _.identity,
asyncRenderCells: function(cells, opt) {
var done = false;
if (this._frameId) {
_.each(_.range(this.options.async && this.options.async.batchSize || 50), function() {
var cell = cells.shift();
done = !cell;
if (!done) this.addCell(cell);
}, this);
this.asyncBatchAdded();
}
if (done) {
delete this._frameId;
this.afterRenderCells(opt);
this.trigger('render:done', opt);
} else {
this._frameId = joint.util.nextFrame(_.bind(function() {
this.asyncRenderCells(cells, opt);
}, this));
}
},
sortCells: function() {
// Run insertion sort algorithm in order to efficiently sort DOM elements according to their
// associated model `z` attribute.
var $cells = $(this.viewport).children('[model-id]');
var cells = this.model.get('cells');
joint.util.sortElements($cells, function(a, b) {
var cellA = cells.get($(a).attr('model-id'));
var cellB = cells.get($(b).attr('model-id'));
return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1;
});
},
scale: function(sx, sy, ox, oy) {
sy = sy || sx;
if (_.isUndefined(ox)) {
ox = 0;
oy = 0;
}
// Remove previous transform so that the new scale is not affected by previous scales, especially
// the old translate() does not affect the new translate if an origin is specified.
V(this.viewport).attr('transform', '');
var oldTx = this.options.origin.x;
var oldTy = this.options.origin.y;
// TODO: V.scale() doesn't support setting scale origin. #Fix
if (ox || oy || oldTx || oldTy) {
var newTx = oldTx - ox * (sx - 1);
var newTy = oldTy - oy * (sy - 1);
this.setOrigin(newTx, newTy);
}
V(this.viewport).scale(sx, sy);
this.trigger('scale', sx, sy, ox, oy);
return this;
},
rotate: function(deg, ox, oy) {
// If the origin is not set explicitely, rotate around the center. Note that
// we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us
// the real bounding box (`bbox()`) including transformations).
if (_.isUndefined(ox)) {
var bbox = this.viewport.getBBox();
ox = bbox.width / 2;
oy = bbox.height / 2;
}
V(this.viewport).rotate(deg, ox, oy);
},
// Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also
// be a selector or a jQuery object.
findView: function(el) {
var $el = this.$(el);
if ($el.length === 0 || $el[0] === this.el) {
return undefined;
}
return $el.data('view') || this.findView($el.parent());
},
// Find a view for a model `cell`. `cell` can also be a string representing a model `id`.
findViewByModel: function(cell) {
var id = _.isString(cell) ? cell : cell.id;
var $view = this.$('[model-id="' + id + '"]');
return $view.length ? $view.data('view') : undefined;
},
// Find all views at given point
findViewsFromPoint: function(p) {
p = g.point(p);
var views = _.map(this.model.getElements(), this.findViewByModel);
return _.filter(views, function(view) {
return view && g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p);
}, this);
},
// Find all views in given area
findViewsInArea: function(r) {
r = g.rect(r);
var views = _.map(this.model.getElements(), this.findViewByModel);
return _.filter(views, function(view) {
return view && r.intersect(g.rect(V(view.el).bbox(false, this.viewport)));
}, this);
},
getModelById: function(id) {
return this.model.getCell(id);
},
snapToGrid: function(p) {
// Convert global coordinates to the local ones of the `viewport`. Otherwise,
// improper transformation would be applied when the viewport gets transformed (scaled/rotated).
var localPoint = V(this.viewport).toLocalPoint(p.x, p.y);
return {
x: g.snapToGrid(localPoint.x, this.options.gridSize),
y: g.snapToGrid(localPoint.y, this.options.gridSize)
};
},
// Transform client coordinates to the paper local coordinates.
// Useful when you have a mouse event object and you'd like to get coordinates
// inside the paper that correspond to `evt.clientX` and `evt.clientY` point.
// Exmaple: var paperPoint = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY });
clientToLocalPoint: function(p) {
var svgPoint = this.svg.createSVGPoint();
svgPoint.x = p.x;
svgPoint.y = p.y;
// This is a hack for Firefox! If there wasn't a fake (non-visible) rectangle covering the
// whole SVG area, `$(paper.svg).offset()` used below won't work.
var fakeRect = V('rect', { width: this.options.width, height: this.options.height, x: 0, y: 0, opacity: 0 });
V(this.svg).prepend(fakeRect);
var paperOffset = $(this.svg).offset();
// Clean up the fake rectangle once we have the offset of the SVG document.
fakeRect.remove();
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
svgPoint.x += scrollLeft - paperOffset.left;
svgPoint.y += scrollTop - paperOffset.top;
// Transform point into the viewport coordinate system.
var pointTransformed = svgPoint.matrixTransform(this.viewport.getCTM().inverse());
return pointTransformed;
},
getDefaultLink: function(cellView, magnet) {
return _.isFunction(this.options.defaultLink)
// default link is a function producing link model
? this.options.defaultLink.call(this, cellView, magnet)
// default link is the Backbone model
: this.options.defaultLink.clone();
},
// Cell highlighting
// -----------------
onCellHighlight: function(cellView, el) {
V(el).addClass('highlighted');
},
onCellUnhighlight: function(cellView, el) {
V(el).removeClass('highlighted');
},
// Interaction.
// ------------
mousedblclick: function(evt) {
evt.preventDefault();
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (this.guard(evt, view)) return;
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
view.pointerdblclick(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y);
}
},
mouseclick: function(evt) {
// Trigger event when mouse not moved.
if (!this._mousemoved) {
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (this.guard(evt, view)) return;
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
view.pointerclick(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y);
}
}
this._mousemoved = false;
},
// Guard guards the event received. If the event is not interesting, guard returns `true`.
// Otherwise, it return `false`.
guard: function(evt, view) {
if (view && view.model && (view.model instanceof joint.dia.Cell)) {
return false;
} else if (this.svg === evt.target || this.el === evt.target || $.contains(this.svg, evt.target)) {
return false;
}
return true; // Event guarded. Paper should not react on it in any way.
},
contextmenu: function(evt) {
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (this.guard(evt, view)) return;
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
view.contextmenu(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:contextmenu', evt, localPoint.x, localPoint.y);
}
},
pointerdown: function(evt) {
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (this.guard(evt, view)) return;
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (view) {
this.sourceView = view;
view.pointerdown(evt, localPoint.x, localPoint.y);
} else {
this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y);
}
},
pointermove: function(evt) {
evt.preventDefault();
evt = joint.util.normalizeEvent(evt);
if (this.sourceView) {
// Mouse moved.
this._mousemoved = true;
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
this.sourceView.pointermove(evt, localPoint.x, localPoint.y);
}
},
pointerup: function(evt) {
evt = joint.util.normalizeEvent(evt);
var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY });
if (this.sourceView) {
this.sourceView.pointerup(evt, localPoint.x, localPoint.y);
//"delete sourceView" occasionally throws an error in chrome (illegal access exception)
this.sourceView = null;
} else {
this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y);
}
},
cellMouseover: function(evt) {
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (view) {
if (this.guard(evt, view)) return;
view.mouseover(evt);
}
},
cellMouseout: function(evt) {
evt = joint.util.normalizeEvent(evt);
var view = this.findView(evt.target);
if (view) {
if (this.guard(evt, view)) return;
view.mouseout(evt);
}
}
});
// JointJS library.
// (c) 2011-2013 client IO
joint.shapes.basic = {};
joint.shapes.basic.Generic = joint.dia.Element.extend({
defaults: joint.util.deepSupplement({
type: 'basic.Generic',
attrs: {
'.': { fill: '#ffffff', stroke: 'none' }
}
}, joint.dia.Element.prototype.defaults)
});
joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Rect',
attrs: {
'rect': {
fill: '#ffffff',
stroke: '#000000',
width: 100,
height: 60
},
'text': {
fill: '#000000',
text: '',
'font-size': 14,
'ref-x': .5,
'ref-y': .5,
'text-anchor': 'middle',
'y-alignment': 'middle',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.TextView = joint.dia.ElementView.extend({
initialize: function() {
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
// The element view is not automatically rescaled to fit the model size
// when the attribute 'attrs' is changed.
this.listenTo(this.model, 'change:attrs', this.resize);
}
});
joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><text/></g></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Text',
attrs: {
'text': {
'font-size': 18,
fill: '#000000'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Circle',
size: { width: 60, height: 60 },
attrs: {
'circle': {
fill: '#ffffff',
stroke: '#000000',
r: 30,
cx: 30,
cy: 30
},
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': .5,
'y-alignment': 'middle',
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Ellipse = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><ellipse/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Ellipse',
size: { width: 60, height: 40 },
attrs: {
'ellipse': {
fill: '#ffffff',
stroke: '#000000',
rx: 30,
ry: 20,
cx: 30,
cy: 20
},
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': .5,
'y-alignment': 'middle',
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Polygon = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Polygon',
size: { width: 60, height: 40 },
attrs: {
'polygon': {
fill: '#ffffff',
stroke: '#000000'
},
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref-x': .5,
'ref-dy': 20,
'y-alignment': 'middle',
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Polyline = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><polyline/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Polyline',
size: { width: 60, height: 40 },
attrs: {
'polyline': {
fill: '#ffffff',
stroke: '#000000'
},
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref-x': .5,
'ref-dy': 20,
'y-alignment': 'middle',
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Image',
attrs: {
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref-x': .5,
'ref-dy': 20,
'y-alignment': 'middle',
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>',
defaults: joint.util.deepSupplement({
type: 'basic.Path',
size: { width: 60, height: 60 },
attrs: {
'path': {
fill: '#ffffff',
stroke: '#000000'
},
'text': {
'font-size': 14,
text: '',
'text-anchor': 'middle',
'ref': 'path',
'ref-x': .5,
'ref-dy': 10,
fill: '#000000',
'font-family': 'Arial, helvetica, sans-serif'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.basic.Rhombus = joint.shapes.basic.Path.extend({
defaults: joint.util.deepSupplement({
type: 'basic.Rhombus',
attrs: {
'path': {
d: 'M 30 0 L 60 30 30 60 0 30 z'
},
'text': {
'ref-y': .5,
'y-alignment': 'middle'
}
}
}, joint.shapes.basic.Path.prototype.defaults)
});
// PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy
// to create new shapes with ports functionality. It is assumed that the new shapes have
// `inPorts` and `outPorts` array properties. Only these properties should be used to set ports.
// In other words, using this interface, it is no longer recommended to set ports directly through the
// `attrs` object.
// Usage:
// joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
// getPortAttrs: function(portName, index, total, selector, type) {
// var attrs = {};
// var portClass = 'port' + index;
// var portSelector = selector + '>.' + portClass;
// var portTextSelector = portSelector + '>text';
// var portCircleSelector = portSelector + '>circle';
//
// attrs[portTextSelector] = { text: portName };
// attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } };
// attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
//
// if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
//
// return attrs;
// }
//}));
joint.shapes.basic.PortsModelInterface = {
initialize: function() {
this.updatePortsAttrs();
this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this);
// Call the `initialize()` of the parent.
this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments);
},
updatePortsAttrs: function(eventName) {
// Delete previously set attributes for ports.
var currAttrs = this.get('attrs');
_.each(this._portSelectors, function(selector) {
if (currAttrs[selector]) delete currAttrs[selector];
});
// This holds keys to the `attrs` object for all the port specific attribute that
// we set in this method. This is necessary in order to remove previously set
// attributes for previous ports.
this._portSelectors = [];
var attrs = {};
_.each(this.get('inPorts'), function(portName, index, ports) {
var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in');
this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
_.extend(attrs, portAttributes);
}, this);
_.each(this.get('outPorts'), function(portName, index, ports) {
var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out');
this._portSelectors = this._portSelectors.concat(_.keys(portAttributes));
_.extend(attrs, portAttributes);
}, this);
// Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure
// that, for example, command manager does not register `change:attrs` command but only
// the important `change:inPorts`/`change:outPorts` command.
this.attr(attrs, { silent: true });
// Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent).
this.processPorts();
// Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object.
this.trigger('process:ports');
},
getPortSelector: function(name) {
var selector = '.inPorts';
var index = this.get('inPorts').indexOf(name);
if (index < 0) {
selector = '.outPorts';
index = this.get('outPorts').indexOf(name);
if (index < 0) throw new Error("getPortSelector(): Port doesn't exist.");
}
return selector + '>g:nth-child(' + (index + 1) + ')>circle';
}
};
joint.shapes.basic.PortsViewInterface = {
initialize: function() {
// `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports.
this.listenTo(this.model, 'process:ports', this.update);
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
},
update: function() {
// First render ports so that `attrs` can be applied to those newly created DOM elements
// in `ElementView.prototype.update()`.
this.renderPorts();
joint.dia.ElementView.prototype.update.apply(this, arguments);
},
renderPorts: function() {
var $inPorts = this.$('.inPorts').empty();
var $outPorts = this.$('.outPorts').empty();
var portTemplate = _.template(this.model.portMarkup);
_.each(_.filter(this.model.ports, function(p) { return p.type === 'in'; }), function(port, index) {
$inPorts.append(V(portTemplate({ id: index, port: port })).node);
});
_.each(_.filter(this.model.ports, function(p) { return p.type === 'out'; }), function(port, index) {
$outPorts.append(V(portTemplate({ id: index, port: port })).node);
});
}
};
joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({
markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>',
// if foreignObject supported
'<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">',
'<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>',
'</foreignObject>',
// else foreignObject is not supported (fallback for IE)
'<text class="content"/>',
'</switch></g>'].join(''),
defaults: joint.util.deepSupplement({
type: 'basic.TextBlock',
// see joint.css for more element styles
attrs: {
rect: {
fill: '#ffffff',
stroke: '#000000',
width: 80,
height: 100
},
text: {
fill: '#000000',
'font-size': 14,
'font-family': 'Arial, helvetica, sans-serif'
},
'.content': {
text: '',
ref: 'rect',
'ref-x': .5,
'ref-y': .5,
'y-alignment': 'middle',
'x-alignment': 'middle'
}
},
content: ''
}, joint.shapes.basic.Generic.prototype.defaults),
initialize: function() {
if (typeof SVGForeignObjectElement !== 'undefined') {
// foreignObject supported
this.setForeignObjectSize(this, this.get('size'));
this.setDivContent(this, this.get('content'));
this.listenTo(this, 'change:size', this.setForeignObjectSize);
this.listenTo(this, 'change:content', this.setDivContent);
}
joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments);
},
setForeignObjectSize: function(cell, size) {
// Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead.
// We have to clone size as we don't want attributes.div.style to be same object as attributes.size.
cell.attr({
'.fobj': _.clone(size),
div: { style: _.clone(size) }
});
},
setDivContent: function(cell, content) {
// Append the content to div as html.
cell.attr({ div : {
html: content
}});
}
});
// TextBlockView implements the fallback for IE when no foreignObject exists and
// the text needs to be manually broken.
joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({
initialize: function() {
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
if (typeof SVGForeignObjectElement === 'undefined') {
this.noSVGForeignObjectElement = true;
this.listenTo(this.model, 'change:content', function(cell) {
// avoiding pass of extra paramters
this.updateContent(cell);
});
}
},
update: function(cell, renderingOnlyAttrs) {
if (this.noSVGForeignObjectElement) {
var model = this.model;
// Update everything but the content first.
var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content');
joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs);
if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) {
// Update the content itself.
this.updateContent(model, renderingOnlyAttrs);
}
} else {
joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs);
}
},
updateContent: function(cell, renderingOnlyAttrs) {
// Create copy of the text attributes
var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']);
delete textAttrs.text;
// Break the content to fit the element size taking into account the attributes
// set on the model.
var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, {
// measuring sandbox svg document
svgDocument: this.paper.svg
});
// Create a new attrs with same structure as the model attrs { text: { *textAttributes* }}
var attrs = joint.util.setByPath({}, '.content', textAttrs, '/');
// Replace text attribute with the one we just processed.
attrs['.content'].text = text;
// Update the view using renderingOnlyAttributes parameter.
joint.dia.ElementView.prototype.update.call(this, cell, attrs);
}
});
joint.routers.orthogonal = (function() {
// bearing -> opposite bearing
var opposite = {
N: 'S',
S: 'N',
E: 'W',
W: 'E'
};
// bearing -> radians
var radians = {
N: -Math.PI / 2 * 3,
S: -Math.PI / 2,
E: 0,
W: Math.PI
};
// HELPERS //
// simple bearing method (calculates only orthogonal cardinals)
function bearing(from, to) {
if (from.x == to.x) return from.y > to.y ? 'N' : 'S';
if (from.y == to.y) return from.x > to.x ? 'W' : 'E';
return null;
}
// returns either width or height of a bbox based on the given bearing
function boxSize(bbox, brng) {
return bbox[brng == 'W' || brng == 'E' ? 'width' : 'height'];
}
// expands a box by specific value
function expand(bbox, val) {
return g.rect(bbox).moveAndExpand({ x: -val, y: -val, width: 2 * val, height: 2 * val });
}
// transform point to a rect
function pointBox(p) {
return g.rect(p.x, p.y, 0, 0);
}
// returns a minimal rect which covers the given boxes
function boundary(bbox1, bbox2) {
var x1 = Math.min(bbox1.x, bbox2.x);
var y1 = Math.min(bbox1.y, bbox2.y);
var x2 = Math.max(bbox1.x + bbox1.width, bbox2.x + bbox2.width);
var y2 = Math.max(bbox1.y + bbox1.height, bbox2.y + bbox2.height);
return g.rect(x1, y1, x2 - x1, y2 - y1);
}
// returns a point `p` where lines p,p1 and p,p2 are perpendicular and p is not contained
// in the given box
function freeJoin(p1, p2, bbox) {
var p = g.point(p1.x, p2.y);
if (bbox.containsPoint(p)) p = g.point(p2.x, p1.y);
// kept for reference
// if (bbox.containsPoint(p)) p = null;
return p;
}
// PARTIAL ROUTERS //
function vertexVertex(from, to, brng) {
var p1 = g.point(from.x, to.y);
var p2 = g.point(to.x, from.y);
var d1 = bearing(from, p1);
var d2 = bearing(from, p2);
var xBrng = opposite[brng];
var p = (d1 == brng || (d1 != xBrng && (d2 == xBrng || d2 != brng))) ? p1 : p2;
return { points: [p], direction: bearing(p, to) };
}
function elementVertex(from, to, fromBBox) {
var p = freeJoin(from, to, fromBBox);
return { points: [p], direction: bearing(p, to) };
}
function vertexElement(from, to, toBBox, brng) {
var route = {};
var pts = [g.point(from.x, to.y), g.point(to.x, from.y)];
var freePts = _.filter(pts, function(pt) { return !toBBox.containsPoint(pt); });
var freeBrngPts = _.filter(freePts, function(pt) { return bearing(pt, from) != brng; });
var p;
if (freeBrngPts.length > 0) {
// try to pick a point which bears the same direction as the previous segment
p = _.filter(freeBrngPts, function(pt) { return bearing(from, pt) == brng; }).pop();
p = p || freeBrngPts[0];
route.points = [p];
route.direction = bearing(p, to);
} else {
// Here we found only points which are either contained in the element or they would create
// a link segment going in opposite direction from the previous one.
// We take the point inside element and move it outside the element in the direction the
// route is going. Now we can join this point with the current end (using freeJoin).
p = _.difference(pts, freePts)[0];
var p2 = g.point(to).move(p, -boxSize(toBBox, brng) / 2);
var p1 = freeJoin(p2, from, toBBox);
route.points = [p1, p2];
route.direction = bearing(p2, to);
}
return route;
}
function elementElement(from, to, fromBBox, toBBox) {
var route = elementVertex(to, from, toBBox);
var p1 = route.points[0];
if (fromBBox.containsPoint(p1)) {
route = elementVertex(from, to, fromBBox);
var p2 = route.points[0];
if (toBBox.containsPoint(p2)) {
var fromBorder = g.point(from).move(p2, -boxSize(fromBBox, bearing(from, p2)) / 2);
var toBorder = g.point(to).move(p1, -boxSize(toBBox, bearing(to, p1)) / 2);
var mid = g.line(fromBorder, toBorder).midpoint();
var startRoute = elementVertex(from, mid, fromBBox);
var endRoute = vertexVertex(mid, to, startRoute.direction);
route.points = [startRoute.points[0], endRoute.points[0]];
route.direction = endRoute.direction;
}
}
return route;
}
// Finds route for situations where one of end is inside the other.
// Typically the route is conduct outside the outer element first and
// let go back to the inner element.
function insideElement(from, to, fromBBox, toBBox, brng) {
var route = {};
var bndry = expand(boundary(fromBBox, toBBox), 1);
// start from the point which is closer to the boundary
var reversed = bndry.center().distance(to) > bndry.center().distance(from);
var start = reversed ? to : from;
var end = reversed ? from : to;
var p1, p2, p3;
if (brng) {
// Points on circle with radius equals 'W + H` are always outside the rectangle
// with width W and height H if the center of that circle is the center of that rectangle.
p1 = g.point.fromPolar(bndry.width + bndry.height, radians[brng], start);
p1 = bndry.pointNearestToPoint(p1).move(p1, -1);
} else {
p1 = bndry.pointNearestToPoint(start).move(start, 1);
}
p2 = freeJoin(p1, end, bndry);
if (p1.round().equals(p2.round())) {
p2 = g.point.fromPolar(bndry.width + bndry.height, g.toRad(p1.theta(start)) + Math.PI / 2, end);
p2 = bndry.pointNearestToPoint(p2).move(end, 1).round();
p3 = freeJoin(p1, p2, bndry);
route.points = reversed ? [p2, p3, p1] : [p1, p3, p2];
} else {
route.points = reversed ? [p2, p1] : [p1, p2];
}
route.direction = reversed ? bearing(p1, to) : bearing(p2, to);
return route;
}
// MAIN ROUTER //
// Return points that one needs to draw a connection through in order to have a orthogonal link
// routing from source to target going through `vertices`.
function findOrthogonalRoute(vertices, opt, linkView) {
var padding = opt.elementPadding || 20;
var orthogonalVertices = [];
var sourceBBox = expand(linkView.sourceBBox, padding);
var targetBBox = expand(linkView.targetBBox, padding);
vertices = _.map(vertices, g.point);
vertices.unshift(sourceBBox.center());
vertices.push(targetBBox.center());
var brng;
for (var i = 0, max = vertices.length - 1; i < max; i++) {
var route = null;
var from = vertices[i];
var to = vertices[i + 1];
var isOrthogonal = !!bearing(from, to);
if (i == 0) {
if (i + 1 == max) { // route source -> target
// Expand one of elements by 1px so we detect also situations when they
// are positioned one next other with no gap between.
if (sourceBBox.intersect(expand(targetBBox, 1))) {
route = insideElement(from, to, sourceBBox, targetBBox);
} else if (!isOrthogonal) {
route = elementElement(from, to, sourceBBox, targetBBox);
}
} else { // route source -> vertex
if (sourceBBox.containsPoint(to)) {
route = insideElement(from, to, sourceBBox, expand(pointBox(to), padding));
} else if (!isOrthogonal) {
route = elementVertex(from, to, sourceBBox);
}
}
} else if (i + 1 == max) { // route vertex -> target
var orthogonalLoop = isOrthogonal && bearing(to, from) == brng;
if (targetBBox.containsPoint(from) || orthogonalLoop) {
route = insideElement(from, to, expand(pointBox(from), padding), targetBBox, brng);
} else if (!isOrthogonal) {
route = vertexElement(from, to, targetBBox, brng);
}
} else if (!isOrthogonal) { // route vertex -> vertex
route = vertexVertex(from, to, brng);
}
if (route) {
Array.prototype.push.apply(orthogonalVertices, route.points);
brng = route.direction;
} else {
// orthogonal route and not looped
brng = bearing(from, to);
}
if (i + 1 < max) {
orthogonalVertices.push(to);
}
}
return orthogonalVertices;
};
return findOrthogonalRoute;
})();
joint.routers.manhattan = (function() {
'use strict';
var config = {
// size of the step to find a route
step: 10,
// use of the perpendicular linkView option to connect center of element with first vertex
perpendicular: true,
// tells how to divide the paper when creating the elements map
mapGridSize: 100,
// should be source or target not to be consider as an obstacle
excludeEnds: [], // 'source', 'target'
// should be any element with a certain type not to be consider as an obstacle
excludeTypes: ['basic.Text'],
// if number of route finding loops exceed the maximum, stops searching and returns
// fallback route
maximumLoops: 500,
// possible starting directions from an element
startDirections: ['left', 'right', 'top', 'bottom'],
// possible ending directions to an element
endDirections: ['left', 'right', 'top', 'bottom'],
// specify directions above
directionMap: {
right: { x: 1, y: 0 },
bottom: { x: 0, y: 1 },
left: { x: -1, y: 0 },
top: { x: 0, y: -1 }
},
// maximum change of the direction
maxAllowedDirectionChange: 1,
// padding applied on the element bounding boxes
paddingBox: function() {
var step = this.step;
return {
x: -step,
y: -step,
width: 2 * step,
height: 2 * step
};
},
// an array of directions to find next points on the route
directions: function() {
var step = this.step;
return [
{ offsetX: step , offsetY: 0 , cost: step },
{ offsetX: 0 , offsetY: step , cost: step },
{ offsetX: -step , offsetY: 0 , cost: step },
{ offsetX: 0 , offsetY: -step , cost: step }
];
},
// a penalty received for direction change
penalties: function() {
return [0, this.step / 2, this.step];
},
// heurestic method to determine the distance between two points
estimateCost: function(from, to) {
return from.manhattanDistance(to);
},
// a simple route used in situations, when main routing method fails
// (exceed loops, inaccessible).
fallbackRoute: function(from, to, opts) {
// Find an orthogonal route ignoring obstacles.
var prevDirIndexes = opts.prevDirIndexes || {};
var point = (prevDirIndexes[from] || 0) % 2
? g.point(from.x, to.y)
: g.point(to.x, from.y);
return [point, to];
},
// if a function is provided, it's used to route the link while dragging an end
// i.e. function(from, to, opts) { return []; }
draggingRoute: null
};
// reconstructs a route by concating points with their parents
function reconstructRoute(parents, point) {
var route = [];
var prevDiff = { x: 0, y: 0 };
var current = point;
var parent;
while ((parent = parents[current])) {
var diff = parent.difference(current);
if (!diff.equals(prevDiff)) {
route.unshift(current);
prevDiff = diff;
}
current = parent;
}
route.unshift(current);
return route;
};
// find points around the rectangle taking given directions in the account
function getRectPoints(bbox, directionList, opts) {
var step = opts.step;
var center = bbox.center();
var startPoints = _.chain(opts.directionMap).pick(directionList).map(function(direction) {
var x = direction.x * bbox.width / 2;
var y = direction.y * bbox.height / 2;
var point = g.point(center).offset(x, y).snapToGrid(step);
if (bbox.containsPoint(point)) {
point.offset(direction.x * step, direction.y * step);
}
return point;
}).value();
return startPoints;
};
// returns a direction index from start point to end point
function getDirection(start, end, dirLen) {
var dirAngle = 360 / dirLen;
var q = Math.floor(start.theta(end) / dirAngle);
return dirLen - q;
}
// finds the route between to points/rectangles implementing A* alghoritm
function findRoute(start, end, map, opt) {
var startDirections = opt.reversed ? opt.endDirections : opt.startDirections;
var endDirections = opt.reversed ? opt.startDirections : opt.endDirections;
// set of points we start pathfinding from
var startSet = start instanceof g.rect
? getRectPoints(start, startDirections, opt)
: [start];
// set of points we want the pathfinding to finish at
var endSet = end instanceof g.rect
? getRectPoints(end, endDirections, opt)
: [end];
var startCenter = startSet.length > 1 ? start.center() : startSet[0];
var endCenter = endSet.length > 1 ? end.center() : endSet[0];
// take into account only accessible end points
var endPoints = _.filter(endSet, function(point) {
var mapKey = g.point(point).snapToGrid(opt.mapGridSize).toString();
var accesible = _.every(map[mapKey], function(obstacle) {
return !obstacle.containsPoint(point);
});
return accesible;
});
if (endPoints.length) {
var step = opt.step;
var penalties = opt.penalties;
// choose the end point with the shortest estimated path cost
var endPoint = _.chain(endPoints).invoke('snapToGrid', step).min(function(point) {
return opt.estimateCost(startCenter, point);
}).value();
var parents = {};
var costFromStart = {};
var totalCost = {};
// directions
var dirs = opt.directions;
var dirLen = dirs.length;
var dirHalfLen = dirLen / 2;
var dirIndexes = opt.previousDirIndexes || {};
// The set of point already evaluated.
var closeHash = {}; // keeps only information whether a point was evaluated'
// The set of tentative points to be evaluated, initially containing the start points
var openHash = {}; // keeps only information whether a point is to be evaluated'
var openSet = _.chain(startSet).invoke('snapToGrid', step).each(function(point) {
var key = point.toString();
costFromStart[key] = 0; // Cost from start along best known path.
totalCost[key] = opt.estimateCost(point, endPoint);
dirIndexes[key] = dirIndexes[key] || getDirection(startCenter, point, dirLen);
openHash[key] = true;
}).map(function(point) {
return point.toString();
}).sortBy(function(pointKey) {
return totalCost[pointKey];
}).value();
var loopCounter = opt.maximumLoops;
var maxAllowedDirectionChange = opt.maxAllowedDirectionChange;
// main route finding loop
while (openSet.length && loopCounter--) {
var currentKey = openSet[0];
var currentPoint = g.point(currentKey);
if (endPoint.equals(currentPoint)) {
opt.previousDirIndexes = _.pick(dirIndexes, currentKey);
return reconstructRoute(parents, currentPoint);
}
// remove current from the open list
openSet.splice(0, 1);
openHash[neighborKey] = null;
// add current to the close list
closeHash[neighborKey] = true;
var currentDirIndex = dirIndexes[currentKey];
var currentDist = costFromStart[currentKey];
for (var dirIndex = 0; dirIndex < dirLen; dirIndex++) {
var dirChange = Math.abs(dirIndex - currentDirIndex);
if (dirChange > dirHalfLen) {
dirChange = dirLen - dirChange;
}
// if the direction changed rapidly don't use this point
if (dirChange > maxAllowedDirectionChange) {
continue;
}
var dir = dirs[dirIndex];
var neighborPoint = g.point(currentPoint).offset(dir.offsetX, dir.offsetY);
var neighborKey = neighborPoint.toString();
if (closeHash[neighborKey]) {
continue;
}
// is point accesible - no obstacle in the way
var mapKey = g.point(neighborPoint).snapToGrid(opt.mapGridSize).toString();
var isAccesible = _.every(map[mapKey], function(obstacle) {
return !obstacle.containsPoint(neighborPoint);
});
if (!isAccesible) {
continue;
}
var inOpenSet = _.has(openHash, neighborKey);
var costToNeighbor = currentDist + dir.cost;
if (!inOpenSet || costToNeighbor < costFromStart[neighborKey]) {
parents[neighborKey] = currentPoint;
dirIndexes[neighborKey] = dirIndex;
costFromStart[neighborKey] = costToNeighbor;
totalCost[neighborKey] = costToNeighbor +
opt.estimateCost(neighborPoint, endPoint) +
penalties[dirChange];
if (!inOpenSet) {
var openIndex = _.sortedIndex(openSet, neighborKey, function(openKey) {
return totalCost[openKey];
});
openSet.splice(openIndex, 0, neighborKey);
openHash[neighborKey] = true;
}
};
};
}
}
// no route found ('to' point wasn't either accessible or finding route took
// way to much calculations)
return opt.fallbackRoute(startCenter, endCenter, opt);
};
// initiation of the route finding
function router(oldVertices, opt) {
// resolve some of the options
opt.directions = _.result(opt, 'directions');
opt.penalties = _.result(opt, 'penalties');
opt.paddingBox = _.result(opt, 'paddingBox');
// enable/disable linkView perpendicular option
this.options.perpendicular = !!opt.perpendicular;
// As route changes its shape rapidly when we start finding route from different point
// it's necessary to start from the element that was not interacted with
// (the position was changed) at very last.
var reverseRouting = opt.reversed = (this.lastEndChange === 'source');
var sourceBBox = reverseRouting ? g.rect(this.targetBBox) : g.rect(this.sourceBBox);
var targetBBox = reverseRouting ? g.rect(this.sourceBBox) : g.rect(this.targetBBox);
// expand boxes by specific padding
sourceBBox.moveAndExpand(opt.paddingBox);
targetBBox.moveAndExpand(opt.paddingBox);
// building an elements map
var link = this.model;
var graph = this.paper.model;
// source or target element could be excluded from set of obstacles
var excludedEnds = _.chain(opt.excludeEnds)
.map(link.get, link)
.pluck('id')
.map(graph.getCell, graph).value();
var mapGridSize = opt.mapGridSize;
var excludeAncestors = [];
var sourceId = link.get('source').id;
if (sourceId !== undefined) {
var source = graph.getCell(sourceId);
if (source !== undefined) {
excludeAncestors = _.union(excludeAncestors, _.map(source.getAncestors(), 'id'));
};
}
var targetId = link.get('target').id;
if (targetId !== undefined) {
var target = graph.getCell(targetId);
if (target !== undefined) {
excludeAncestors = _.union(excludeAncestors, _.map(target.getAncestors(), 'id'));
}
}
// builds a map of all elements for quicker obstacle queries (i.e. is a point contained
// in any obstacle?) (a simplified grid search)
// The paper is divided to smaller cells, where each of them holds an information which
// elements belong to it. When we query whether a point is in an obstacle we don't need
// to go through all obstacles, we check only those in a particular cell.
var map = _.chain(graph.getElements())
// remove source and target element if required
.difference(excludedEnds)
// remove all elements whose type is listed in excludedTypes array
.reject(function(element) {
// reject any element which is an ancestor of either source or target
return _.contains(opt.excludeTypes, element.get('type')) || _.contains(excludeAncestors, element.id);
})
// change elements (models) to their bounding boxes
.invoke('getBBox')
// expand their boxes by specific padding
.invoke('moveAndExpand', opt.paddingBox)
// build the map
.foldl(function(res, bbox) {
var origin = bbox.origin().snapToGrid(mapGridSize);
var corner = bbox.corner().snapToGrid(mapGridSize);
for (var x = origin.x; x <= corner.x; x += mapGridSize) {
for (var y = origin.y; y <= corner.y; y += mapGridSize) {
var gridKey = x + '@' + y;
res[gridKey] = res[gridKey] || [];
res[gridKey].push(bbox);
}
}
return res;
}, {}).value();
// pathfinding
var newVertices = [];
var points = _.map(oldVertices, g.point);
var tailPoint = sourceBBox.center();
// find a route by concating all partial routes (routes need to go through the vertices)
// startElement -> vertex[1] -> ... -> vertex[n] -> endElement
for (var i = 0, len = points.length; i <= len; i++) {
var partialRoute = null;
var from = to || sourceBBox;
var to = points[i];
if (!to) {
to = targetBBox;
// 'to' is not a vertex. If the target is a point (i.e. it's not an element), we
// might use dragging route instead of main routing method if that is enabled.
var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id;
if (endingAtPoint && _.isFunction(opt.draggingRoute)) {
// Make sure we passing points only (not rects).
var dragFrom = from instanceof g.rect ? from.center() : from;
partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt);
}
}
// if partial route has not been calculated yet use the main routing method to find one
partialRoute = partialRoute || findRoute(from, to, map, opt);
var leadPoint = _.first(partialRoute);
if (leadPoint && leadPoint.equals(tailPoint)) {
// remove the first point if the previous partial route had the same point as last
partialRoute.shift();
}
tailPoint = _.last(partialRoute) || tailPoint;
newVertices = newVertices.concat(partialRoute);
};
// we might have to reverse the result if we swapped source and target at the beginning
return reverseRouting ? newVertices.reverse() : newVertices;
};
// public function
return function(vertices, opt, linkView) {
return router.call(linkView, vertices, _.extend({}, config, opt));
};
})();
joint.routers.metro = (function() {
if (!_.isFunction(joint.routers.manhattan)) {
throw('Metro requires the manhattan router.');
}
var config = {
// cost of a diagonal step (calculated if not defined).
diagonalCost: null,
// an array of directions to find next points on the route
directions: function() {
var step = this.step;
var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1));
return [
{ offsetX: step , offsetY: 0 , cost: step },
{ offsetX: step , offsetY: step , cost: diagonalCost },
{ offsetX: 0 , offsetY: step , cost: step },
{ offsetX: -step , offsetY: step , cost: diagonalCost },
{ offsetX: -step , offsetY: 0 , cost: step },
{ offsetX: -step , offsetY: -step , cost: diagonalCost },
{ offsetX: 0 , offsetY: -step , cost: step },
{ offsetX: step , offsetY: -step , cost: diagonalCost }
];
},
// a simple route used in situations, when main routing method fails
// (exceed loops, inaccessible).
fallbackRoute: function(from, to, opts) {
// Find a route which breaks by 45 degrees ignoring all obstacles.
var theta = from.theta(to);
var a = { x: to.x, y: from.y };
var b = { x: from.x, y: to.y };
if (theta % 180 > 90) {
var t = a;
a = b;
b = t;
}
var p1 = (theta % 90) < 45 ? a : b;
var l1 = g.line(from, p1);
var alpha = 90 * Math.ceil(theta / 90);
var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1);
var l2 = g.line(to, p2);
var point = l1.intersection(l2);
return point ? [point.round(), to] : [to];
}
};
// public function
return function(vertices, opts, linkView) {
return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView);
};
})();
joint.connectors.normal = function(sourcePoint, targetPoint, vertices) {
// Construct the `d` attribute of the `<path>` element.
var d = ['M', sourcePoint.x, sourcePoint.y];
_.each(vertices, function(vertex) {
d.push(vertex.x, vertex.y);
});
d.push(targetPoint.x, targetPoint.y);
return d.join(' ');
};
joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) {
var offset = opts.radius || 10;
var c1, c2, d1, d2, prev, next;
// Construct the `d` attribute of the `<path>` element.
var d = ['M', sourcePoint.x, sourcePoint.y];
_.each(vertices, function(vertex, index) {
// the closest vertices
prev = vertices[index - 1] || sourcePoint;
next = vertices[index + 1] || targetPoint;
// a half distance to the closest vertex
d1 = d2 || g.point(vertex).distance(prev) / 2;
d2 = g.point(vertex).distance(next) / 2;
// control points
c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round();
c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round();
d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L');
});
d.push(targetPoint.x, targetPoint.y);
return d.join(' ');
};
joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) {
var d;
if (vertices.length) {
d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint]));
} else {
// if we have no vertices use a default cubic bezier curve, cubic bezier requires
// two control points. The two control points are both defined with X as mid way
// between the source and target points. SourceControlPoint Y is equal to sourcePoint Y
// and targetControlPointY being equal to targetPointY. Handle situation were
// sourcePointX is greater or less then targetPointX.
var controlPointX = (sourcePoint.x < targetPoint.x)
? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2)
: sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2);
d = [
'M', sourcePoint.x, sourcePoint.y,
'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y,
targetPoint.x, targetPoint.y
];
}
return d.join(' ');
};
|
src/routes/Dashboard/components/Map/Map.story.js
|
gabe-terrell/acme-freight-webui
|
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Map } from './Map';
storiesOf('Map', module)
.add('empty', () => (
<Map />
))
.add('with data', () => (
<Map
distributionCenters={[
{
address: {
city: 'Salt Lake City',
state: 'Utah',
country: 'US',
latitude: 40.71,
longitude: -111.90,
},
contact: {
name: 'Joseph Smith',
},
},
{
address: {
city: 'Cincinnati',
state: 'Ohio',
country: 'US',
latitude: 39.10,
longitude: -84.49,
},
contact: {
name: 'Joseph Smith',
},
},
]}
shipments={[
{
status: 'APPROVED',
currentLocation: {
city: 'Memphis',
state: 'Tennessee',
country: 'US',
latitude: 35.19,
longitude: -90.02,
},
},
]}
retailers={[
{
address: {
city: 'Austin',
state: 'Texas',
country: 'US',
latitude: 30.22,
longitude: -97.74,
},
},
]}
storms={[
{
event: {
event_desc: 'Snow Storm',
lat: 38.89,
lon: -77.03,
radiusInKm: 800,
severity: 'Moderate',
},
},
]}
/>
));
|
js/components/tab/tabTwo.js
|
HomelandGvarim/FE-Phone
|
import React, { Component } from 'react';
import { Container, Content, Card, CardItem, Text, Body } from 'native-base';
import styles from './styles';
export default class TabTwo extends Component {
// eslint-disable-line
render() {
// eslint-disable-line
return (
<Content padder style={{ marginTop: 0 }}>
<Card style={{ flex: 0 }}>
<CardItem>
<Body>
<Text>
NativeBase builds a layer on top of React Native that provides you with basic set of
components for mobile application development. This helps you to build world-class
application experiences on native platforms.
</Text>
</Body>
</CardItem>
</Card>
</Content>
);
}
}
|
app/javascript/mastodon/components/status_action_bar.js
|
TootCat/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
});
class StatusActionBar extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onMuteConversation: PropTypes.func,
me: PropTypes.number.isRequired,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'me',
'withDismiss',
]
handleReplyClick = () => {
this.props.onReply(this.props.status, this.context.router);
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleOpen = () => {
this.context.router.push(`/statuses/${this.props.status.get('id')}`);
}
handleReport = () => {
this.props.onReport(this.props.status);
this.context.router.push('/report');
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
render () {
const { status, me, intl, withDismiss } = this.props;
const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct';
const mutingConversation = status.get('muted');
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
menu.push(null);
if (withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = "reply";
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = "reply-all";
replyTitle = intl.formatMessage(messages.replyAll);
}
return (
<div className='status__action-bar'>
<IconButton className='status__action-bar-button' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} />
<IconButton className='status__action-bar-button' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='status__action-bar-button star-icon' animate={true} active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} />
<div className='status__action-bar-dropdown'>
<DropdownMenu items={menu} icon='ellipsis-h' size={18} direction="right" ariaLabel="More"/>
</div>
</div>
);
}
}
export default injectIntl(StatusActionBar);
|
lib/pages/ViewDataset2/index.js
|
Kitware/light-viz
|
import React from 'react';
import PropTypes from 'prop-types';
import clone from 'mout/src/lang/clone';
import VtkRenderer from 'paraviewweb/src/React/Renderers/VtkRenderer';
import SvgIcon from 'paraviewweb/src/React/Widgets/SvgIconWidget';
import ProgressLoaderWidget from 'paraviewweb/src/React/Widgets/ProgressLoaderWidget';
import style from 'LightVizStyle/ViewDataset2.mcss';
import Section from '../../panels/Section';
import modules from '../../modules';
import TimePanel from '../../panels/Time';
import ColorMap from '../../widgets/ColorMap';
import lightVizIcon from '../../../svg/LightViz.svg';
import {
resetCamera,
loadDataset,
getConnection,
getClient,
saveThumbnail,
setForegroundColor,
setBackgroundColor,
onBusyChange,
unsubscribeBusy,
} from '../../client';
const colors = [
{
label: 'White',
pvcolor: '1 1 1',
pvbgcolor: '0 0 0',
cssColor: [255, 255, 255],
cssBGColor: [0, 0, 0],
},
{
label: 'Red',
pvcolor: '.8 .2 .2',
pvbgcolor: '.3 .3 .3',
cssColor: [204, 51, 51],
cssBGColor: [77, 77, 77],
},
{
label: 'Green',
pvcolor: '.2 .8 .2',
pvbgcolor: '.4 .2 .2',
cssColor: [51, 204, 51],
cssBGColor: [102, 51, 51],
},
];
function updateColors(e) {
const idx = e.target.dataset.index;
const scheme = colors[idx];
setForegroundColor(scheme.pvcolor);
setBackgroundColor(scheme.pvbgcolor);
}
export default class ViewDataset2 extends React.Component {
constructor(props) {
super(props);
this.state = {
time: 0,
dataset: {
empty: true,
data: {
arrays: [
{ range: [0, 100], name: 'unkown', location: 'unkown', label: '' },
],
time: [],
bounds: [0, 1, 0, 1, 0, 1],
},
},
datasetId: null,
showControls: false,
busy: false,
};
this.querySaveThumbnail = this.querySaveThumbnail.bind(this);
this.listDataSets = this.listDataSets.bind(this);
this.toggleShowControls = this.toggleShowControls.bind(this);
this.toggleAutoApply = this.toggleAutoApply.bind(this);
this.subscriptionId = onBusyChange((busy) => this.setState({ busy }));
}
componentWillMount() {
this.setState({
datasetId: this.props.match.params.datasetId,
});
loadDataset(this.props.match.params.datasetId, (dataset) =>
this.setState({
dataset,
})
);
}
componentWillReceiveProps(nextProps) {
if (nextProps.match.params.datasetId !== this.state.datasetId) {
this.setState({
datasetId: nextProps.match.params.datasetId,
});
loadDataset(this.props.match.params.datasetId, (dataset) =>
this.setState({
dataset,
})
);
}
}
componentWillUnmount() {
unsubscribeBusy(this.subscriptionId);
}
querySaveThumbnail() {
window.confirm(
"Add a snapshot of the current view to this dataset's thumbnails?\n" +
'The view will be resized and the camera reset before taking the screenshot.'
);
// I'd like to ask the user if they are sure here...
saveThumbnail();
}
listDataSets() {
this.props.history.push('/list');
}
toggleShowControls(e) {
const show = !this.state.showControls;
this.setState({ showControls: show });
}
toggleAutoApply() {
const newAA = !this.state.dataset.autoApply;
const newDataset = clone(this.state.dataset);
newDataset.autoApply = newAA;
this.setState({ dataset: newDataset });
}
render() {
const hideTimeControls = this.state.dataset.data.time.length === 0;
const controlPanelClass = this.state.showControls
? style.controlPanel
: style.controlPanelHidden;
const controlsClass = this.state.showControls
? style.controls
: style.controlsHidden;
const newModules = modules.filter((mdl) => {
if (this.props.profile.modules_included.includes(mdl.name)) {
return true;
}
if (
this.props.profile.modules_included.length === 0 &&
!this.props.profile.modules_excluded.includes(mdl.name)
) {
return true;
}
return false;
});
if (this.state.dataset.empty) {
return <ProgressLoaderWidget message="Dataset loading..." />;
}
return (
<div className={style.viewDataset}>
<div className={controlPanelClass}>
<div className={style.showControlsIconDiv}>
<div className={style.lineItem}>
<i
className={
this.state.showControls
? style.addThumbnailButton
: style.hidden
}
onClick={this.querySaveThumbnail}
/>
{colors.map((c, idx) => {
const myfg = c.cssColor.join(',');
const mybg = c.cssBGColor.join(',');
const mygradient = `radial-gradient(rgb(${myfg}) 30%, rgb(${mybg}) 45%)`;
return (
<div
className={
this.state.showControls ? style.colorItem : style.hidden
}
key={idx}
style={{ background: mygradient }}
data-index={idx}
onClick={updateColors}
/>
);
})}
<div
className={
this.state.showControls
? style.toggleAutoApplyDiv
: style.hidden
}
onClick={this.toggleAutoApply}
>
<i
className={
this.state.dataset.autoApply
? style.autoApplyOnIcon
: style.autoApplyOffIcon
}
/>
Auto-Apply
</div>
</div>
<div className={style.lineItem}>
<i
className={style.listDataSetsButton}
onClick={this.listDataSets}
/>
<i className={style.resetViewButton} onClick={resetCamera} />
<div className={style.logo} onClick={this.toggleShowControls}>
<SvgIcon
icon={lightVizIcon}
height="30px"
width="30px"
style={{ position: 'absolute', top: '-6px', left: 0 }}
/>
</div>
</div>
</div>
<div className={controlsClass}>
{hideTimeControls ? null : (
<div>
<TimePanel
{...this.props}
className={style.timeContainer}
dataset={this.state.dataset}
/>
</div>
)}
<ColorMap dataset={this.state.dataset} />
{newModules.map((panel) => (
<Section
className={style.section}
key={panel.name}
panel={panel}
{...this.props}
dataset={this.state.dataset}
/>
))}
</div>
</div>
<VtkRenderer
className={style.vtkRenderer}
connection={getConnection()}
client={getClient()}
viewId="-1"
/>
{this.state.busy ? (
<ProgressLoaderWidget message="Server busy" />
) : null}
</div>
);
}
}
ViewDataset2.propTypes = {
profile: PropTypes.object,
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
ViewDataset2.defaultProps = {
profile: undefined,
};
|
fields/types/color/ColorColumn.js
|
asifiqbal84/keystone
|
import React from 'react';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var ColorColumn = React.createClass({
displayName: 'ColorColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value) return null;
let colorBoxStyle = {
backgroundColor: value,
borderRadius: 3,
display: 'inline-block',
height: 18,
marginRight: 10,
verticalAlign: 'middle',
width: 18,
};
return (
<ItemsTableValue truncate={false} field={this.props.col.type}>
<div style={{ lineHeight: '18px' }}>
<span style={colorBoxStyle} />
<span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{value}</span>
</div>
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = ColorColumn;
|
client/src/components/General/UsernameInput.js
|
patteri/slave-cardgame
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import { FormGroup, ControlLabel, FormControl, Alert } from 'react-bootstrap';
import _ from 'lodash';
import classNames from 'classnames';
import { GameValidation as gv } from '../../shared/constants';
import api from '../../api/api';
import store from '../../store';
import { openErrorModal } from '../Errors/actions';
import './style.css';
class UsernameInput extends Component {
constructor(props) {
super(props);
this.state = {
username: props.initialValue ? props.initialValue : '',
isValid: false,
isReserved: false
};
this.queryUsernameAvailable = _.debounce(this.queryUsernameAvailable, 500, {
leading: true,
trailing: true
});
}
onUsernameChanged(username) {
const state = {
username: username,
isValid: false,
isReserved: false
};
this.setState(state);
this.props.onUsernameChanged(state);
if (username != null) {
this.queryUsernameAvailable(username);
}
}
queryUsernameAvailable(username) {
api.auth.usernameAvailable(username).then((response) => {
// Query may be outdated. Validate only if not.
if (username === this.state.username) {
let isValid = response.data.available && username.length >= gv.minUsernameLength &&
username.length <= gv.maxUsernameLength;
const state = {
username: username,
isValid,
isReserved: !response.data.available
};
this.setState(state);
this.props.onUsernameChanged(state);
}
}).catch(() => {
store.dispatch(openErrorModal('An unknown error occurred.'));
});
}
render() {
const { controlId, showHeader, showRegistrationText } = this.props;
return (
<FormGroup controlId={controlId}>
{showHeader &&
<ControlLabel>Player name</ControlLabel>
}
{showRegistrationText &&
<FormControl.Static className="Field-additional-text">
Improve experience by <Link to="/register">registering</Link> your player name!
</FormControl.Static>
}
{this.state.isReserved &&
<Alert bsStyle="danger" className="input-alert">
The player name is reserved
</Alert>
}
<div className={classNames({ 'has-error': this.state.isReserved })}>
<FormControl
type="text"
value={this.state.username}
required
maxLength={gv.maxUsernameLength}
onChange={e => this.onUsernameChanged(e.target.value)}
/>
</div>
</FormGroup>
);
}
}
UsernameInput.defaultProps = {
showHeader: true,
showRegistrationText: false
};
UsernameInput.propTypes = {
initialValue: PropTypes.string,
controlId: PropTypes.string.isRequired,
showHeader: PropTypes.bool,
showRegistrationText: PropTypes.bool,
onUsernameChanged: PropTypes.func.isRequired
};
export default UsernameInput;
|
playgrounds/cra/src/App.js
|
emotion-js/emotion
|
/** @jsxImportSource @emotion/react */
import React from 'react'
import { Global } from '@emotion/react'
function App() {
return (
<div>
<Global
styles={{
body: {
padding: '2rem',
fontFamily: 'sans-serif'
},
h1: {
marginTop: 0
}
}}
/>
<h1>CRA Playground</h1>
<div css={{ color: 'orchid' }}>Some colored text</div>
</div>
)
}
export default App
|
stories/SuppliedSimpleUserFormDemo.js
|
de44/kb-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import kb from '../src/kb-ui';
import { withState, compose } from 'recompose';
import FormDemo from './FormDemo';
function getUser(id, name, email, suspended) {
return {
id,
name,
email,
suspended,
profile: {
bio: '<h4 style="border-bottom: 1px dashed red;"><span style="color: blue">Hello, </span><span style="color: green">World!</span></h4>',
website: {
url: "https://github.com/de44",
text: "de44 (github)"
}
}
}
}
const supplier = kb.suppliers.mem([
getUser('a', 'David P', 'david@bc.com', false),
getUser('c', 'David H', 'davidh@bc.com', false),
getUser('d', 'David E', 'davide@bc.com', false),
getUser('e', 'John Mo', 'johnmo@bc.com', true),
getUser('f', 'John Mc', 'johnmc@bc.com', true)
])
const form = kb.form()
.supplier(supplier)
.fields([
kb.field('id').readOnly(true).defaultValue('asdf-1234-qwerty-567890'),
kb.field('name'),
kb.field('email'),
kb.field('suspened', 'bool')
]);
const formDef = `function getUser(id, name, email, suspended) {
return {
id,
name,
email,
suspended,
profile: {
bio: '<h4 style="border-bottom: 1px dashed red;"><span style="color: blue">Hello, </span><span style="color: green">World!</span></h4>',
website: {
url: "https://github.com/de44",
text: "de44 (github)"
}
}
}
}
const supplier = kb.suppliers.mem([
getUser('a', 'David P', 'david@bc.com', false),
getUser('c', 'David H', 'davidh@bc.com', false),
getUser('d', 'David E', 'davide@bc.com', false),
getUser('e', 'John Mo', 'johnmo@bc.com', false),
getUser('f', 'John Mc', 'johnmc@bc.com', false)
])
const form = kb.form()
.supplier(supplier)
.fields([
kb.field('id').readOnly(true).defaultValue('asdf-1234-qwerty-567890'),
kb.field('name'),
kb.field('email'),
kb.field('suspened', 'bool')
]);`;
const SuppliedSimpleUserFormDemo = ({ id, setId }) => {
return (
<div className="SimpleUserFormDemo">
<div>
Set Id: <input type="text" onChange={e=>setId(e.target.value)} value={id} />
</div>
<hr/>
<FormDemo form={form} formDef={formDef} model={id} />
</div>
);
};
export default compose(
withState('id', 'setId', 'a')
)(SuppliedSimpleUserFormDemo);
|
app/javascript/mastodon/features/ui/index.js
|
8796n/mastodon
|
import React from 'react';
import ColumnsArea from './components/columns_area';
import NotificationsContainer from './containers/notifications_container';
import PropTypes from 'prop-types';
import LoadingBarContainer from './containers/loading_bar_container';
import HomeTimeline from '../home_timeline';
import Compose from '../compose';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import Notifications from '../notifications';
import { connect } from 'react-redux';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose } from '../../actions/compose';
import { refreshTimeline } from '../../actions/timelines';
import { refreshNotifications } from '../../actions/notifications';
import UploadArea from './components/upload_area';
const noOp = () => false;
class UI extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node
};
state = {
width: window.innerWidth,
draggingOver: false
};
handleResize = () => {
this.setState({ width: window.innerWidth });
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && e.dataTransfer.types.includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
this.props.dispatch(refreshTimeline('home'));
this.props.dispatch(refreshNotifications());
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = (c) => {
this.node = c;
}
render () {
const { width, draggingOver } = this.state;
const { children } = this.props;
let mountedColumns;
if (isMobile(width)) {
mountedColumns = (
<ColumnsArea>
{children}
</ColumnsArea>
);
} else {
mountedColumns = (
<ColumnsArea>
<Compose withHeader={true} />
<HomeTimeline shouldUpdateScroll={noOp} />
<Notifications shouldUpdateScroll={noOp} />
<div style={{display: 'flex', flex: '1 1 auto', position: 'relative'}}>{children}</div>
</ColumnsArea>
);
}
return (
<div className='ui' ref={this.setRef}>
<TabsBar />
{mountedColumns}
<NotificationsContainer />
<LoadingBarContainer className="loading-bar" />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
);
}
}
export default connect()(UI);
|
frontend/app/js/components/processes/process.js
|
serverboards/serverboards
|
import React from 'react'
import Loading from '../loading'
import rpc from 'app/rpc'
import {goto} from 'app/utils/store'
import {i18n} from 'app/utils/i18n'
import Modal from '../modal'
class ProcessView extends React.Component{
render(){
let process = this.props.process
if (!process)
return (
<Loading>{i18n("Process history")}</Loading>
)
let label_color=""
switch(process.status){
case "running":
label_color="olive"
break;
case "error":
label_color="red"
break;
case "aborted":
label_color="orange"
break;
case "ok":
label_color="green"
break;
}
return (
<Modal className="wide">
<div className="ui central white background">
<div className="ui text container">
<h1 className="ui header">{i18n(process.action)}</h1>
<span className="ui text label" style={{float:"left"}}><span className={`ui rectangular label ${label_color}`} style={{float:"right"}}/>{i18n(process.status)}</span>
<div className="ui meta">{process.type}</div>
<div className="ui meta">{process.uuid}</div>
<ul>
<li>{i18n("Date")}: {process.date}</li>
<li>{i18n("User")}: {process.user}</li>
{process.elapsed ? (
<li>{i18n("Elapsed")}: {process.elapsed} ms</li>
) : null}
{process.params.rule ? (
<li>{i18n("Related rule")}:
{process.params.rule.project ? (
<a onClick={() => goto(`/project/${process.params.rule.project}/rules/${process.params.rule.uuid}`)} style={{cursor:"pointer"}}>
<span> {process.params.rule.name || process.params.rule.trigger.trigger}</span>
</a>
) : (
<span> {process.params.rule.name || process.params.rule.trigger.trigger}</span>
) }
</li>
) : null}
{process.params ? (
<li>{i18n("Action params")}:
<pre className="ui code json">{JSON.stringify(process.params, null, 2)}</pre>
</li>
) : null}
{process.result ? (
<li>{i18n("Action result")}:
<pre className="ui code json">{JSON.stringify(process.result, null, 2)}</pre>
</li>
) : null}
</ul>
</div>
</div>
</Modal>
)
}
}
export default ProcessView
|
assets/jqwidgets/demos/react/app/complexinput/changeevent/app.js
|
juannelisalde/holter
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxComplexInput from '../../../jqwidgets-react/react_jqxcomplexinput.js';
import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js';
class App extends React.Component {
componentDidMount() {
this.refs.myComplexInput.on('change', (event) => {
let args = event.args;
if (args) {
let value = args.value;
let oldValue = args.oldValue;
let realPart = args.realPart;
let imaginaryPart = args.imaginaryPart;
this.refs.myPanel.append('<strong>' + event.type + '</strong><br />' +
'value: ' + value + ', old value: ' + oldValue +
',<br /> real part: ' + realPart + ', imaginary part: ' + imaginaryPart + '<br />');
}
});
}
render() {
return (
<div>
<JqxComplexInput ref='myComplexInput'
width={300} height={25} value={'15 + 7i'} spinButtons={true}
/>
<div style={{ marginTop: 20 }}>Events log:</div>
<JqxPanel ref='myPanel' width={300} height={150} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
packages/react-static/src/browser/components/Default404.js
|
nozzle/react-static
|
import React from 'react'
export default () => (
<div>404 - We couldn't find the page you're looking for!</div>
)
|
app/views/components/go-back-button/index.js
|
get-focus/focus-demo-app
|
import React from 'react';
import {withRouter} from 'react-router';
import ButtonBack from 'focus-components/button-back';
const GoBackComponent = ({router}) => (
<ButtonBack back={router.goBack} />
);
export default withRouter(GoBackComponent);
|
src/components/Display/ProductPagination.js
|
CoreyDH/product-finder
|
import React from 'react';
import {Row, Col} from 'react-bootstrap';
// import {AutoAffix} from 'react-overlays';
import ReactPaginate from 'react-paginate';
export default class ProductPagination extends React.Component {
changeOffset(event) {
// console.log('offset', event.selected, this.props.amount, event.selected*this.props.amount);
this.props.refreshProducts({
offset: event.selected*this.props.amount
})
}
render() {
// console.log('pagination', this.props.total, this.props.amount);
return (
<Row>
<Col xs={12} className="product-finder-pagination">
{this.props.total > this.props.amount &&
<ReactPaginate
previousLabel={<span className="glyphicon glyphicon-chevron-left"></span>}
nextLabel={<span className="glyphicon glyphicon-chevron-right"></span>}
breakLabel={<a>...</a>}
breakClassName={"break-me"}
pageCount={Math.ceil(this.props.total/this.props.amount)}
forcePage={Math.floor(this.props.offset/this.props.amount)}
marginPagesDisplayed={5}
pageRangeDisplayed={5}
onPageChange={this.changeOffset.bind(this)}
containerClassName={"pagination"}
subContainerClassName={"pages pagination"}
activeClassName={"active"} />
}
</Col>
</Row>
)
};
}
|
examples/pinterest/app.js
|
flocks/react-router
|
import React from 'react';
import { Router, Link } from 'react-router';
import HashHistory from 'react-router/lib/HashHistory';
var history = new HashHistory({ queryKey: 'k' });
var pictures = [
{id: 0, src: 'http://placekitten.com/601/601'},
{id: 1, src: 'http://placekitten.com/610/610'},
{id: 2, src: 'http://placekitten.com/620/620'},
];
var App = React.createClass({
render () {
return (
<div>
<h1>Pinterest Style Routes</h1>
<p>
The url `/pictures/:id` can potentially match two routes,
it all depends on if the url was navigated to from the feed or
not.
</p>
<p>
Click on an item in the feed, and see that it opens in an overlay.
Then copy/paste it into a different browser window (Like Chrome -> Firefox),
and see that the image does not render inside the overlay. One URL, two
session dependent routes and UI :D
</p>
{this.props.children}
</div>
);
}
});
var Feed = React.createClass({
overlayStyles: {
position: 'fixed',
top: 30,
right: 30,
bottom: 30,
left: 30,
padding: 20,
boxShadow: '0px 0px 50px 30px rgba(0, 0, 0, 0.5)',
overflow: 'auto',
background: '#fff'
},
render () {
return (
<div>
<div>
{pictures.map(picture => (
<Link
to={`/pictures/${picture.id}`}
state={{fromFeed: true}}
>
<img style={{margin: 10}} src={picture.src} height="100"/>
</Link>
))}
</div>
{this.props.children && (
<div style={this.overlayStyles}>
{this.props.children}
</div>
)}
</div>
);
}
});
var FeedPicture = React.createClass({
render () {
return (
<div>
<h2>Inside the feed</h2>
<Link to="/">back</Link>
<p>
<img src={pictures[this.props.params.id].src} height="400"/>
</p>
</div>
);
}
});
var Picture = React.createClass({
render () {
return (
<div>
<h2>Not Inside the feed</h2>
<Link to="/">Feed</Link>
<p>
<img src={pictures[this.props.params.id].src}/>
</p>
</div>
);
}
});
var FeedPictureRoute = {
path: '/pictures/:id',
component: FeedPicture
};
var FeedRoute = {
component: Feed,
childRoutes: [ FeedPictureRoute ],
};
var PictureRoute = {
path: '/pictures/:id',
component: Picture
};
var RootRoute = {
path: '/',
component: App,
indexRoute: FeedRoute,
getChildRoutes (state, cb) {
if (state && state.fromFeed) {
cb(null, [ FeedRoute ]);
}
else {
cb(null, [ PictureRoute ]);
}
}
};
React.render(
<Router history={history} children={RootRoute}/>,
document.getElementById('example')
);
// Wait a sec ... what's happening?
//
// 1. When you visit "/" `RootRoute.indexRoute` is matched,
// which is `FeedRoute`, and that renders `Feed`.
//
// 2. Then, when you click a link on the feed, it sets some location `state`,
// particularly, `fromFeed`.
//
// 3. The router calls `RootRoute.getChildRoutes` while matching, which
// branches on `transitionState.fromFeed` and calls back with only
// `FeedRoute` as a child, so `PictureRoute` has no chance of ever matching.
//
// 4. `FeedRoute` has no path, so the router will dig down into its children
// to try to find a match, and finds `FeedPictureRoute` as a match.
//
// 5. The components `App -> Feed -> FeedPicture` all render.
//
// 6. Hit refresh in the browser.
//
// 7. The url is not `/` so `RootRoute.indexRoute` does not get matched.
//
// 8. Since there is no `transitionState`, `RootRoute.getChildRoutes` branches
// the other way, and callsback with `PictureRoute` as a child, which matches
// the url.
//
// 9. `App -> PictureRoute` renders
//
// 10. I am very glad there aren't ten steps to explain this ...
//
|
src/script/ListChannel.js
|
phuongnd11/frequency-poc
|
import React from 'react';
import ChannelItem from './ChannelItem';
class ListChannel extends React.Component {
constructor(props) {
super(props);
this.state = {
channels: [],
videos: [],
activeRow: null,
};
this.eachChannel = this.eachChannel.bind(this);
this.handleRowClick = this.handleRowClick.bind(this);
}
componentDidMount() {
this.fetchChannels();
}
fetchChannels() {
const $ = require('jquery');
$.ajax({
url: 'http://203.162.103.34:8082/cors-proxy-1.0-SNAPSHOT/cn1-cors-proxy?_target=https://dev.freq.us/api/2.0/channels/all',
type: 'get',
headers: {
'Content-Type': 'application/json',
'X-Frequency-DeviceId': '556a6dc3-1ea0-09b6',
'X-Frequency-Auth': 'ba4cea0a-d4c4-4951-8991-029df07a4242',
},
success: function (data) {
this.setState({ channels: data.channels });
}.bind(this),
});
}
handleRowClick(i) {
this.props.fetchVideos(this.state.channels[i].channel_id);
this.setState({ activeRow: i });
}
eachChannel(item, i) {
return (
<ChannelItem
key={i}
item={item}
handleRowClick={() => this.handleRowClick(i)}
activeRow={this.state.activeRow}
idx={i}
/>
);
}
render() {
return (
<table className="table table-striped table-hover">
<thead>
<tr>
<th>Channel Title</th>
<th># of Videos</th>
<th>Duration</th>
<th>Channel Status</th>
<th></th>
</tr>
</thead>
<tbody>
{
this.state.channels.map(this.eachChannel)
}
</tbody>
</table>
);
}
}
ListChannel.propTypes = {
fetchVideos: React.PropTypes.func,
};
export default ListChannel;
|
docs/src/app/components/pages/components/Tabs/ExampleSwipeable.js
|
frnk94/material-ui
|
import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
// From https://github.com/oliviertassinari/react-swipeable-views
import SwipeableViews from 'react-swipeable-views';
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
slide: {
padding: 10,
},
};
export default class TabsExampleSwipeable extends React.Component {
constructor(props) {
super(props);
this.state = {
slideIndex: 0,
};
}
handleChange = (value) => {
this.setState({
slideIndex: value,
});
};
render() {
return (
<div>
<Tabs
onChange={this.handleChange}
value={this.state.slideIndex}
>
<Tab label="Tab One" value={0} />
<Tab label="Tab Two" value={1} />
<Tab label="Tab Three" value={2} />
</Tabs>
<SwipeableViews
index={this.state.slideIndex}
onChangeIndex={this.handleChange}
>
<div>
<h2 style={styles.headline}>Tabs with slide effect</h2>
Swipe to see the next slide.<br />
</div>
<div style={styles.slide}>
slide n°2
</div>
<div style={styles.slide}>
slide n°3
</div>
</SwipeableViews>
</div>
);
}
}
|
ajax/libs/clappr/0.0.21/clappr.js
|
AlicanC/cdnjs
|
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
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');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],2:[function(require,module,exports){
(function (process,global){
(function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function assertObject(x) {
if (!isObject(x))
throw $TypeError(x + ' is not an Object');
return x;
}
function setupGlobals(global) {
global.Symbol = Symbol;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
assertObject: assertObject,
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
var toObject = $traceurRuntime.toObject;
function spread() {
var rv = [],
k = 0;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = toObject(arguments[i]);
for (var j = 0; j < valueToSpread.length; j++) {
rv[k++] = valueToSpread[j];
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
}
if (superClass === null)
return null;
throw new $TypeError();
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw new Error(("\"" + action + "\" on closed generator"));
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime.assertObject($traceurRuntime),
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
return this.value_ = this.func.call(global);
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils";
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x | 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function toInteger(x) {
x = +x;
if (isNaN(x))
return 0;
if (!isFinite(x) || x === 0)
return x;
return x > 0 ? Math.floor(x) : Math.ceil(x);
}
var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH);
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array";
var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toInteger = $__3.toInteger,
toLength = $__3.toLength,
toObject = $__3.toObject,
isCallable = $__3.isCallable;
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
return {
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__5;
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator";
var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toObject = $__6.toObject,
toUint32 = $__6.toUint32;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__5, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__5), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map";
var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError("Constructor Map requires 'new'");
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError("Map can not be reentrantly initialised");
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
var iter = iterable[Symbol.iterator];
if (iter !== undefined) {
for (var $__8 = iterable[Symbol.iterator](),
$__9; !($__9 = $__8.next()).done; ) {
var $__10 = $traceurRuntime.assertObject($__9.value),
key = $__10[0],
value = $__10[1];
{
this.set(key, value);
}
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
}
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0,
len = this.entries_.length; i < len; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
}
}, {});
return {get Map() {
return Map;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object";
var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")),
toInteger = $__11.toInteger,
toLength = $__11.toLength,
toObject = $__11.toObject,
isCallable = $__11.isCallable;
var $__11 = $traceurRuntime.assertObject($traceurRuntime),
defineProperty = $__11.defineProperty,
getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor,
getOwnPropertyNames = $__11.getOwnPropertyNames,
keys = $__11.keys,
privateNames = $__11.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
}
};
});
System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap";
var $__default = function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
scheduleFlush();
}
};
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0],
arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise";
var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
cast: function(x) {
if (x instanceof this)
return x;
if (isPromise(x)) {
var result = getDeferred(this);
chain(x, result.resolve, result.reject);
return result.promise;
}
return this.resolve(x);
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
return {get Promise() {
return Promise;
}};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String";
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
}
};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills";
var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map;
var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")),
codePointAt = $__14.codePointAt,
contains = $__14.contains,
endsWith = $__14.endsWith,
fromCodePoint = $__14.fromCodePoint,
repeat = $__14.repeat,
raw = $__14.raw,
startsWith = $__14.startsWith;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")),
fill = $__14.fill,
find = $__14.find,
findIndex = $__14.findIndex;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")),
entries = $__14.entries,
keys = $__14.keys,
values = $__14.values;
var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")),
assign = $__14.assign,
is = $__14.is,
mixin = $__14.mixin;
function maybeDefineMethod(object, name, value) {
if (!(name in object)) {
Object.defineProperty(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
function polyfillCollections(global) {
if (!global.Map)
global.Map = Map;
}
function polyfillString(String) {
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
}
function polyfillArray(Array, Symbol) {
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
if (Symbol && Symbol.iterator) {
Object.defineProperty(Array.prototype, Symbol.iterator, {
value: values,
configurable: true,
enumerable: false,
writable: true
});
}
}
function polyfillObject(Object) {
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
function polyfill(global) {
polyfillPromise(global);
polyfillCollections(global);
polyfillString(global.String);
polyfillArray(global.Array, global.Symbol);
polyfillObject(global.Object);
}
polyfill(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfill(global);
};
return {};
});
System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() {
"use strict";
var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import";
var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"));
return {};
});
System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + '');
}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"FWaASH":1}],3:[function(require,module,exports){
/*!
* jQuery JavaScript Library v2.1.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:11Z
*/
(function( global, factory ) {
if ( 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 inherently posses a window with a document
// (such as Node.js), expose a jQuery-making 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 ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var arr = [];
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 support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.1",
// Define a local copy of jQuery
jQuery = function( 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.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
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( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( 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;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// 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 !== "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 = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.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( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( 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( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( 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( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
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( 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() {
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
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(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" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[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
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// 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
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( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"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 = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, 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 );
};
// 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 match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
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 div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = 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 = attrs.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 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// 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 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 !== strundefined && 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,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
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 !== strundefined && 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 http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// 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
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><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
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowclip^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// 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 ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.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 ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[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 does not implement inclusive descendent
// 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( 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 === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( 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 doc;
};
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 &&
( !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.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( 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( 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( 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( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( 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 !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( 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 + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( 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, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
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
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && 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 ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// 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 ) {
(node[ expando ] || (node[ expando ] = {}))[ 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, 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.call( 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 );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
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( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( 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( 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( 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( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( 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,
checkNonElements = base && dir === "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 );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
if ( (oldCache = outerCache[ dir ]) &&
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
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
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.call( 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.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
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( 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;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// 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;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, 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 );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
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 no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && 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,
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
// 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( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.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( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.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( div ) {
return div.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;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
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 ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
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;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( 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 <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// 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;
// 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] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).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.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
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.extend({
dir: function( 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;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( 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( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.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.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( 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( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( 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( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || 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.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], 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" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
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( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
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( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
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,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( 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 ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( 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 ) {
jQuery.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( 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 ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// 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) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(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( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = 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 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, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// 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 ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// 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
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
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 intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( 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( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( 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( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.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 cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// #11217 - WebKit loses check when the name is after the checked attribute
// Support: Windows Web Apps (WWA)
// `name` and `type` need .setAttribute for WWA
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* 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( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.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;
}
// 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 !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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, false );
}
}
}
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( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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 the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( 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(".") >= 0 ) {
// 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 === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.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) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name 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;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.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;
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.namespace_re || event.namespace_re.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( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
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() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
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() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( 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;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
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 < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// 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
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/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;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
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( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
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 this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( 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 this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( 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 === "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 );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
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
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
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;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
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 ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.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 ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
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;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://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;
},
buildFragment: function( elems, context, scripts, selection ) {
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: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
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 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
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;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
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 );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( 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() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( 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() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
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( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( 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 = value.replace( rxhtmlTag, "<$1></$2>" );
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() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
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 this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
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: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ 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 || "" ) &&
!data_priv.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 {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
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: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( 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
// 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() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( 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;
};
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]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 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 offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the 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 ] );
// 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";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( 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: {
"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: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( 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 ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
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 ) {
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( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
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 ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( 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( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.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 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
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( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( 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( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || 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
// so, 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( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( 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: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
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,
// if we don't include width, 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 = ( tweeners[ prop ] || [] ).concat( 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 ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// handle queue: false promises
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() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
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 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
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 ( jQuery.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 wont overwrite keys already present.
// also - reusing 'index' from above 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 = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// 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 ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( 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( 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ 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( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// 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 || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( 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 = data_priv.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( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.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 ];
// Checks the timer has not already been removed
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 );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// 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 = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( 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;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = 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, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
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 ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.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.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( 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;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
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 ( jQuery.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( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-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
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.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( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// 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( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error 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( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// 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( rnotwhite ) || [];
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: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
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: /xml/,
html: /html/,
json: /json/
},
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": jQuery.parseJSON,
// 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( 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( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( 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,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// 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 = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
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() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// 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 || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// 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 ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = 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
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// 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 || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// 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 ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
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 {
// We extract error from statusText
// then normalize statusText and status 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( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( 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;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// 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._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( 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( 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( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
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 ( jQuery.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 === "object" ? 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( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.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( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
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();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
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( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = 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() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( 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, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
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") && 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() {
// Restore preexisting value
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";
}
});
// data: 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 ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( 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 === "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
type: type,
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 );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( 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 ) ) {
options = options.call( elem, i, 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( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
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" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
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 )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// 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 ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we 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 ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return 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, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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 ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
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 ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
},{}],4:[function(require,module,exports){
/**
* Copyright 2012 Craig Campbell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.1.2
* @url craig.is/killing/mice
*/
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
},
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
_KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
_SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
},
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
_SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc'
},
/**
* variable to store the flipped version of _MAP from above
* needed to check if we should use keypress or not when no action
* is specified
*
* @type {Object|undefined}
*/
_REVERSE_MAP,
/**
* a list of all the callbacks setup via Mousetrap.bind()
*
* @type {Object}
*/
_callbacks = {},
/**
* direct map of string combinations to callbacks used for trigger()
*
* @type {Object}
*/
_direct_map = {},
/**
* keeps track of what level each sequence is at since multiple
* sequences can start out with the same sequence
*
* @type {Object}
*/
_sequence_levels = {},
/**
* variable to store the setTimeout call
*
* @type {null|number}
*/
_reset_timer,
/**
* temporary state where we will ignore the next keyup
*
* @type {boolean|string}
*/
_ignore_next_keyup = false,
/**
* are we currently inside of a sequence?
* type of action ("keyup" or "keydown" or "keypress") or false
*
* @type {boolean|string}
*/
_inside_sequence = false;
/**
* loop through the f keys, f1 to f19 and add them to the map
* programatically
*/
for (var i = 1; i < 20; ++i) {
_MAP[111 + i] = 'f' + i;
}
/**
* loop through to map numbers on the numeric keypad
*/
for (i = 0; i <= 9; ++i) {
_MAP[i + 96] = i;
}
/**
* cross browser add event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _addEvent(object, type, callback) {
if (object.addEventListener) {
return object.addEventListener(type, callback, false);
}
object.attachEvent('on' + type, callback);
}
/**
* takes the event and returns the key character
*
* @param {Event} e
* @return {string}
*/
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
return String.fromCharCode(e.which);
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
return String.fromCharCode(e.which).toLowerCase();
}
/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @return {boolean}
*/
function _stop(e) {
var element = e.target || e.srcElement,
tag_name = element.tagName;
// if the element has the class "mousetrap" then no need to stop
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
return false;
}
// stop for input, select, and textarea
return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
}
/**
* checks if two arrays are equal
*
* @param {Array} modifiers1
* @param {Array} modifiers2
* @returns {boolean}
*/
function _modifiersMatch(modifiers1, modifiers2) {
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
}
/**
* resets all sequence counters except for the ones passed in
*
* @param {Object} do_not_reset
* @returns void
*/
function _resetSequences(do_not_reset) {
do_not_reset = do_not_reset || {};
var active_sequences = false,
key;
for (key in _sequence_levels) {
if (do_not_reset[key]) {
active_sequences = true;
continue;
}
_sequence_levels[key] = 0;
}
if (!active_sequences) {
_inside_sequence = false;
}
}
/**
* finds all callbacks that match based on the keycode, modifiers,
* and action
*
* @param {string} character
* @param {Array} modifiers
* @param {string} action
* @param {boolean=} remove - should we remove any matches
* @param {string=} combination
* @returns {Array}
*/
function _getMatches(character, modifiers, action, remove, combination) {
var i,
callback,
matches = [];
// if there are no events related to this keycode
if (!_callbacks[character]) {
return [];
}
// if a modifier key is coming up on its own we should allow it
if (action == 'keyup' && _isModifier(character)) {
modifiers = [character];
}
// loop through all callbacks for the key that was pressed
// and see if any of them match
for (i = 0; i < _callbacks[character].length; ++i) {
callback = _callbacks[character][i];
// if this is a sequence but it is not at the right level
// then move onto the next match
if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
continue;
}
// if the action we are looking for doesn't match the action we got
// then we should keep going
if (action != callback.action) {
continue;
}
// if this is a keypress event that means that we need to only
// look at the character, otherwise check the modifiers as
// well
if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
// remove is used so if you change your mind and call bind a
// second time with a new function the first one is overwritten
if (remove && callback.combo == combination) {
_callbacks[character].splice(i, 1);
}
matches.push(callback);
}
}
return matches;
}
/**
* takes a key event and figures out what the modifiers are
*
* @param {Event} e
* @returns {Array}
*/
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
/**
* actually calls the callback function
*
* if your callback function returns false this will use the jquery
* convention - prevent default and stop propogation on the event
*
* @param {Function} callback
* @param {Event} e
* @returns void
*/
function _fireCallback(callback, e) {
if (callback(e) === false) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
}
/**
* handles a character key event
*
* @param {string} character
* @param {Event} e
* @returns void
*/
function _handleCharacter(character, e) {
// if this event should not happen stop here
if (_stop(e)) {
return;
}
var callbacks = _getMatches(character, _eventModifiers(e), e.type),
i,
do_not_reset = {},
processed_sequence_callback = false;
// loop through matching callbacks for this key event
for (i = 0; i < callbacks.length; ++i) {
// fire for all sequence callbacks
// this is because if for example you have multiple sequences
// bound such as "g i" and "g t" they both need to fire the
// callback for matching g cause otherwise you can only ever
// match the first one
if (callbacks[i].seq) {
processed_sequence_callback = true;
// keep a list of which sequences were matches for later
do_not_reset[callbacks[i].seq] = 1;
_fireCallback(callbacks[i].callback, e);
continue;
}
// if there were no sequence matches but we are still here
// that means this is a regular match so we should fire that
if (!processed_sequence_callback && !_inside_sequence) {
_fireCallback(callbacks[i].callback, e);
}
}
// if you are inside of a sequence and the key you are pressing
// is not a modifier key then we should reset all sequences
// that were not matched by this key event
if (e.type == _inside_sequence && !_isModifier(character)) {
_resetSequences(do_not_reset);
}
}
/**
* handles a keydown event
*
* @param {Event} e
* @returns void
*/
function _handleKey(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
e.which = typeof e.which == "number" ? e.which : e.keyCode;
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
if (e.type == 'keyup' && _ignore_next_keyup == character) {
_ignore_next_keyup = false;
return;
}
_handleCharacter(character, e);
}
/**
* determines if the keycode specified is a modifier key or not
*
* @param {string} key
* @returns {boolean}
*/
function _isModifier(key) {
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
}
/**
* called to set a 1 second timeout on the specified sequence
*
* this is so after each key press in the sequence you have 1 second
* to press the next key before you have to start over
*
* @returns void
*/
function _resetSequenceTimer() {
clearTimeout(_reset_timer);
_reset_timer = setTimeout(_resetSequences, 1000);
}
/**
* reverses the map lookup so that we can look for specific keys
* to see what can and can't use keypress
*
* @return {Object}
*/
function _getReverseMap() {
if (!_REVERSE_MAP) {
_REVERSE_MAP = {};
for (var key in _MAP) {
// pull out the numeric keypad from here cause keypress should
// be able to detect the keys from the character
if (key > 95 && key < 112) {
continue;
}
if (_MAP.hasOwnProperty(key)) {
_REVERSE_MAP[_MAP[key]] = key;
}
}
}
return _REVERSE_MAP;
}
/**
* picks the best action based on the key combination
*
* @param {string} key - character for key
* @param {Array} modifiers
* @param {string=} action passed in
*/
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
/**
* binds a key sequence to an event
*
* @param {string} combo - combo specified in bind call
* @param {Array} keys
* @param {Function} callback
* @param {string=} action
* @returns void
*/
function _bindSequence(combo, keys, callback, action) {
// start off by adding a sequence level record for this combination
// and setting the level to 0
_sequence_levels[combo] = 0;
// if there is no action pick the best one for the first key
// in the sequence
if (!action) {
action = _pickBestAction(keys[0], []);
}
/**
* callback to increase the sequence level for this sequence and reset
* all other sequences that were active
*
* @param {Event} e
* @returns void
*/
var _increaseSequence = function(e) {
_inside_sequence = action;
++_sequence_levels[combo];
_resetSequenceTimer();
},
/**
* wraps the specified callback inside of another function in order
* to reset all sequence counters as soon as this sequence is done
*
* @param {Event} e
* @returns void
*/
_callbackAndReset = function(e) {
_fireCallback(callback, e);
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
_ignore_next_keyup = _characterFromEvent(e);
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(_resetSequences, 10);
},
i;
// loop through keys one at a time and bind the appropriate callback
// function. for any key leading up to the final one it should
// increase the sequence. after the final, it should reset all sequences
for (i = 0; i < keys.length; ++i) {
_bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
}
}
/**
* binds a single keyboard combination
*
* @param {string} combination
* @param {Function} callback
* @param {string=} action
* @param {string=} sequence_name - name of sequence if part of sequence
* @param {number=} level - what part of the sequence the command is
* @returns void
*/
function _bindSingle(combination, callback, action, sequence_name, level) {
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' '),
i,
key,
keys,
modifiers = [];
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
return _bindSequence(combination, sequence, callback, action);
}
// take the keys from this pattern and figure out what the actual
// pattern is all about
keys = combination === '+' ? ['+'] : combination.split('+');
for (i = 0; i < keys.length; ++i) {
key = keys[i];
// normalize key names
if (_SPECIAL_ALIASES[key]) {
key = _SPECIAL_ALIASES[key];
}
// if this is not a keypress event then we should
// be smart about using shift keys
// this will only work for US keyboards however
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
key = _SHIFT_MAP[key];
modifiers.push('shift');
}
// if this key is a modifier then add it to the list of modifiers
if (_isModifier(key)) {
modifiers.push(key);
}
}
// depending on what the key combination is
// we will try to pick the best event for it
action = _pickBestAction(key, modifiers, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
if (!_callbacks[key]) {
_callbacks[key] = [];
}
// remove an existing match if there is one
_getMatches(key, modifiers, action, !sequence_name, combination);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
_callbacks[key][sequence_name ? 'unshift' : 'push']({
callback: callback,
modifiers: modifiers,
action: action,
seq: sequence_name,
level: level,
combo: combination
});
}
/**
* binds multiple combinations to the same callback
*
* @param {Array} combinations
* @param {Function} callback
* @param {string|undefined} action
* @returns void
*/
function _bindMultiple(combinations, callback, action) {
for (var i = 0; i < combinations.length; ++i) {
_bindSingle(combinations[i], callback, action);
}
}
// start!
_addEvent(document, 'keypress', _handleKey);
_addEvent(document, 'keydown', _handleKey);
_addEvent(document, 'keyup', _handleKey);
var mousetrap = {
/**
* binds an event to mousetrap
*
* can be a single key, a combination of keys separated with +,
* a comma separated list of keys, an array of keys, or
* a sequence of keys separated by spaces
*
* be sure to list the modifier keys first to make sure that the
* correct key ends up getting bound (the last key in the pattern)
*
* @param {string|Array} keys
* @param {Function} callback
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
* @returns void
*/
bind: function(keys, callback, action) {
_bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
_direct_map[keys + ':' + action] = callback;
return this;
},
/**
* unbinds an event to mousetrap
*
* the unbinding sets the callback function of the specified key combo
* to an empty function and deletes the corresponding key in the
* _direct_map dict.
*
* the keycombo+action has to be exactly the same as
* it was defined in the bind method
*
* TODO: actually remove this from the _callbacks dictionary instead
* of binding an empty function
*
* @param {string|Array} keys
* @param {string} action
* @returns void
*/
unbind: function(keys, action) {
if (_direct_map[keys + ':' + action]) {
delete _direct_map[keys + ':' + action];
this.bind(keys, function() {}, action);
}
return this;
},
/**
* triggers an event that has already been bound
*
* @param {string} keys
* @param {string=} action
* @returns void
*/
trigger: function(keys, action) {
_direct_map[keys + ':' + action]();
return this;
},
/**
* resets the library back to its initial state. this is useful
* if you want to clear out the current keyboard shortcuts and bind
* new ones - for example if you switch to another page
*
* @returns void
*/
reset: function() {
_callbacks = {};
_direct_map = {};
return this;
}
};
module.exports = mousetrap;
},{}],5:[function(require,module,exports){
(function( factory ) {
if (typeof define !== 'undefined' && define.amd) {
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
var $ = require('jquery');
module.exports = factory( $ );
} else {
window.scrollMonitor = factory( jQuery );
}
})(function( $ ) {
var exports = {};
var $window = $(window);
var $document = $(document);
var watchers = [];
var VISIBILITYCHANGE = 'visibilityChange';
var ENTERVIEWPORT = 'enterViewport';
var FULLYENTERVIEWPORT = 'fullyEnterViewport';
var EXITVIEWPORT = 'exitViewport';
var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';
var LOCATIONCHANGE = 'locationChange';
var STATECHANGE = 'stateChange';
var eventTypes = [
VISIBILITYCHANGE,
ENTERVIEWPORT,
FULLYENTERVIEWPORT,
EXITVIEWPORT,
PARTIALLYEXITVIEWPORT,
LOCATIONCHANGE,
STATECHANGE
];
var defaultOffsets = {top: 0, bottom: 0};
exports.viewportTop;
exports.viewportBottom;
exports.documentHeight;
exports.viewportHeight = windowHeight();
var previousDocumentHeight;
var latestEvent;
function windowHeight() {
return window.innerHeight || document.documentElement.clientHeight;
}
var calculateViewportI;
function calculateViewport() {
exports.viewportTop = $window.scrollTop();
exports.viewportBottom = exports.viewportTop + exports.viewportHeight;
exports.documentHeight = $document.height();
if (exports.documentHeight !== previousDocumentHeight) {
calculateViewportI = watchers.length;
while( calculateViewportI-- ) {
watchers[calculateViewportI].recalculateLocation();
}
previousDocumentHeight = exports.documentHeight;
}
}
function recalculateWatchLocationsAndTrigger() {
exports.viewportHeight = windowHeight();
calculateViewport();
updateAndTriggerWatchers();
}
var recalculateAndTriggerTimer;
function debouncedRecalcuateAndTrigger() {
clearTimeout(recalculateAndTriggerTimer);
recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );
}
var updateAndTriggerWatchersI;
function updateAndTriggerWatchers() {
// update all watchers then trigger the events so one can rely on another being up to date.
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].update();
}
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].triggerCallbacks();
}
}
function ElementWatcher( watchItem, offsets ) {
var self = this;
this.watchItem = watchItem;
if (!offsets) {
this.offsets = defaultOffsets;
} else if (offsets === +offsets) {
this.offsets = {top: offsets, bottom: offsets};
} else {
this.offsets = $.extend({}, defaultOffsets, offsets);
}
this.callbacks = {}; // {callback: function, isOne: true }
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]] = [];
}
this.locked = false;
var wasInViewport;
var wasFullyInViewport;
var wasAboveViewport;
var wasBelowViewport;
var listenerToTriggerListI;
var listener;
function triggerCallbackArray( listeners ) {
if (listeners.length === 0) {
return;
}
listenerToTriggerListI = listeners.length;
while( listenerToTriggerListI-- ) {
listener = listeners[listenerToTriggerListI];
listener.callback.call( self, latestEvent );
if (listener.isOne) {
listeners.splice(listenerToTriggerListI, 1);
}
}
}
this.triggerCallbacks = function triggerCallbacks() {
if (this.isInViewport && !wasInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
}
if (this.isFullyInViewport && !wasFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
}
if (this.isAboveViewport !== wasAboveViewport &&
this.isBelowViewport !== wasBelowViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
// if you skip completely past this element
if (!wasFullyInViewport && !this.isFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!wasInViewport && !this.isInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
}
if (!this.isFullyInViewport && wasFullyInViewport) {
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!this.isInViewport && wasInViewport) {
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
if (this.isInViewport !== wasInViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
}
switch( true ) {
case wasInViewport !== this.isInViewport:
case wasFullyInViewport !== this.isFullyInViewport:
case wasAboveViewport !== this.isAboveViewport:
case wasBelowViewport !== this.isBelowViewport:
triggerCallbackArray( this.callbacks[STATECHANGE] );
}
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
};
this.recalculateLocation = function() {
if (this.locked) {
return;
}
var previousTop = this.top;
var previousBottom = this.bottom;
if (this.watchItem.nodeName) { // a dom element
var cachedDisplay = this.watchItem.style.display;
if (cachedDisplay === 'none') {
this.watchItem.style.display = '';
}
var elementLocation = $(this.watchItem).offset();
this.top = elementLocation.top;
this.bottom = elementLocation.top + this.watchItem.offsetHeight;
if (cachedDisplay === 'none') {
this.watchItem.style.display = cachedDisplay;
}
} else if (this.watchItem === +this.watchItem) { // number
if (this.watchItem > 0) {
this.top = this.bottom = this.watchItem;
} else {
this.top = this.bottom = exports.documentHeight - this.watchItem;
}
} else { // an object with a top and bottom property
this.top = this.watchItem.top;
this.bottom = this.watchItem.bottom;
}
this.top -= this.offsets.top;
this.bottom += this.offsets.bottom;
this.height = this.bottom - this.top;
if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {
triggerCallbackArray( this.callbacks[LOCATIONCHANGE] );
}
};
this.recalculateLocation();
this.update();
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
}
ElementWatcher.prototype = {
on: function( event, callback, isOne ) {
// trigger the event if it applies to the element right now.
switch( true ) {
case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:
case event === ENTERVIEWPORT && this.isInViewport:
case event === FULLYENTERVIEWPORT && this.isFullyInViewport:
case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:
case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:
callback();
if (isOne) {
return;
}
}
if (this.callbacks[event]) {
this.callbacks[event].push({callback: callback, isOne: isOne});
} else {
throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
off: function( event, callback ) {
if (this.callbacks[event]) {
for (var i = 0, item; item = this.callbacks[event][i]; i++) {
if (item.callback === callback) {
this.callbacks[event].splice(i, 1);
break;
}
}
} else {
throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
one: function( event, callback ) {
this.on( event, callback, true);
},
recalculateSize: function() {
this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;
this.bottom = this.top + this.height;
},
update: function() {
this.isAboveViewport = this.top < exports.viewportTop;
this.isBelowViewport = this.bottom > exports.viewportBottom;
this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);
this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||
(this.isAboveViewport && this.isBelowViewport);
},
destroy: function() {
var index = watchers.indexOf(this),
self = this;
watchers.splice(index, 1);
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]].length = 0;
}
},
// prevent recalculating the element location
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
}
};
var eventHandlerFactory = function (type) {
return function( callback, isOne ) {
this.on.call(this, type, callback, isOne);
};
};
for (var i = 0, j = eventTypes.length; i < j; i++) {
var type = eventTypes[i];
ElementWatcher.prototype[type] = eventHandlerFactory(type);
}
try {
calculateViewport();
} catch (e) {
$(calculateViewport);
}
function scrollMonitorListener(event) {
latestEvent = event;
calculateViewport();
updateAndTriggerWatchers();
}
$window.on('scroll', scrollMonitorListener);
$window.on('resize', debouncedRecalcuateAndTrigger);
exports.beget = exports.create = function( element, offsets ) {
if (typeof element === 'string') {
element = $(element)[0];
}
if (element instanceof $) {
element = element[0];
}
var watcher = new ElementWatcher( element, offsets );
watchers.push(watcher);
watcher.update();
return watcher;
};
exports.update = function() {
latestEvent = null;
calculateViewport();
updateAndTriggerWatchers();
};
exports.recalculateLocations = function() {
exports.documentHeight = 0;
exports.update();
};
return exports;
});
},{"jquery":3}],6:[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return obj.length === +obj.length ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(slice.call(arguments, 1), true, true, []);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// 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.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
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() {
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;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],"base_object":[function(require,module,exports){
module.exports=require('2HNVgz');
},{}],"2HNVgz":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = require('./utils').extend;
var Events = require('./events');
var pluginOptions = ['container'];
var BaseObject = function BaseObject(options) {
this.uniqueId = _.uniqueId('o');
options || (options = {});
_.extend(this, _.pick(options, pluginOptions));
};
($traceurRuntime.createClass)(BaseObject, {}, {}, Events);
BaseObject.extend = extend;
module.exports = BaseObject;
},{"./events":11,"./utils":23,"underscore":6}],"core_plugin":[function(require,module,exports){
module.exports=require('it+usN');
},{}],"it+usN":[function(require,module,exports){
"use strict";
var BaseObject = require('./base_object');
var CorePlugin = function CorePlugin(core) {
$traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]);
this.core = core;
};
var $CorePlugin = CorePlugin;
($traceurRuntime.createClass)(CorePlugin, {getExternalInterface: function() {
return {};
}}, {}, BaseObject);
module.exports = CorePlugin;
},{"./base_object":"2HNVgz"}],11:[function(require,module,exports){
(function (global){
"use strict";
var _ = require('underscore');
var Log = require('../plugins/log');
var slice = Array.prototype.slice;
var Events = function Events() {};
($traceurRuntime.createClass)(Events, {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain,
ev,
events,
names,
i,
l,
j,
k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
events = this._events[name];
if (events) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length)
delete this._events[name];
}
}
return this;
},
trigger: function(name) {
var klass = arguments[arguments.length - 1];
if (global.DEBUG) {
if (Log.BLACKLIST.indexOf(name) < 0)
Log.info(klass, 'event ' + name + ' triggered');
}
if (!this._events)
return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args))
return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events)
triggerEvents(events, args);
if (allEvents)
triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo)
return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object')
callback = this;
if (obj)
(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events))
delete this._listeningTo[id];
}
return this;
}
}, {});
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name)
return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0,
l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev,
i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)
(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
_.each(listenMethods, function(implementation, method) {
Events.prototype[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object')
callback = this;
obj[implementation](name, callback, this);
return this;
};
});
module.exports = Events;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../plugins/log":58,"underscore":6}],12:[function(require,module,exports){
"use strict";
var _ = require('underscore');
module.exports = {
'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls> <% var renderBar = function(name) { %> <div class="bar-container" data-<%= name %>> <div class="bar-background" data-<%= name %>> <div class="bar-fill-1" data-<%= name %>></div> <div class="bar-fill-2" data-<%= name %>></div> <div class="bar-hover" data-<%= name %>></div> </div> <div class="bar-scrubber" data-<%= name %>> <div class="bar-scrubber-icon" data-<%= name %>></div> </div> </div> <% }; %> <% var renderDrawer = function(name, renderContent) { %> <div class="drawer-container" data-<%= name %>> <div class="drawer-icon-container" data-<%= name %>> <div class="drawer-icon media-control-icon" data-<%= name %>></div> <span class="drawer-text" data-<%= name %>></span> </div> <% renderContent(name); %> </div> <% }; %> <% var renderIndicator = function(name) { %> <div class="media-control-indicator" data-<%= name %>></div> <% }; %> <% var renderButton = function(name) { %> <button class="media-control-button media-control-icon" data-<%= name %>></button> <% }; %> <% var render = function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.default && settings.default.length) { %> <div class="media-control-center-panel" data-media-control> <% render(settings.default); %> </div> <% } %> <% if (settings.left && settings.left.length) { %> <div class="media-control-left-panel" data-media-control> <% render(settings.left); %> </div> <% } %> <% if (settings.right && settings.right.length) { %> <div class="media-control-right-panel" data-media-control> <% render(settings.right); %> </div> <% } %></div>'),
'seek_time': _.template('<span data-seek-time><%= time %></span>'),
'flash': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'),
'hls': _.template(' <param name="movie" value="<%= swfPath %>?inline=1"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'),
'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'),
'background_button': _.template('<div class="playpause-button-wrapper" data-background-button> <span class="playpause-icon" data-background-button></span></div>'),
'poster': _.template('<div class="play-wrapper" data-poster> <span class="poster-icon play" data-poster /></div>'),
'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'),
'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'),
CSS: {
'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}',
'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}',
'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;border-radius:0;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto;max-width:100%;min-width:60%;height:40px;z-index:9999;-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:150px;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:all,.6s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.6s,ease-out;-o-transition:all,.6s,ease-out;transition:all,.6s,ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.5) 0 0 15px;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control].media-control-hide{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-background[data-background],.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:relative;top:10%;height:80%;vertical-align:middle}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:10px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.3)}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin-right:3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:none;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5)}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{display:block}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all,.1s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.1s,ease-out;-o-transition:all,.1s,ease-out;transition:all,.1s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all,.2s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.2s,ease-out;-o-transition:all,.2s,ease-out;transition:all,.2s,ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}',
'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:all,.2s,ease-in;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.2s,ease-in;-o-transition:all,.2s,ease-in;transition:all,.2s,ease-in}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',
'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',
'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',
'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',
'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);-webkit-transition:all,.4s,ease-out;-webkit-transition-delay:0s,0s,0s;-moz-transition:all,.4s,ease-out;-o-transition:all,.4s,ease-out;transition:all,.4s,ease-out}.background-button[data-background-button].hide[data-background-button]{opacity:0}.background-button[data-background-button] .playpause-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:20%;top:45%;margin-top:-5%;text-align:center}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]{font-family:Player;cursor:pointer;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;font-size:90px;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button]:hover{text-shadow:rgba(255,255,255,.5) 0 0 15px}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .playpause-button-wrapper[data-background-button] .playpause-icon[data-background-button].paused:before{content:"\\e001"}',
'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;overflow:hidden;width:100%;height:20%;line-height:100%;font-size:20%;top:50%;margin-top:-5%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}',
'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',
'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'
}
};
},{"underscore":6}],"VbgHr3":[function(require,module,exports){
"use strict";
var UIObject = require('../base/ui_object');
var Playback = function Playback(options) {
$traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]);
this.settings = {};
};
var $Playback = Playback;
($traceurRuntime.createClass)(Playback, {
play: function() {},
pause: function() {},
stop: function() {},
seek: function(time) {},
getDuration: function() {
return 0;
},
isPlaying: function() {
return false;
},
getPlaybackType: function() {
return 'no_op';
},
isHighDefinitionInUse: function() {
return false;
},
destroy: function() {
this.$el.remove();
}
}, {}, UIObject);
Playback.canPlay = (function(source) {
return false;
});
module.exports = Playback;
},{"../base/ui_object":"8lqCAT"}],"playback":[function(require,module,exports){
module.exports=require('VbgHr3');
},{}],15:[function(require,module,exports){
"use strict";
var PluginMixin = {
initialize: function() {
this.bindEvents();
},
enable: function() {
this.bindEvents();
},
disable: function() {
this.stopListening();
}
};
module.exports = PluginMixin;
},{}],16:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var JST = require('./jst');
var Styler = {getStyleFor: function(name, options) {
options = options || {};
return $('<style></style>').html(_.template(JST.CSS[name])(options));
}};
module.exports = Styler;
},{"./jst":12,"jquery":3,"underscore":6}],"ui_core_plugin":[function(require,module,exports){
module.exports=require('gNZMEo');
},{}],"gNZMEo":[function(require,module,exports){
"use strict";
var UIObject = require('./ui_object');
var UICorePlugin = function UICorePlugin(core) {
$traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]);
this.core = core;
this.render();
};
var $UICorePlugin = UICorePlugin;
($traceurRuntime.createClass)(UICorePlugin, {
getExternalInterface: function() {
return {};
},
render: function() {
this.$el.html(this.template());
this.$el.append(this.styler.getStyleFor(this.name));
this.core.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = UICorePlugin;
},{"./ui_object":"8lqCAT"}],"ui_object":[function(require,module,exports){
module.exports=require('8lqCAT');
},{}],"8lqCAT":[function(require,module,exports){
"use strict";
var $ = require('jquery');
var _ = require('underscore');
var extend = require('./utils').extend;
var BaseObject = require('./base_object');
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var UIObject = function UIObject(options) {
$traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]);
this.cid = _.uniqueId('c');
this._ensureElement();
this.delegateEvents();
};
var $UIObject = UIObject;
($traceurRuntime.createClass)(UIObject, {
get tagName() {
return 'div';
},
$: function(selector) {
return this.$el.find(selector);
},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
setElement: function(element, delegate) {
if (this.$el)
this.undelegateEvents();
this.$el = element instanceof $ ? element : $(element);
this.el = this.$el[0];
if (delegate !== false)
this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events'))))
return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method))
method = this[events[key]];
if (!method)
continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id)
attrs.id = _.result(this, 'id');
if (this.className)
attrs['class'] = _.result(this, 'className');
var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
}, {}, BaseObject);
UIObject.extend = extend;
module.exports = UIObject;
},{"./base_object":"2HNVgz","./utils":23,"jquery":3,"underscore":6}],"Z7u8cr":[function(require,module,exports){
"use strict";
var PluginMixin = require('./plugin_mixin');
var UIObject = require('./ui_object');
var extend = require('./utils').extend;
var _ = require('underscore');
var UIPlugin = function UIPlugin() {
$traceurRuntime.defaultSuperCall(this, $UIPlugin.prototype, arguments);
};
var $UIPlugin = UIPlugin;
($traceurRuntime.createClass)(UIPlugin, {
get type() {
return 'ui';
},
enable: function() {
$UIPlugin.super('enable').call(this);
this.$el.show();
},
disable: function() {
$UIPlugin.super('disable').call(this);
this.$el.hide();
},
bindEvents: function() {}
}, {}, UIObject);
_.extend(UIPlugin.prototype, PluginMixin);
UIPlugin.extend = extend;
module.exports = UIPlugin;
},{"./plugin_mixin":15,"./ui_object":"8lqCAT","./utils":23,"underscore":6}],"ui_plugin":[function(require,module,exports){
module.exports=require('Z7u8cr');
},{}],23:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps)
_.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
child.super = function(name) {
return parent.prototype[name];
};
child.prototype.getClass = function() {
return child;
};
return child;
};
var zeroPad = function(number, size) {
return (new Array(size + 1 - number.toString().length)).join('0') + number;
};
var formatTime = function(time) {
time = time * 1000;
time = parseInt(time / 1000);
var seconds = time % 60;
time = parseInt(time / 60);
var minutes = time % 60;
time = parseInt(time / 60);
var hours = time % 24;
var out = "";
if (hours && hours > 0)
out += ("0" + hours).slice(-2) + ":";
out += ("0" + minutes).slice(-2) + ":";
out += ("0" + seconds).slice(-2);
return out.trim();
};
var Fullscreen = {
isFullscreen: function() {
return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement;
},
requestFullscreen: function(el) {
if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
},
cancelFullscreen: function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
};
var HEX_TAB = "0123456789abcdef";
var B64_TAB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
var b64pad = "";
var rstr2b64 = function(input) {
var output = "";
var len = input.length;
for (var i = 0; i < len; i += 3) {
var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > input.length * 8)
output += b64pad;
else
output += B64_TAB.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
}
}
return output;
};
var rstr2hex = function(input) {
var output = "";
for (var i = 0; i < input.length; i++) {
var x = input.charCodeAt(i);
output += HEX_TAB.charAt((x >>> 4) & 0x0F) + HEX_TAB.charAt(x & 0x0F);
}
return output;
};
var getHostname = function() {
return location.hostname;
};
var Ajax = {
jsonp: function(settings) {
var defer = new $.Deferred();
settings.callbackName = settings.callbackName || "json_callback";
settings.timeout = settings.timeout || 15000;
window[settings.callbackName] = function(data) {
if (!Ajax.isErrorObject(data)) {
defer.resolve(data);
} else {
defer.reject(data);
}
};
var head = $("head")[0];
var script = document.createElement("script");
script.setAttribute("src", settings.url);
script.setAttribute("async", "async");
script.onload = script.onreadystatechange = function(eventLoad) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (settings.timeoutId) {
window.clearTimeout(settings.timeoutId);
}
script.onload = script.onreadystatechange = null;
if (head && script.parentNode)
head.removeChild(script);
script = undefined;
}
};
head.insertBefore(script, head.firstChild);
if (settings.error) {
settings.timeoutId = window.setTimeout(settings.error, settings.timeout);
}
return defer.promise();
},
isErrorObject: function(data) {
return data && data.http_status_code && data.http_status_code != 200;
}
};
module.exports = {
extend: extend,
zeroPad: zeroPad,
formatTime: formatTime,
Fullscreen: Fullscreen,
Ajax: Ajax,
rstr2b64: rstr2b64,
rstr2hex: rstr2hex,
getHostname: getHostname
};
},{"jquery":3,"underscore":6}],"195Wj5":[function(require,module,exports){
"use strict";
var Browser = function Browser() {};
($traceurRuntime.createClass)(Browser, {}, {});
Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);
Browser.isChrome = !!(navigator.userAgent.match(/chrome/i));
Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i));
Browser.isLegacyIE = !!(window.ActiveXObject);
Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i));
Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));
Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));
module.exports = Browser;
},{}],"browser":[function(require,module,exports){
module.exports=require('195Wj5');
},{}],26:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var _ = require('underscore');
var Container = function Container(options) {
$traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]);
this.playback = options.playback;
this.settings = this.playback.settings;
this.isReady = false;
this.mediaControlDisabled = false;
this.plugins = [this.playback];
this.bindEvents();
};
var $Container = Container;
($traceurRuntime.createClass)(Container, {
get name() {
return 'Container';
},
get attributes() {
return {'data-container': ''};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.playback, 'playback:progress', this.progress);
this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated);
this.listenTo(this.playback, 'playback:ready', this.ready);
this.listenTo(this.playback, 'playback:buffering', this.buffering);
this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull);
this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate);
this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata);
this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.playback, 'playback:playbackstate', this.playbackStateChanged);
this.listenTo(this.playback, 'playback:dvr', this.playbackDvrStateChanged);
this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl);
this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl);
this.listenTo(this.playback, 'playback:ended', this.ended);
this.listenTo(this.playback, 'playback:play', this.playing);
},
with: function(klass) {
_.extend(this, klass);
return this;
},
playbackStateChanged: function() {
this.trigger('container:playbackstate');
},
playbackDvrStateChanged: function(dvrInUse) {
this.settings = this.playback.settings;
this.trigger('container:dvr', dvrInUse);
},
statsAdd: function(metric) {
this.trigger('container:stats:add', metric);
},
statsReport: function(metrics) {
this.trigger('container:stats:report', metrics);
},
getPlaybackType: function() {
return this.playback.getPlaybackType();
},
destroy: function() {
this.trigger('container:destroyed', this, this.name);
this.playback.destroy();
this.$el.remove();
},
setStyle: function(style) {
this.$el.css(style);
},
animate: function(style, duration) {
return this.$el.animate(style, duration).promise();
},
ready: function() {
this.isReady = true;
this.trigger('container:ready', this.name);
},
isPlaying: function() {
return this.playback.isPlaying();
},
getDuration: function() {
return this.playback.getDuration();
},
error: function(errorObj) {
this.trigger('container:error', errorObj, this.name);
},
loadedMetadata: function(duration) {
this.trigger('container:loadedmetadata', duration);
},
timeUpdated: function(position, duration) {
this.trigger('container:timeupdate', position, duration, this.name);
},
progress: function(startPosition, endPosition, duration) {
this.trigger('container:progress', startPosition, endPosition, duration, this.name);
},
playing: function() {
this.trigger('container:play', this.name);
},
play: function() {
this.playback.play();
},
stop: function() {
this.trigger('container:stop', this.name);
this.playback.stop();
},
pause: function() {
this.trigger('container:pause', this.name);
this.playback.pause();
},
ended: function() {
this.trigger('container:ended', this, this.name);
},
clicked: function() {
this.trigger('container:click', this, this.name);
},
setCurrentTime: function(time) {
this.trigger('container:seek', time, this.name);
this.playback.seek(time);
},
setVolume: function(value) {
this.trigger('container:volume', value, this.name);
this.playback.volume(value);
},
requestFullscreen: function() {
this.trigger('container:fullscreen', this.name);
},
buffering: function() {
this.trigger('container:state:buffering', this.name);
},
bufferfull: function() {
this.trigger('container:state:bufferfull', this.name);
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find(function(plugin) {
return plugin.name === name;
});
},
settingsUpdate: function() {
this.settings = this.playback.settings;
this.trigger('container:settingsupdate');
},
highDefinitionUpdate: function() {
this.trigger('container:highdefinitionupdate');
},
isHighDefinitionInUse: function() {
return this.playback.isHighDefinitionInUse();
},
disableMediaControl: function() {
this.mediaControlDisabled = true;
this.trigger('container:mediacontrol:disable');
},
enableMediaControl: function() {
this.mediaControlDisabled = false;
this.trigger('container:mediacontrol:enable');
},
render: function() {
var style = Styler.getStyleFor('container');
this.$el.append(style);
this.$el.append(this.playback.render().el);
return this;
}
}, {}, UIObject);
module.exports = Container;
},{"../../base/styler":16,"../../base/ui_object":"8lqCAT","underscore":6}],27:[function(require,module,exports){
"use strict";
module.exports = require('./container');
},{"./container":26}],28:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('../../base/base_object');
var Container = require('../container');
var $ = require('jquery');
var ContainerFactory = function ContainerFactory(options, loader) {
$traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]);
this.options = options;
this.loader = loader;
};
var $ContainerFactory = ContainerFactory;
($traceurRuntime.createClass)(ContainerFactory, {
createContainers: function() {
return $.Deferred(function(promise) {
promise.resolve(_.map(this.options.sources, function(source) {
return this.createContainer(source);
}, this));
}.bind(this));
},
findPlaybackPlugin: function(source) {
return _.find(this.loader.playbackPlugins, (function(p) {
return p.canPlay(source.toString());
}), this);
},
createContainer: function(source) {
var playbackPlugin = this.findPlaybackPlugin(source);
var options = _.extend({}, this.options, {
src: source,
autoPlay: !!this.options.autoPlay
});
var playback = new playbackPlugin(options);
var container = new Container({playback: playback});
var defer = $.Deferred();
defer.promise(container);
this.addContainerPlugins(container, source);
this.listenToOnce(container, 'container:ready', (function() {
return defer.resolve(container);
}));
return container;
},
addContainerPlugins: function(container, source) {
_.each(this.loader.containerPlugins, function(Plugin) {
var options = _.extend(this.options, {
container: container,
src: source
});
container.addPlugin(new Plugin(options));
}, this);
}
}, {}, BaseObject);
module.exports = ContainerFactory;
},{"../../base/base_object":"2HNVgz","../container":27,"jquery":3,"underscore":6}],29:[function(require,module,exports){
"use strict";
module.exports = require('./container_factory');
},{"./container_factory":28}],30:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var UIObject = require('../../base/ui_object');
var ContainerFactory = require('../container_factory');
var Fullscreen = require('../../base/utils').Fullscreen;
var Styler = require('../../base/styler');
var MediaControl = require('../media_control');
var PlayerInfo = require('../player_info');
var Mediator = require('../mediator');
var Core = function Core(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]);
this.playerInfo = PlayerInfo.getInstance();
this.playerInfo.options = options;
this.options = options;
this.plugins = [];
this.containers = [];
this.createContainers(options);
this.updateSize();
document.addEventListener('fullscreenchange', (function() {
return $__0.exit();
}));
document.addEventListener('MSFullscreenChange', (function() {
return $__0.exit();
}));
document.addEventListener('mozfullscreenchange', (function() {
return $__0.exit();
}));
$(window).resize((function() {
return $__0.updateSize();
}));
};
var $Core = Core;
($traceurRuntime.createClass)(Core, {
get events() {
return {
'webkitfullscreenchange': 'exit',
'mousemove': 'showMediaControl',
'mouseleave': 'hideMediaControl'
};
},
get attributes() {
return {'data-player': ''};
},
createContainers: function(options) {
var $__0 = this;
this.defer = $.Deferred();
this.defer.promise(this);
this.containerFactory = new ContainerFactory(options, options.loader);
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
})).then((function(containers) {
return $__0.resolveOnContainersReady(containers);
}));
},
updateSize: function() {
if (Fullscreen.isFullscreen()) {
this.$el.addClass('fullscreen');
this.$el.removeAttr('style');
this.playerInfo.currentSize = {
width: window.innerWidth,
height: window.innerHeight
};
} else {
var needStretch = !!this.options.stretchWidth && !!this.options.stretchHeight;
var width,
height;
if (needStretch && this.options.stretchWidth <= window.innerWidth && this.options.stretchHeight <= (window.innerHeight * 0.73)) {
width = this.options.stretchWidth;
height = this.options.stretchHeight;
} else {
width = this.options.width;
height = this.options.height;
}
this.$el.css({width: width});
this.$el.css({height: height});
this.$el.removeClass('fullscreen');
this.playerInfo.currentSize = {
width: width,
height: height
};
}
Mediator.trigger('player:resize');
},
resolveOnContainersReady: function(containers) {
var $__0 = this;
$.when.apply($, containers).done((function() {
return $__0.defer.resolve($__0);
}));
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find((function(plugin) {
return plugin.name === name;
}));
},
load: function(sources) {
var $__0 = this;
sources = _.isString(sources) ? [sources] : sources;
_(this.containers).each((function(container) {
return container.destroy();
}));
this.containerFactory.options = _(this.options).extend({sources: sources});
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
}));
},
destroy: function() {
_(this.containers).each((function(container) {
return container.destroy();
}));
this.$el.remove();
},
exit: function() {
this.updateSize();
this.mediaControl.show();
},
setMediaControlContainer: function(container) {
this.mediaControl.setContainer(container);
this.mediaControl.render();
},
disableMediaControl: function() {
this.mediaControl.disable();
this.$el.removeClass('nocursor');
},
enableMediaControl: function() {
this.mediaControl.enable();
},
removeContainer: function(container) {
this.stopListening(container);
this.containers = _.without(this.containers, container);
},
appendContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.el.appendChild(container.render().el);
this.containers.push(container);
},
prependContainer: function(container) {
this.listenTo(container, 'container:destroyed', this.removeContainer);
this.$el.append(container.render().el);
this.containers.unshift(container);
},
setupContainers: function(containers) {
_.map(containers, this.appendContainer, this);
this.setupMediaControl(this.getCurrentContainer());
this.render();
this.$el.appendTo(this.options.parentElement);
return containers;
},
createContainer: function(source) {
var container = this.containerFactory.createContainer(source);
this.appendContainer(container);
return container;
},
setupMediaControl: function(container) {
if (this.mediaControl) {
this.mediaControl.setContainer(container);
} else {
this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));
this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen);
this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true));
this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false));
}
},
createMediaControl: function(options) {
if (options.mediacontrol && options.mediacontrol.external) {
return new options.mediacontrol.external(options);
} else {
return new MediaControl(options);
}
},
getCurrentContainer: function() {
return this.containers[0];
},
toggleFullscreen: function() {
if (!Fullscreen.isFullscreen()) {
Fullscreen.requestFullscreen(this.el);
this.$el.addClass('fullscreen');
} else {
Fullscreen.cancelFullscreen();
this.$el.removeClass('fullscreen nocursor');
}
this.mediaControl.show();
},
showMediaControl: function(event) {
this.mediaControl.show(event);
},
hideMediaControl: function(event) {
this.mediaControl.hide(event);
},
onMediaControlShow: function(showing) {
if (showing)
this.$el.removeClass('nocursor');
else if (Fullscreen.isFullscreen())
this.$el.addClass('nocursor');
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor('core');
this.$el.append(style);
this.$el.append(this.mediaControl.render().el);
this.$el.ready((function() {
$__0.options.width = $__0.options.width || $__0.$el.width();
$__0.options.height = $__0.options.height || $__0.$el.height();
$__0.updateSize();
}));
return this;
}
}, {}, UIObject);
module.exports = Core;
},{"../../base/styler":16,"../../base/ui_object":"8lqCAT","../../base/utils":23,"../container_factory":29,"../media_control":"A8Uh+k","../mediator":"veeMMc","../player_info":"Pce0iO","jquery":3,"underscore":6}],31:[function(require,module,exports){
"use strict";
module.exports = require('./core');
},{"./core":30}],32:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('../../base/base_object');
var Core = require('../core');
var CoreFactory = function CoreFactory(player, loader) {
this.player = player;
this.options = player.options;
this.loader = loader;
this.options.loader = this.loader;
};
($traceurRuntime.createClass)(CoreFactory, {
create: function() {
this.core = new Core(this.options);
this.core.then(this.addCorePlugins.bind(this));
return this.core;
},
addCorePlugins: function() {
_.each(this.loader.corePlugins, function(Plugin) {
var plugin = new Plugin(this.core);
this.core.addPlugin(plugin);
this.setupExternalInterface(plugin);
}, this);
return this.core;
},
setupExternalInterface: function(plugin) {
_.each(plugin.getExternalInterface(), function(value, key) {
this.player[key] = value.bind(plugin);
}, this);
}
}, {}, BaseObject);
module.exports = CoreFactory;
},{"../../base/base_object":"2HNVgz","../core":31,"underscore":6}],33:[function(require,module,exports){
"use strict";
module.exports = require('./core_factory');
},{"./core_factory":32}],34:[function(require,module,exports){
"use strict";
module.exports = require('./loader');
},{"./loader":35}],35:[function(require,module,exports){
"use strict";
var BaseObject = require('../../base/base_object');
var _ = require('underscore');
var PlayerInfo = require('../player_info');
var HTML5VideoPlayback = require('../../playbacks/html5_video');
var FlashVideoPlayback = require('../../playbacks/flash');
var HTML5AudioPlayback = require('../../playbacks/html5_audio');
var HLSVideoPlayback = require('../../playbacks/hls');
var NoOp = require('../../playbacks/no_op');
var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');
var StatsPlugin = require('../../plugins/stats');
var WaterMarkPlugin = require('../../plugins/watermark');
var PosterPlugin = require('../../plugins/poster');
var BackgroundButton = require('../../plugins/background_button');
var Loader = function Loader(externalPlugins) {
$traceurRuntime.superCall(this, $Loader.prototype, "constructor", []);
this.playerInfo = PlayerInfo.getInstance();
this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, NoOp];
this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin];
this.corePlugins = [BackgroundButton];
if (externalPlugins) {
this.addExternalPlugins(externalPlugins);
}
};
var $Loader = Loader;
($traceurRuntime.createClass)(Loader, {
addExternalPlugins: function(plugins) {
var pluginName = function(plugin) {
return plugin.prototype.name;
};
if (plugins.playback) {
this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);
}
if (plugins.container) {
this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);
}
if (plugins.core) {
this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);
}
this.playerInfo.playbackPlugins = this.playbackPlugins;
},
getPlugin: function(name) {
var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);
return _.find(allPlugins, function(plugin) {
return plugin.prototype.name === name;
});
}
}, {}, BaseObject);
module.exports = Loader;
},{"../../base/base_object":"2HNVgz","../../playbacks/flash":48,"../../playbacks/hls":50,"../../playbacks/html5_audio":52,"../../playbacks/html5_video":54,"../../playbacks/no_op":55,"../../plugins/background_button":57,"../../plugins/poster":60,"../../plugins/spinner_three_bounce":62,"../../plugins/stats":64,"../../plugins/watermark":66,"../player_info":"Pce0iO","underscore":6}],"A8Uh+k":[function(require,module,exports){
"use strict";
module.exports = require('./media_control');
},{"./media_control":38}],"media_control":[function(require,module,exports){
module.exports=require('A8Uh+k');
},{}],38:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('jquery');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var UIObject = require('../../base/ui_object');
var Utils = require('../../base/utils');
var Mousetrap = require('mousetrap');
var SeekTime = require('../seek_time');
var transitionEvents = 'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend';
var MediaControl = function MediaControl(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]);
this.seekTime = new SeekTime(this);
this.options = options;
this.currentVolume = this.options.mute ? 0 : 100;
this.container = options.container;
this.container.setVolume(this.currentVolume);
this.keepVisible = false;
this.addEventListeners();
this.settings = {
left: ['play', 'stop', 'pause'],
right: ['volume'],
default: ['position', 'seekbar', 'duration']
};
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.disabled = false;
if (this.container.mediaControlDisabled || this.options.chromeless) {
this.disable();
}
$(document).bind('mouseup', (function(event) {
return $__0.stopDrag(event);
}));
$(document).bind('mousemove', (function(event) {
return $__0.updateDrag(event);
}));
};
var $MediaControl = MediaControl;
($traceurRuntime.createClass)(MediaControl, {
get name() {
return 'MediaControl';
},
get attributes() {
return {
class: 'media-control',
'data-media-control': ''
};
},
get events() {
return {
'click [data-play]': 'play',
'click [data-pause]': 'pause',
'click [data-playpause]': 'togglePlayPause',
'click [data-stop]': 'stop',
'click [data-playstop]': 'togglePlayStop',
'click [data-fullscreen]': 'toggleFullscreen',
'click [data-seekbar]': 'seek',
'click .bar-background[data-volume]': 'volume',
'click .drawer-icon[data-volume]': 'toggleMute',
'mouseover .drawer-container[data-volume]': 'showVolumeBar',
'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',
'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',
'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',
'mouseenter .bar-container[data-volume]': 'mousemoveOnSeekBar',
'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',
'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',
'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',
'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'
};
},
get template() {
return JST.media_control;
},
addEventListeners: function() {
this.listenTo(this.container, 'container:play', this.changeTogglePlay);
this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar);
this.listenTo(this.container, 'container:progress', this.updateProgressBar);
this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate);
this.listenTo(this.container, 'container:mediacontrol:disable', this.disable);
this.listenTo(this.container, 'container:mediacontrol:enable', this.enable);
this.listenTo(this.container, 'container:playbackstate', this.updatePlaybackType);
this.listenTo(this.container, 'container:ended', this.ended);
},
disable: function() {
this.disabled = true;
this.hide();
this.$el.hide();
},
enable: function() {
if (this.options.chromeless)
return;
this.disabled = false;
this.show();
},
play: function() {
this.container.play();
},
pause: function() {
this.container.pause();
},
stop: function() {
this.container.stop();
},
changeTogglePlay: function() {
if (this.container.isPlaying()) {
this.$playPauseToggle.removeClass('paused').addClass('playing');
this.$playStopToggle.removeClass('stopped').addClass('playing');
this.trigger('mediacontrol:playing');
} else {
this.$playPauseToggle.removeClass('playing').addClass('paused');
this.$playStopToggle.removeClass('playing').addClass('stopped');
this.trigger('mediacontrol:notplaying');
}
},
mousemoveOnSeekBar: function(event) {
if (this.container.settings.seekEnabled) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);
this.$seekBarHover.css({left: offsetX});
this.$seekBarHover.show();
}
this.trigger('mediacontrol:mousemove:seekbar', event);
},
mouseleaveOnSeekBar: function(event) {
this.$seekBarHover.hide();
this.trigger('mediacontrol:mouseleave:seekbar', event);
},
togglePlayPause: function() {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
this.changeTogglePlay();
},
togglePlayStop: function() {
if (this.container.isPlaying()) {
this.container.stop();
} else {
this.container.play();
}
this.changeTogglePlay();
},
startSeekDrag: function(event) {
if (!this.container.settings.seekEnabled)
return;
this.draggingSeekBar = true;
this.$seekBarLoaded.addClass('media-control-notransition');
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (event) {
event.preventDefault();
}
},
startVolumeDrag: function(event) {
this.draggingVolumeBar = true;
if (event) {
event.preventDefault();
}
},
stopDrag: function(event) {
if (this.draggingSeekBar) {
this.seek(event);
}
this.$seekBarLoaded.removeClass('media-control-notransition');
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
this.draggingSeekBar = false;
this.draggingVolumeBar = false;
},
updateDrag: function(event) {
if (event) {
event.preventDefault();
}
if (this.draggingSeekBar) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.setSeekPercentage(pos);
} else if (this.draggingVolumeBar) {
this.volume(event);
}
},
volume: function(event) {
var offsetY = event.pageY - this.$volumeBarContainer.offset().top;
this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100;
this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0));
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
},
toggleMute: function() {
if (!!this.mute) {
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
this.mute = false;
} else {
this.container.setVolume(0);
this.setVolumeLevel(0);
this.mute = true;
}
},
toggleFullscreen: function() {
this.trigger('mediacontrol:fullscreen', this.name);
},
setContainer: function(container) {
this.stopListening(this.container);
this.container = container;
this.changeTogglePlay();
this.addEventListeners();
this.settingsUpdate();
this.container.setVolume(this.currentVolume);
if (this.container.mediaControlDisabled) {
this.disable();
}
this.trigger("mediacontrol:containerchanged");
},
showVolumeBar: function() {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.$volumeBarContainer.show();
this.$volumeBarContainer.removeClass('volume-bar-hide');
},
hideVolumeBar: function() {
var $__0 = this;
if (!this.$volumeBarContainer)
return;
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.hideVolumeId = setTimeout((function() {
$__0.$volumeBarContainer.one(transitionEvents, (function() {
$__0.$volumeBarContainer.off(transitionEvents);
$__0.$volumeBarContainer.hide();
}));
$__0.$volumeBarContainer.addClass('volume-bar-hide');
}), 750);
},
ended: function() {
this.changeTogglePlay();
},
updateProgressBar: function(startPosition, endPosition, duration) {
var loadedStart = startPosition / duration * 100;
var loadedEnd = endPosition / duration * 100;
this.$seekBarLoaded.css({
left: loadedStart + '%',
width: (loadedEnd - loadedStart) + '%'
});
},
updateSeekBar: function(position, duration) {
if (this.draggingSeekBar)
return;
if (position < 0)
position = duration;
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
var seekbarValue = (100 / duration) * position;
this.setSeekPercentage(seekbarValue);
this.$('[data-position]').html(Utils.formatTime(position));
this.$('[data-duration]').html(Utils.formatTime(duration));
},
seek: function(event) {
if (!this.container.settings.seekEnabled)
return;
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.container.setCurrentTime(pos);
},
setKeepVisible: function() {
this.keepVisible = true;
},
resetKeepVisible: function() {
this.keepVisible = false;
},
show: function(event) {
var $__0 = this;
if (this.disabled || !this.$el.hasClass('media-control-hide'))
return;
var timeout = 2000;
if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {
if (this.hideId) {
clearTimeout(this.hideId);
}
this.$el.show();
this.trigger('mediacontrol:show', this.name);
this.$el.removeClass('media-control-hide');
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (event) {
this.lastMouseX = event.clientX;
this.lastMouseY = event.clientY;
}
}
},
hide: function() {
var $__0 = this;
var timeout = 2000;
if (this.hideId) {
clearTimeout(this.hideId);
}
if (this.$el.hasClass('media-control-hide'))
return;
if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) {
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
} else {
if (this.$volumeBarContainer) {
this.$volumeBarContainer.hide();
}
this.trigger('mediacontrol:hide', this.name);
this.$el.addClass('media-control-hide');
}
},
settingsUpdate: function() {
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.render();
},
highDefinitionUpdate: function() {
if (this.container.isHighDefinitionInUse()) {
this.$el.find('button[data-hd-indicator]').addClass("enabled");
} else {
this.$el.find('button[data-hd-indicator]').removeClass("enabled");
}
},
createCachedElements: function() {
this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');
this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');
this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');
this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');
this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');
this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');
this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');
this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');
this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]');
this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]');
this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]');
this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');
},
setVolumeLevel: function(value) {
var $__0 = this;
if (!this.container.isReady) {
this.listenToOnce(this.container, "container:ready", (function() {
return $__0.setVolumeLevel(value);
}));
} else {
var containerHeight = this.$volumeBarContainer.height();
var barHeight = this.$volumeBarBackground.height();
var offset = (containerHeight - barHeight) / 2.0;
var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset;
this.$volumeBarFill.css({height: value + '%'});
this.$volumeBarScrubber.css({bottom: pos});
if (value > 0) {
this.$volumeIcon.removeClass('muted');
} else {
this.$volumeIcon.addClass('muted');
}
}
},
setSeekPercentage: function(value) {
if (value > 100)
return;
var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);
this.currentSeekPercentage = value;
this.$seekBarPosition.css({width: value + '%'});
this.$seekBarScrubber.css({left: pos});
},
bindKeyEvents: function() {
var $__0 = this;
Mousetrap.bind(['space'], (function() {
return $__0.togglePlayPause();
}));
},
parseColors: function() {
var $__0 = this;
var translate = {
query: {
'seekbar': '.bar-fill-2[data-seekbar]',
'buttons': '[data-media-control] > .media-control-icon, [data-volume]'
},
rule: {
'seekbar': 'background-color',
'buttons': 'color'
}
};
var customColors = _.pick(this.options.mediacontrol, 'seekbar', 'buttons');
_.each(customColors, (function(value, key) {
$__0.$el.find(translate.query[key]).css(translate.rule[key], customColors[key]);
}));
},
render: function() {
var $__0 = this;
var timeout = 1000;
var style = Styler.getStyleFor('media_control');
this.$el.html(this.template({settings: this.settings}));
this.$el.append(style);
this.createCachedElements();
this.$playPauseToggle.addClass('paused');
this.$playStopToggle.addClass('stopped');
this.$volumeBarContainer.hide();
this.changeTogglePlay();
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (this.disabled) {
this.hide();
}
this.$seekBarHover.hide();
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (!this.currentSeekPercentage) {
this.currentSeekPercentage = 0;
}
this.setSeekPercentage(this.currentSeekPercentage);
this.$el.ready((function() {
if (!$__0.container.settings.seekEnabled) {
$__0.$seekBarContainer.addClass('seek-disabled');
}
$__0.setVolumeLevel($__0.currentVolume);
$__0.bindKeyEvents();
}));
this.parseColors();
return this;
}
}, {}, UIObject);
module.exports = MediaControl;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_object":"8lqCAT","../../base/utils":23,"../seek_time":44,"jquery":3,"mousetrap":4,"underscore":6}],"veeMMc":[function(require,module,exports){
"use strict";
var Events = require('../base/events');
var events = new Events();
var Mediator = function Mediator() {};
($traceurRuntime.createClass)(Mediator, {}, {});
Mediator.on = function(name, callback, context) {
events.on(name, callback, context);
return;
};
Mediator.once = function(name, callback, context) {
events.once(name, callback, context);
return;
};
Mediator.off = function(name, callback, context) {
events.off(name, callback, context);
return;
};
Mediator.trigger = function(name, opts) {
events.trigger(name, opts);
return;
};
Mediator.stopListening = function(obj, name, callback) {
events.stopListening(obj, name, callback);
return;
};
module.exports = Mediator;
},{"../base/events":11}],"mediator":[function(require,module,exports){
module.exports=require('veeMMc');
},{}],"Pce0iO":[function(require,module,exports){
"use strict";
module.exports = require('./player_info');
},{"./player_info":43}],"player_info":[function(require,module,exports){
module.exports=require('Pce0iO');
},{}],43:[function(require,module,exports){
"use strict";
var BaseObject = require('../../base/base_object');
var PlayerInfo = function PlayerInfo() {
this.options = {};
this.playbackPlugins = [];
this.currentSize = {
width: 0,
height: 0
};
};
($traceurRuntime.createClass)(PlayerInfo, {}, {}, BaseObject);
PlayerInfo.getInstance = function() {
if (this._instance === undefined) {
this._instance = new this();
}
return this._instance;
};
module.exports = PlayerInfo;
},{"../../base/base_object":"2HNVgz"}],44:[function(require,module,exports){
"use strict";
module.exports = require('./seek_time');
},{"./seek_time":45}],45:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var formatTime = require('../../base/utils').formatTime;
var $ = require('jquery');
var SeekTime = function SeekTime(mediaControl) {
$traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []);
this.mediaControl = mediaControl;
this.listenTo(this.mediaControl.container, 'container:playbackstate', this.setPlaybackType);
this.listenTo(this.mediaControl, 'mediacontrol:containerchanged', this.onContainerChanged);
this.setPlaybackType();
this.render();
};
var $SeekTime = SeekTime;
($traceurRuntime.createClass)(SeekTime, {
get name() {
return 'seek_time';
},
get template() {
return JST.seek_time;
},
get attributes() {
return {
'class': 'seek-time hidden',
'data-seek-time': ''
};
},
onContainerChanged: function() {
this.listenTo(this.mediaControl.container, 'container:playbackstate', this.setPlaybackType);
this.setPlaybackType();
},
addEventListeners: function() {
this.listenTo(this.mediaControl, 'mediacontrol:mousemove:seekbar', this.showTime);
this.listenTo(this.mediaControl, 'mediacontrol:mouseleave:seekbar', this.hideTime);
},
setPlaybackType: function() {
var type = this.mediaControl.container.getPlaybackType();
if (type === 'vod') {
this.addEventListeners();
} else {
this.stopListening(this.mediaControl, 'mediacontrol:mousemove:seekbar');
this.stopListening(this.mediaControl, 'mediacontrol:mouseleave:seekbar');
this.hideTime();
}
},
showTime: function(event) {
var elementClass = $(event.target).attr('class');
var offset,
width;
if (elementClass === 'bar-container') {
offset = $(event.target).offset().left;
width = $(event.target).width();
} else if (elementClass === 'bar-hover') {
offset = $(event.target).parent().parent().offset().left;
width = $(event.target).parent().parent().width();
} else {
return;
}
var pos = (event.pageX - offset) / width * 100;
pos = Math.min(100, Math.max(pos, 0));
this.currentTime = pos * this.mediaControl.container.getDuration() / 100;
this.time = formatTime(this.currentTime);
this.$el.css('left', event.pageX - Math.floor((this.$el.width() / 2) + 6));
this.$el.removeClass('hidden');
this.render(event);
},
hideTime: function() {
this.$el.addClass('hidden');
},
getExternalInterface: function() {},
render: function(event) {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({time: this.time}));
this.$el.append(style);
this.mediaControl.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = SeekTime;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_object":"8lqCAT","../../base/utils":23,"jquery":3}],46:[function(require,module,exports){
(function (global){
"use strict";
var BaseObject = require('./base/base_object');
var CoreFactory = require('./components/core_factory');
var Loader = require('./components/loader');
var Mediator = require('./components/mediator');
var _ = require('underscore');
var ScrollMonitor = require('scrollmonitor');
var PlayerInfo = require('./components/player_info');
var Player = function Player(options) {
$traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]);
window.p = this;
this.options = options;
this.options.sources = this.normalizeSources(options);
this.loader = new Loader(this.options.plugins || []);
this.coreFactory = new CoreFactory(this, this.loader);
this.playerInfo = PlayerInfo.getInstance();
options.height || (options.height = 360);
options.width || (options.width = 640);
this.playerInfo.currentSize = {
width: options.width,
height: options.height
};
};
var $Player = Player;
($traceurRuntime.createClass)(Player, {
attachTo: function(element) {
this.options.parentElement = element;
this.core = this.coreFactory.create();
if (this.options.autoPlayVisible) {
this.bindAutoPlayVisible(this.options.autoPlayVisible);
}
},
bindAutoPlayVisible: function(option) {
var $__0 = this;
this.elementWatcher = ScrollMonitor.create(this.core.$el);
if (option === 'full') {
this.elementWatcher.fullyEnterViewport((function() {
return $__0.enterViewport();
}));
} else if (option === 'partial') {
this.elementWatcher.enterViewport((function() {
return $__0.enterViewport();
}));
}
},
enterViewport: function() {
if (this.elementWatcher.top !== 0 && !this.isPlaying()) {
this.play();
}
},
normalizeSources: function(options) {
return _.compact(_.flatten([options.source, options.sources]));
},
load: function(sources) {
this.core.load(sources);
},
destroy: function() {
this.core.destroy();
},
play: function() {
this.core.mediaControl.container.play();
},
pause: function() {
this.core.mediaControl.container.pause();
},
stop: function() {
this.core.mediaControl.container.stop();
},
seek: function(time) {
this.core.mediaControl.container.setCurrentTime(time);
},
setVolume: function(volume) {
this.core.mediaControl.container.setVolume(volume);
},
mute: function() {
this.core.mediaControl.container.setVolume(0);
},
unmute: function() {
this.core.mediaControl.container.setVolume(100);
},
isPlaying: function() {
return this.core.mediaControl.container.isPlaying();
}
}, {}, BaseObject);
global.DEBUG = false;
window.Clappr = {
Player: Player,
Mediator: Mediator
};
module.exports = window.Clappr;
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./base/base_object":"2HNVgz","./components/core_factory":33,"./components/loader":34,"./components/mediator":"veeMMc","./components/player_info":"Pce0iO","scrollmonitor":5,"underscore":6}],47:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('../../components/mediator');
var _ = require('underscore');
var $ = require('jquery');
var Browser = require('../../components/browser');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> </object>';
var Flash = function Flash(options) {
$traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]);
this.src = options.src;
this.isRTMP = !!(this.src.indexOf("rtmp") > -1);
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/Player.swf";
this.autoPlay = options.autoPlay;
this.settings = {default: ['seekbar']};
if (this.isRTMP) {
this.settings.left = ["playstop", "volume"];
this.settings.right = ["fullscreen"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["volume", "fullscreen"];
this.settings.seekEnabled = true;
}
this.isReady = false;
this.addListeners();
};
var $Flash = Flash;
($traceurRuntime.createClass)(Flash, {
get name() {
return 'flash';
},
get tagName() {
return 'object';
},
get template() {
return JST.flash;
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger('playback:ready', this.name);
this.currentState = "IDLE";
this.autoPlay && this.play();
$('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el);
},
getPlaybackType: function() {
return this.isRTMP ? 'live' : 'vod';
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-flash', '');
this.setElement($el[0]);
},
isHighDefinitionInUse: function() {
return false;
},
updateTime: function() {
this.trigger('playback:timeupdate', this.el.getPosition(), this.el.getDuration(), this.name);
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':progress', (function() {
return $__0.progress();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':statechanged', (function() {
return $__0.checkState();
}));
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':progress');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':statechanged');
},
checkState: function() {
if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") {
this.trigger('playback:buffering', this.name);
this.currentState = "PLAYING_BUFFERING";
} else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") {
this.trigger('playback:bufferfull', this.name);
this.currentState = "PLAYING";
} else if (this.el.getState() === "IDLE") {
this.currentState = "IDLE";
} else if (this.el.getState() === "ENDED") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.getDuration(), this.name);
this.currentState = "ENDED";
}
},
progress: function() {
if (this.currentState !== "IDLE" && this.currentState !== "ENDED") {
this.trigger('playback:progress', 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);
}
},
firstPlay: function() {
this.currentState = "PLAYING";
this.el.playerPlay(this.src);
},
play: function() {
if (this.el.getState() === 'PAUSED') {
this.currentState = "PLAYING";
this.el.playerResume();
} else if (this.el.getState() !== 'PLAYING') {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.playerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
this.currentState = "PAUSED";
this.el.playerPause();
},
stop: function() {
this.el.playerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
return !!(this.isReady && this.currentState === "PLAYING");
},
getDuration: function() {
return this.el.getDuration();
},
seek: function(time) {
var seekTo = this.el.getDuration() * (time / 100);
this.el.playerSeek(seekTo);
this.trigger('playback:timeupdate', seekTo, this.el.getDuration(), this.name);
if (this.currentState === "PAUSED") {
this.pause();
}
},
destroy: function() {
clearInterval(this.bootstrapId);
this.stopListening();
this.$el.remove();
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath
})));
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isLegacyIE) {
this.setupIE();
}
this.$el.append(style);
return this;
}
}, {}, UIObject);
Flash.canPlay = function(resource) {
if (resource.indexOf('rtmp') > -1) {
return true;
} else if (Browser.isFirefox || Browser.isLegacyIE) {
return _.isString(resource) && !!resource.match(/(.*).(mp4|mov|f4v|3gpp|3gp)/);
} else {
return _.isString(resource) && !!resource.match(/(.*).(mov|f4v|3gpp|3gp)/);
}
};
module.exports = Flash;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_object":"8lqCAT","../../components/browser":"195Wj5","../../components/mediator":"veeMMc","jquery":3,"underscore":6}],48:[function(require,module,exports){
"use strict";
module.exports = require('./flash');
},{"./flash":47}],49:[function(require,module,exports){
"use strict";
var UIPlugin = require('../../base/ui_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var _ = require("underscore");
var Mediator = require('../../components/mediator');
var Browser = require('../../components/browser');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var HLS = function HLS(options) {
$traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]);
this.src = options.src;
this.swfPath = options.swfPath || "http://cdn.clappr.io/latest/assets/HLSPlayer.swf";
this.highDefinition = false;
this.autoPlay = options.autoPlay;
this.defaultSettings = {
left: ["playstop"],
default: ['seekbar'],
right: ["fullscreen", "volume", "hd-indicator"],
seekEnabled: true
};
this.settings = _.extend({}, this.defaultSettings);
this.addListeners();
};
var $HLS = HLS;
($traceurRuntime.createClass)(HLS, {
get name() {
return 'hls';
},
get tagName() {
return 'object';
},
get template() {
return JST.hls;
},
get attributes() {
return {
'class': 'hls-playback',
'data-hls': '',
'type': 'application/x-shockwave-flash'
};
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':playbackstate', (function(state) {
return $__0.setPlaybackState(state);
}));
Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {
return $__0.updateHighDefinition(isHD);
}));
Mediator.on(this.uniqueId + ':playbackerror', (function() {
return $__0.flashPlaybackError();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':flashready');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':playbackstate');
Mediator.off(this.uniqueId + ':highdefinition');
Mediator.off(this.uniqueId + ':playbackerror');
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger('playback:ready', this.name);
this.currentState = "IDLE";
this.el.globoPlayerSetflushLiveURLCache(true);
this.autoPlay && this.play();
},
updateHighDefinition: function(isHD) {
this.highDefinition = (isHD === "true");
this.trigger('playback:highdefinitionupdate');
},
updateTime: function() {
var duration = this.getDuration();
var position = this.el.globoGetPosition();
var livePlayback = this.playbackType === 'live';
if (livePlayback && (position >= duration || position < 0)) {
position = duration;
}
var previousDVRStatus = this.dvrEnabled;
this.dvrEnabled = (livePlayback && duration > 240);
if (this.dvrEnabled !== previousDVRStatus) {
this.updateSettings();
this.trigger('playback:settingsupdate', this.name);
}
if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {
position = duration;
}
this.trigger('playback:timeupdate', position, duration, this.name);
},
play: function() {
if (this.currentState === 'PAUSED') {
this.el.globoPlayerResume();
} else if (this.currentState !== "PLAYING") {
this.firstPlay();
}
this.trigger('playback:play', this.name);
},
getPlaybackType: function() {
if (this.playbackType)
return this.playbackType;
return null;
},
getCurrentBitrate: function() {
var currentLevel = this.getLevels()[this.el.globoGetLevel()];
return currentLevel.bitrate;
},
getLastProgramDate: function() {
var programDate = this.el.globoGetLastProgramDate();
return programDate - 1.08e+7;
},
isHighDefinitionInUse: function() {
return this.highDefinition;
},
getLevels: function() {
if (!this.levels || this.levels.length === 0) {
this.levels = this.el.globoGetLevels();
}
return this.levels;
},
setPlaybackState: function(state) {
var bufferLength = this.el.globoGetbufferLength();
if (state === "PLAYING_BUFFERING" && bufferLength < 1) {
this.trigger('playback:buffering', this.name);
this.updateCurrentState(state);
} else if (state === "PLAYING") {
if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) {
this.trigger('playback:bufferfull', this.name);
this.updateCurrentState(state);
}
} else if (state === "PAUSED") {
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name);
this.updateCurrentState(state);
}
this.lastBufferLength = bufferLength;
},
updateCurrentState: function(state) {
this.currentState = state;
this.updatePlaybackType();
},
updatePlaybackType: function() {
this.playbackType = this.el.globoGetType();
if (this.playbackType) {
this.playbackType = this.playbackType.toLowerCase();
}
this.trigger('playback:playbackstate');
},
firstPlay: function() {
this.el.globoPlayerLoad(this.src);
this.el.globoPlayerPlay();
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.globoPlayerVolume(value);
} else {
this.listenToOnce(this, 'playback:bufferfull', (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
if (this.playbackType !== 'live' || this.dvrEnabled) {
this.el.globoPlayerPause();
if (this.playbackType === 'live' && this.dvrEnabled) {
this.updateDvr(true);
}
}
},
stop: function() {
this.el.globoPlayerStop();
this.trigger('playback:timeupdate', 0, this.name);
},
isPlaying: function() {
if (this.currentState) {
return !!(this.currentState.match(/playing/i));
}
return false;
},
getDuration: function() {
var duration = this.el.globoGetDuration();
if (this.playbackType === 'live') {
duration = duration - 10;
}
return duration;
},
seek: function(time) {
var duration = this.getDuration();
if (time > 0) {
time = duration * time / 100;
}
if (this.playbackType === 'live') {
var dvrInUse = (duration - time > 5);
if (!dvrInUse) {
time = -1;
}
this.updateDvr(dvrInUse);
}
this.el.globoPlayerSeek(time);
this.trigger('playback:timeupdate', time, duration, this.name);
},
updateDvr: function(dvrInUse) {
var previousDvrInUse = !!this.dvrInUse;
this.dvrInUse = dvrInUse;
if (this.dvrInUse !== previousDvrInUse) {
this.updateSettings();
this.trigger('playback:dvr', this.dvrInUse);
}
},
flashPlaybackError: function() {
this.trigger('playback:stop');
},
timeUpdate: function(time, duration) {
this.trigger('playback:timeupdate', time, duration, this.name);
},
destroy: function() {
this.stopListening();
this.$el.remove();
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-hls', '');
this.setElement($el);
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
updateSettings: function() {
this.settings = _.extend({}, this.defaultSettings);
if (this.playbackType === "vod" || this.dvrInUse) {
this.settings.left = ["playpause", "position", "duration"];
} else if (this.dvrEnabled) {
this.settings.left = ["playpause"];
} else {
this.settings.seekEnabled = false;
}
},
setElement: function(element) {
this.$el = element;
this.el = element[0];
},
render: function() {
var style = Styler.getStyleFor(this.name);
if (Browser.isLegacyIE) {
this.setupIE();
} else {
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isIE) {
this.$('embed').remove();
}
}
this.el.id = this.cid;
this.$el.append(style);
return this;
}
}, {}, UIPlugin);
HLS.canPlay = function(resource) {
return !!resource.match(/^http(.*).m3u8/);
};
module.exports = HLS;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_plugin":"Z7u8cr","../../components/browser":"195Wj5","../../components/mediator":"veeMMc","underscore":6}],50:[function(require,module,exports){
"use strict";
module.exports = require('./hls');
},{"./hls":49}],51:[function(require,module,exports){
"use strict";
var UIPlugin = require('../../base/ui_plugin');
var HTML5Audio = function HTML5Audio(params) {
$traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]);
this.el.src = params.src;
this.settings = {
left: ['playpause', 'position', 'duration'],
right: ['fullscreen', 'volume'],
default: ['seekbar']
};
this.render();
params.autoPlay && this.play();
};
var $HTML5Audio = HTML5Audio;
($traceurRuntime.createClass)(HTML5Audio, {
get name() {
return 'html5_audio';
},
get tagName() {
return 'audio';
},
get events() {
return {
'timeupdate': 'timeUpdated',
'ended': 'ended'
};
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.play);
this.listenTo(this.container, 'container:pause', this.pause);
this.listenTo(this.container, 'container:seek', this.seek);
this.listenTo(this.container, 'container:volume', this.volume);
this.listenTo(this.container, 'container:stop', this.stop);
},
getPlaybackType: function() {
return "aod";
},
play: function() {
this.el.play();
this.trigger('playback:play');
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger('container:timeupdate', 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
timeUpdated: function() {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
},
render: function() {
return this;
}
}, {}, UIPlugin);
HTML5Audio.canPlay = function(resource) {
return !!resource.match(/(.*).mp3/);
};
module.exports = HTML5Audio;
},{"../../base/ui_plugin":"Z7u8cr"}],52:[function(require,module,exports){
"use strict";
module.exports = require('./html5_audio');
},{"./html5_audio":51}],53:[function(require,module,exports){
"use strict";
var Playback = require('../../base/playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('../../components/browser');
var HTML5Video = function HTML5Video(options) {
$traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]);
this.options = options;
this.src = options.src;
this.el.src = options.src;
this.el.loop = options.loop;
this.isHLS = !!(this.src.indexOf('m3u8') > -1);
this.settings = {default: ['seekbar']};
if (this.isHLS) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
};
var $HTML5Video = HTML5Video;
($traceurRuntime.createClass)(HTML5Video, {
get name() {
return 'html5_video';
},
get tagName() {
return 'video';
},
get template() {
return JST.html5_video;
},
get attributes() {
return {'data-html5-video': ''};
},
get events() {
return {
'timeupdate': 'timeUpdated',
'progress': 'progress',
'ended': 'ended',
'playing': 'playing',
'stalled': 'stalled',
'waiting': 'waiting',
'canplaythrough': 'bufferFull',
'loadedmetadata': 'loadedMetadata'
};
},
loadedMetadata: function(e) {
this.trigger('playback:loadedmetadata', e.target.duration);
},
getPlaybackType: function() {
return this.isHLS ? 'live' : 'vod';
},
isHighDefinitionInUse: function() {
return false;
},
play: function() {
this.el.play();
this.trigger('playback:play');
if (this.isHLS) {
this.trigger('playback:timeupdate', 1, 1, this.name);
}
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
if (this.el.readyState !== 0) {
this.el.currentTime = 0;
}
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
ended: function() {
this.trigger('playback:ended', this.name);
this.trigger('playback:timeupdate', 0, this.el.duration, this.name);
},
stalled: function() {
if (this.getPlaybackType() === 'vod') {
this.trigger('playback:buffering', this.name);
}
},
waiting: function() {
this.trigger('playback:buffering', this.name);
},
bufferFull: function() {
this.trigger('playback:bufferfull', this.name);
},
destroy: function() {
this.stop();
this.el.src = '';
this.$el.remove();
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
if (!this.isHLS) {
this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
}
},
progress: function() {
if (!this.el.buffered.length)
return;
var bufferedPos = 0;
for (var i = 0; i < this.el.buffered.length; i++) {
if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
bufferedPos = i;
break;
}
}
this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
},
typeFor: function(src) {
return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
src: this.src,
type: this.typeFor(this.src)
}));
this.$el.append(style);
this.trigger('playback:ready', this.name);
this.options.autoPlay && this.play();
return this;
}
}, {}, Playback);
HTML5Video.canPlay = function(resource) {
return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App);
};
module.exports = HTML5Video;
},{"../../base/jst":12,"../../base/playback":"VbgHr3","../../base/styler":16,"../../components/browser":"195Wj5"}],54:[function(require,module,exports){
"use strict";
module.exports = require('./html5_video');
},{"./html5_video":53}],55:[function(require,module,exports){
"use strict";
var Playback = require('../base/playback');
var NoOp = function NoOp() {
$traceurRuntime.defaultSuperCall(this, $NoOp.prototype, arguments);
};
var $NoOp = NoOp;
($traceurRuntime.createClass)(NoOp, {}, {}, Playback);
NoOp.canPlay = (function(source) {
return true;
});
module.exports = NoOp;
},{"../base/playback":"VbgHr3"}],56:[function(require,module,exports){
"use strict";
var UIObject = require('../../base/ui_object');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var BackgroundButton = function BackgroundButton(core) {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]);
this.core = core;
this.listenTo(this.core.mediaControl.container, 'container:state:buffering', this.hide);
this.listenTo(this.core.mediaControl.container, 'container:state:bufferfull', this.show);
this.listenTo(this.core.mediaControl.container, 'container:settingsupdate', this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, 'container:dvr', this.settingsUpdate);
this.listenTo(this.core.mediaControl, 'mediacontrol:show', this.show);
this.listenTo(this.core.mediaControl, 'mediacontrol:hide', this.hide);
this.listenTo(this.core.mediaControl, 'mediacontrol:playing', this.playing);
this.listenTo(this.core.mediaControl, 'mediacontrol:notplaying', this.notplaying);
this.settingsUpdate();
};
var $BackgroundButton = BackgroundButton;
($traceurRuntime.createClass)(BackgroundButton, {
get template() {
return JST.background_button;
},
get name() {
return 'background_button';
},
get events() {
return {'click .playpause-icon': 'click'};
},
get attributes() {
return {
'class': 'background-button',
'data-background-button': ''
};
},
settingsUpdate: function() {
if (this.shouldRender()) {
this.render();
if (this.core.mediaControl.container.isPlaying()) {
this.playing();
} else {
this.notplaying();
}
}
},
shouldRender: function() {
var settings = this.core.mediaControl.settings;
return settings.default.indexOf('playpause') >= 0 || settings.left.indexOf('playpause') >= 0 || settings.right.indexOf('playpause') >= 0;
},
click: function() {
this.core.mediaControl.togglePlayPause();
},
show: function() {
this.$el.removeClass('hide');
},
hide: function() {
this.$el.addClass('hide');
},
playing: function() {
this.$el.find('.playpause-icon[data-background-button]').removeClass('paused').addClass('playing');
},
notplaying: function() {
this.$el.find('.playpause-icon[data-background-button]').removeClass('playing').addClass('paused');
},
getExternalInterface: function() {},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.core.mediaControl.$el.find('[data-playpause]').hide();
this.core.$el.append(this.$el);
return this;
}
}, {}, UIObject);
module.exports = BackgroundButton;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_object":"8lqCAT"}],57:[function(require,module,exports){
"use strict";
module.exports = require('./background_button');
},{"./background_button":56}],58:[function(require,module,exports){
"use strict";
module.exports = require('./log');
},{"./log":59}],59:[function(require,module,exports){
"use strict";
var $ = require('jquery');
var BOLD = 'font-weight: bold; font-size: 13px;';
var INFO = 'color: green;' + BOLD;
var DEBUG = 'color: #222;' + BOLD;
var ERROR = 'color: red;' + BOLD;
var DEFAULT = '';
$(document).keydown(function(e) {
if (e.ctrlKey && e.shiftKey && e.keyCode === 68) {
window.DEBUG = !window.DEBUG;
}
});
var Log = function(klass) {
this.klass = klass || 'Logger';
};
Log.info = function(klass, msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg);
};
Log.error = function(klass, msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg);
};
Log.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
Log.prototype = {
log: function(msg) {
this.info(msg);
},
info: function(msg) {
console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg);
},
error: function(msg) {
console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg);
}
};
module.exports = Log;
},{"jquery":3}],60:[function(require,module,exports){
"use strict";
module.exports = require('./poster');
},{"./poster":61}],61:[function(require,module,exports){
"use strict";
var UIPlugin = require('../../base/ui_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('../../components/mediator');
var PlayerInfo = require('../../components/player_info');
var $ = require('jquery');
var _ = require('underscore');
var PosterPlugin = function PosterPlugin(options) {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]);
this.options = options;
_.defaults(this.options, {disableControlsOnPoster: true});
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
this.render();
this.bindEvents();
};
var $PosterPlugin = PosterPlugin;
($traceurRuntime.createClass)(PosterPlugin, {
get name() {
return 'poster';
},
get template() {
return JST.poster;
},
get attributes() {
return {
'class': 'player-poster',
'data-poster': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
var $__0 = this;
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:ended', this.onStop);
Mediator.on('player:resize', (function() {
return $__0.updateSize();
}));
},
onBuffering: function() {
this.hidePlayButton();
},
onPlay: function() {
this.$el.hide();
if (this.options.disableControlsOnPoster) {
this.container.enableMediaControl();
}
},
onStop: function() {
this.$el.show();
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
if (!this.options.hidePlayButton) {
this.showPlayButton();
}
},
hidePlayButton: function() {
this.$playButton.hide();
},
showPlayButton: function() {
this.updateSize();
this.$playButton.show();
},
clicked: function() {
this.container.play();
},
updateSize: function() {
if (!this.$el)
return;
var playerInfo = PlayerInfo.getInstance();
var height = playerInfo.currentSize ? playerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.container.$el.append(this.el);
this.$el.ready((function() {
return $__0.updateSize();
}));
this.$playButton = $(this.$el.find('.play-wrapper'));
if (this.options.poster !== undefined) {
var imgEl = $('<img data-poster class="poster-background"></img>');
imgEl.attr('src', this.options.poster);
this.$el.prepend(imgEl);
}
return this;
}
}, {}, UIPlugin);
module.exports = PosterPlugin;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_plugin":"Z7u8cr","../../components/mediator":"veeMMc","../../components/player_info":"Pce0iO","jquery":3,"underscore":6}],62:[function(require,module,exports){
"use strict";
module.exports = require('./spinner_three_bounce');
},{"./spinner_three_bounce":63}],63:[function(require,module,exports){
"use strict";
var UIPlugin = require('../../base/ui_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {
$traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stop', this.onStop);
this.render();
};
var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;
($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {
get name() {
return 'spinner_three_bounce';
},
get attributes() {
return {
'data-spinner': '',
'class': 'spinner-three-bounce'
};
},
onBuffering: function() {
this.$el.show();
},
onBufferFull: function() {
this.$el.hide();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
this.$el.html(this.template());
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIPlugin);
module.exports = SpinnerThreeBouncePlugin;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_plugin":"Z7u8cr"}],64:[function(require,module,exports){
"use strict";
module.exports = require('./stats');
},{"./stats":65}],65:[function(require,module,exports){
"use strict";
var BaseObject = require('../../base/base_object');
var $ = require("jquery");
var StatsPlugin = function StatsPlugin(options) {
$traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]);
this.setInitialAttrs();
this.reportInterval = options.reportInterval || 5000;
this.state = "IDLE";
this.bindEvents();
};
var $StatsPlugin = StatsPlugin;
($traceurRuntime.createClass)(StatsPlugin, {
get name() {
return 'stats';
},
bindEvents: function() {
this.listenTo(this.container.playback, 'playback:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
this.listenTo(this.container, 'container:destroyed', this.onStop);
this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval);
this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
this.listenTo(this.container, 'container:stats:add', this.onStatsAdd);
this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd);
},
setReportInterval: function(reportInterval) {
this.reportInterval = reportInterval;
},
setInitialAttrs: function() {
this.firstPlay = true;
this.startupTime = 0;
this.rebufferingTime = 0;
this.watchingTime = 0;
this.rebuffers = 0;
this.externalMetrics = {};
},
onPlay: function() {
this.state = "PLAYING";
this.watchingTimeInit = Date.now();
if (!this.intervalId) {
this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
}
},
onStop: function() {
clearInterval(this.intervalId);
this.intervalId = undefined;
this.state = "STOPPED";
},
onBuffering: function() {
if (this.firstPlay) {
this.startupTimeInit = Date.now();
} else {
this.rebufferingTimeInit = Date.now();
}
this.state = "BUFFERING";
this.rebuffers++;
},
onBufferFull: function() {
if (this.firstPlay) {
this.firstPlay = false;
this.startupTime = Date.now() - this.startupTimeInit;
this.watchingTimeInit = Date.now();
} else if (!!this.rebufferingTimeInit) {
this.rebufferingTime += this.getRebufferingTime();
}
this.rebufferingTimeInit = undefined;
this.state = "PLAYING";
},
getRebufferingTime: function() {
return Date.now() - this.rebufferingTimeInit;
},
getWatchingTime: function() {
var totalTime = (Date.now() - this.watchingTimeInit);
return totalTime - this.rebufferingTime;
},
isRebuffering: function() {
return !!this.rebufferingTimeInit;
},
onStatsAdd: function(metric) {
$.extend(this.externalMetrics, metric);
},
getStats: function() {
var metrics = {
startupTime: this.startupTime,
rebuffers: this.rebuffers,
rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,
watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()
};
$.extend(metrics, this.externalMetrics);
return metrics;
},
report: function() {
var stats = this.getStats();
this.container.statsReport(this.getStats());
}
}, {}, BaseObject);
module.exports = StatsPlugin;
},{"../../base/base_object":"2HNVgz","jquery":3}],66:[function(require,module,exports){
"use strict";
module.exports = require('./watermark');
},{"./watermark":67}],67:[function(require,module,exports){
"use strict";
var UIPlugin = require('../../base/ui_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var WaterMarkPlugin = function WaterMarkPlugin(options) {
$traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.position = options.position || "bottom-right";
if (options.watermark) {
this.imageUrl = options.watermark;
this.render();
} else {
this.$el.remove();
}
};
var $WaterMarkPlugin = WaterMarkPlugin;
($traceurRuntime.createClass)(WaterMarkPlugin, {
get name() {
return 'watermark';
},
bindEvents: function() {
this.listenTo(this.container, 'container:play', this.onPlay);
this.listenTo(this.container, 'container:stop', this.onStop);
},
onPlay: function() {
if (!this.hidden)
this.$el.show();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
var templateOptions = {
position: this.position,
imageUrl: this.imageUrl
};
this.$el.html(this.template(templateOptions));
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIPlugin);
module.exports = WaterMarkPlugin;
},{"../../base/jst":12,"../../base/styler":16,"../../base/ui_plugin":"Z7u8cr"}]},{},[2,46])
|
pages/premium-themes/onepirate/privacy.js
|
allanalexandre/material-ui
|
import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import AppTheme from 'docs/src/modules/components/AppTheme';
import Privacy from 'docs/src/pages/premium-themes/onepirate/Privacy';
function Page() {
return (
<AppTheme title="Onepirate theme - Material-UI" description="A onepirate theme">
<Privacy />
</AppTheme>
);
}
export default Page;
|
examples/simple-map/src/index.js
|
sushantparkhi/react-google-maps
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/components/Keycap.js
|
cuebrick/TypeWriter
|
import React from 'react';
class Keycap extends React.Component{
render(){
let nextCodeClassName = (this.props.nextCode === this.props.keyCode || this.props.isShiftKey) ? 'next-code' : '';
let keyTypeClassName = (this.props.keyType) ? ' ' + this.props.keyType : '';
let shiftingClassName = (this.props.isShifting) ? ' shifted' : '';
return(
<div data-key={this.props.keyCode} className={nextCodeClassName + keyTypeClassName}>
<div className={"en" + shiftingClassName}>
<div className="shift">{this.props.ens}</div>
<div className="normal">{this.props.enn}</div>
</div>
<div className={"kr" + shiftingClassName}>
<div className="shift">{this.props.krs}</div>
<div className="normal">{this.props.krn}</div>
</div>
</div>
)
}
}
export default Keycap;
|
packages/material-ui-icons/custom/Twitter.js
|
kybarg/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M22.46 6c-.77.35-1.6.58-2.46.69.88-.53 1.56-1.37 1.88-2.38-.83.5-1.75.85-2.72 1.05C18.37 4.5 17.26 4 16 4c-2.35 0-4.27 1.92-4.27 4.29 0 .34.04.67.11.98C8.28 9.09 5.11 7.38 3 4.79c-.37.63-.58 1.37-.58 2.15 0 1.49.75 2.81 1.91 3.56-.71 0-1.37-.2-1.95-.5v.03c0 2.08 1.48 3.82 3.44 4.21a4.22 4.22 0 0 1-1.93.07 4.28 4.28 0 0 0 4 2.98 8.521 8.521 0 0 1-5.33 1.84c-.34 0-.68-.02-1.02-.06C3.44 20.29 5.7 21 8.12 21 16 21 20.33 14.46 20.33 8.79c0-.19 0-.37-.01-.56.84-.6 1.56-1.36 2.14-2.23z" />,
'Twitter',
);
|
app/components/signUp.js
|
cqlanus/bons
|
import React from 'react'
import {login, signup} from 'APP/app/reducers/auth'
import {connect} from 'react-redux'
import {browserHistory} from 'react-router'
export const Signup = ({ login, signup }) => (
<div>
<h1>Sign Up</h1>
<form onSubmit={evt => {
evt.preventDefault()
signup(evt.target.username.value, evt.target.password.value)
browserHistory.push('/')
} }>
<input name="username" />
<input name="password" type="password" />
<input type="submit" value="Sign Up" />
</form>
</div>
)
export default connect(
state => ({}),
{login, signup},
)(Signup)
|
src/routes/Dashboard/components/sales.js
|
liufulin90/react-admin
|
import React from 'react'
import styles from './sales.less'
import {color} from '../../../utils'
import {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer} from 'recharts'
function Sales (props) {
return (
<div className={styles.sales}>
<div className={styles.title}>Yearly Sales</div>
<ResponsiveContainer minHeight={360}>
<LineChart data={props.data}>
<Legend verticalAlign='top'
content={props => {
const { payload } = props
return <ul className={styles.legend + ' clearfix'}>
{payload.map((item, key) => <li key={key}><span className={styles.radiusdot} style={{background: item.color}} />{item.value}</li>) }
</ul>
}} />
<XAxis dataKey='name' axisLine={{stroke: color.borderBase, strokeWidth: 1}} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray='3 3' />
<Tooltip
wrapperStyle={{border: 'none', boxShadow: '4px 4px 40px rgba(0, 0, 0, 0.05)'}}
content={content => {
const list = content.payload.map((item, key) => <li key={key} className={styles.tipitem}><span className={styles.radiusdot} style={{background: item.color}} />{item.name + ':' + item.value}</li>)
return <div className={styles.tooltip}><p className={styles.tiptitle}>{content.label}</p><ul>{list}</ul></div>
}} />
<Line type='monotone' dataKey='Food' stroke={color.purple} strokeWidth={3} dot={{fill: color.purple}} activeDot={{r: 5, strokeWidth: 0}} />
<Line type='monotone' dataKey='Clothes' stroke={color.red} strokeWidth={3} dot={{fill: color.red}} activeDot={{r: 5, strokeWidth: 0}} />
<Line type='monotone' dataKey='Electronics' stroke={color.green} strokeWidth={3} dot={{fill: color.green}} activeDot={{r: 5, strokeWidth: 0}} />
</LineChart>
</ResponsiveContainer>
</div>
)
}
export default Sales
|
ui/src/js/profile/edit/EditUserDetails.js
|
Dica-Developer/weplantaforest
|
import axios from 'axios';
import counterpart from 'counterpart';
import moment from 'dayjs';
import React, { Component } from 'react';
import IconButton from '../../common/components/IconButton';
import Notification from '../../common/components/Notification';
import EditDropdownItem from './EditDropdownItem';
import EditItem from './EditItem';
import EditNameItem from './EditNameItem';
import EditPasswordItem from './EditPasswordItem';
import FileChooseAndUploadButton from './FileChooseAndUploadButton';
require('./editUserDetails.less');
export default class EditUserDetails extends Component {
constructor(props) {
super(props);
}
showProfile() {
this.props.showProfile();
}
editUser(toEdit, newEntry) {
var that = this;
var config = {
headers: {
'X-AUTH-TOKEN': localStorage.getItem('jwt')
}
};
axios
.post('http://localhost:8081/user/edit?userName=' + encodeURIComponent(this.props.user.userName) + '&toEdit=' + toEdit + '&newEntry=' + encodeURIComponent(newEntry), {}, config)
.then(function(response) {
that.refs[toEdit].saveChanges();
})
.catch(function(error) {
that.refs[toEdit].undoChanges();
that.refs.notification.handleError(error);
});
if (toEdit == 'LANGUAGE') {
this.props.updateLanguage(newEntry);
}
}
editUsername(newEntry) {
var that = this;
var config = {
headers: {
'X-AUTH-TOKEN': localStorage.getItem('jwt')
}
};
axios
.post('http://localhost:8081/user/edit?userName=' + encodeURIComponent(this.props.user.userName) + '&toEdit=NAME&newEntry=' + encodeURIComponent(newEntry), {}, config)
.then(function(response) {
that.props.logout();
})
.catch(function(error) {
that.refs.name.undoChanges(that.props.user.userName);
that.refs.notification.handleError(error);
});
}
updateImageName(imageName) {
this.props.updateImageName(imageName);
}
render() {
return (
<div>
<div className="editUserDetails" onClick={this.clearErrorMessage}>
<h1>{counterpart.translate('EDIT_PROFILE')}</h1>
<div className="summary">
<span className="name">{this.props.user.userName}</span>
<br />
<span className="bold">{counterpart.translate('MEMBER_SINCE')}: </span>
{moment(this.props.user.regDate).format('DD.MM.YYYY')}
<br />
<span className="bold">{counterpart.translate('RANK')}: </span>
{this.props.user.rank}
</div>
</div>
<FileChooseAndUploadButton imageId="edit-logo-img" imageFileName={this.props.user.imageFileName} updateImageName={this.updateImageName.bind(this)} />
<EditNameItem text={counterpart.translate('USERNAME')} content={this.props.user.userName} toEdit="NAME" editUsername={this.editUsername.bind(this)} ref="name" />
<EditItem text={counterpart.translate('ABOUT_ME')} content={this.props.user.aboutMe} toEdit="ABOUTME" editUser={this.editUser.bind(this)} ref="ABOUTME" />
<EditItem text={counterpart.translate('LOCATION')} content={this.props.user.location} toEdit="LOCATION" editUser={this.editUser.bind(this)} ref="LOCATION" />
<EditItem text={counterpart.translate('ORGANISATION')} content={this.props.user.organisation} toEdit="ORGANISATION" editUser={this.editUser.bind(this)} ref="ORGANISATION" />
<EditItem text={counterpart.translate('WEBSITE')} content={this.props.user.homepage} toEdit="HOMEPAGE" editUser={this.editUser.bind(this)} ref="HOMEPAGE" />
<EditDropdownItem text={counterpart.translate('LANGUAGE')} toEdit="LANGUAGE" content={this.props.user.lang} editUser={this.editUser.bind(this)} width="100" ref="LANGUAGE">
<option value="DEUTSCH">{counterpart.translate('GERMAN')}</option>
<option value="ENGLISH">{counterpart.translate('ENGLISH')}</option>
</EditDropdownItem>
<EditItem text={counterpart.translate('MAIL')} content={this.props.user.mail} toEdit="MAIL" editUser={this.editUser.bind(this)} ref="MAIL" />
<EditDropdownItem
text={counterpart.translate('TYPE')}
toEdit="ORGANIZATION_TYPE"
content={this.props.user.organizationType}
editUser={this.editUser.bind(this)}
width="180"
ref="ORGANIZATION_TYPE"
>
<option value="PRIVATE">{counterpart.translate('RANKING_TYPES.PRIVATE')}</option>
<option value="COMMERCIAL">{counterpart.translate('RANKING_TYPES.COMMERCIAL')}</option>
<option value="NONPROFIT">{counterpart.translate('RANKING_TYPES.NONPROFIT')}</option>
<option value="EDUCATIONAL">{counterpart.translate('RANKING_TYPES.EDUCATIONAL')}</option>
</EditDropdownItem>
<EditPasswordItem text={counterpart.translate('PASSWORD')} toEdit="PASSWORD" editUser={this.editUser.bind(this)} ref="PASSWORD" />
<div className="align-center bottomButton">
<IconButton text={counterpart.translate('VIEW')} glyphIcon="glyphicon-eye-open" onClick={this.showProfile.bind(this)} />
</div>
<Notification ref="notification" />
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
node_modules/react-slick/src/dots.js
|
DaveSpivey/muttwhat
|
'use strict';
import React from 'react';
import classnames from 'classnames';
var getDotCount = function (spec) {
var dots;
dots = Math.ceil(spec.slideCount / spec.slidesToScroll);
return dots;
};
export var Dots = React.createClass({
clickHandler: function (options, e) {
// In Autoplay the focus stays on clicked button even after transition
// to next slide. That only goes away by click somewhere outside
e.preventDefault();
this.props.clickHandler(options);
},
render: function () {
var dotCount = getDotCount({
slideCount: this.props.slideCount,
slidesToScroll: this.props.slidesToScroll
});
// Apply join & split to Array to pre-fill it for IE8
//
// Credit: http://stackoverflow.com/a/13735425/1849458
var dots = Array.apply(null, Array(dotCount + 1).join('0').split('')).map((x, i) => {
var leftBound = (i * this.props.slidesToScroll);
var rightBound = (i * this.props.slidesToScroll) + (this.props.slidesToScroll - 1);
var className = classnames({
'slick-active': (this.props.currentSlide >= leftBound) && (this.props.currentSlide <= rightBound)
});
var dotOptions = {
message: 'dots',
index: i,
slidesToScroll: this.props.slidesToScroll,
currentSlide: this.props.currentSlide
};
var onClick = this.clickHandler.bind(this, dotOptions);
return (
<li key={i} className={className}>
{React.cloneElement(this.props.customPaging(i), {onClick})}
</li>
);
});
return (
<ul className={this.props.dotsClass} style={{display: 'block'}}>
{dots}
</ul>
);
}
});
|
examples/nested/src/client/index.js
|
ericf/react-intl
|
import React from 'react';
import ReactDOM from 'react-dom';
import {addLocaleData, IntlProvider} from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import App from './components/app';
addLocaleData(enLocaleData);
const {locale, messages} = window.App;
ReactDOM.render(
<IntlProvider
locale={locale}
messages={messages.app}
>
<App getIntlMessages={(namespace) => messages[namespace]} />
</IntlProvider>,
document.getElementById('container')
);
|
docs/getting-started-chart/components/Client.js
|
reimagined/resolve
|
import React from 'react'
const Client = ({ selected, onClick }) => (
<g className="box-outer" data-selected={selected} onClick={onClick}>
<path className="box" d="M470 43H550V414H470V43Z" />
<path
className="caption"
d="M496.541 220.492C496.176 217.469 493.888 215.73 490.858 215.73C487.4 215.73 484.76 218.172 484.76 222.455C484.76 226.724 487.355 229.179 490.858 229.179C494.214 229.179 496.24 226.948 496.541 224.538L493.741 224.526C493.479 225.925 492.38 226.731 490.903 226.731C488.915 226.731 487.566 225.254 487.566 222.455C487.566 219.732 488.896 218.178 490.922 218.178C492.437 218.178 493.53 219.054 493.741 220.492H496.541ZM501.197 215.909H498.474V229H501.197V215.909ZM503.379 229H506.102V219.182H503.379V229ZM504.747 217.916C505.558 217.916 506.223 217.296 506.223 216.536C506.223 215.781 505.558 215.161 504.747 215.161C503.941 215.161 503.276 215.781 503.276 216.536C503.276 217.296 503.941 217.916 504.747 217.916ZM512.757 229.192C515.186 229.192 516.823 228.009 517.206 226.188L514.688 226.021C514.413 226.769 513.71 227.159 512.802 227.159C511.441 227.159 510.578 226.258 510.578 224.794V224.788H517.264V224.04C517.264 220.703 515.244 219.054 512.649 219.054C509.759 219.054 507.887 221.106 507.887 224.136C507.887 227.249 509.734 229.192 512.757 229.192ZM510.578 223.1C510.635 221.982 511.485 221.087 512.693 221.087C513.876 221.087 514.694 221.93 514.701 223.1H510.578ZM521.764 223.324C521.77 222.058 522.524 221.317 523.624 221.317C524.717 221.317 525.375 222.033 525.369 223.234V229H528.092V222.749C528.092 220.46 526.75 219.054 524.704 219.054C523.247 219.054 522.192 219.77 521.751 220.914H521.636V219.182H519.041V229H521.764V223.324ZM535.46 219.182H533.613V216.83H530.89V219.182H529.548V221.227H530.89V226.341C530.877 228.265 532.188 229.217 534.163 229.134C534.866 229.109 535.364 228.968 535.639 228.879L535.211 226.852C535.077 226.878 534.789 226.942 534.533 226.942C533.99 226.942 533.613 226.737 533.613 225.983V221.227H535.46V219.182Z"
/>
</g>
)
export default Client
|
app/javascript/flavours/glitch/features/status/components/detailed_status.js
|
im-in-space/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Avatar from 'flavours/glitch/components/avatar';
import DisplayName from 'flavours/glitch/components/display_name';
import StatusContent from 'flavours/glitch/components/status_content';
import MediaGallery from 'flavours/glitch/components/media_gallery';
import AttachmentList from 'flavours/glitch/components/attachment_list';
import { Link } from 'react-router-dom';
import { injectIntl, FormattedDate } from 'react-intl';
import Card from './card';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Video from 'flavours/glitch/features/video';
import Audio from 'flavours/glitch/features/audio';
import VisibilityIcon from 'flavours/glitch/components/status_visibility_icon';
import scheduleIdleTask from 'flavours/glitch/util/schedule_idle_task';
import classNames from 'classnames';
import PollContainer from 'flavours/glitch/containers/poll_container';
import Icon from 'flavours/glitch/components/icon';
import AnimatedNumber from 'flavours/glitch/components/animated_number';
import PictureInPicturePlaceholder from 'flavours/glitch/components/picture_in_picture_placeholder';
import EditedTimestamp from 'flavours/glitch/components/edited_timestamp';
export default @injectIntl
class DetailedStatus extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
settings: ImmutablePropTypes.map.isRequired,
onOpenMedia: PropTypes.func.isRequired,
onOpenVideo: PropTypes.func.isRequired,
onToggleHidden: PropTypes.func,
expanded: PropTypes.bool,
measureHeight: PropTypes.bool,
onHeightChange: PropTypes.func,
domain: PropTypes.string.isRequired,
compact: PropTypes.bool,
showMedia: PropTypes.bool,
usingPiP: PropTypes.bool,
onToggleMediaVisibility: PropTypes.func,
intl: PropTypes.object.isRequired,
};
state = {
height: null,
};
handleAccountClick = (e) => {
if (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey) && this.context.router) {
e.preventDefault();
let state = {...this.context.router.history.location.state};
state.mastodonBackSteps = (state.mastodonBackSteps || 0) + 1;
this.context.router.history.push(`/@${this.props.status.getIn(['account', 'acct'])}`, state);
}
e.stopPropagation();
}
parseClick = (e, destination) => {
if (e.button === 0 && !(e.ctrlKey || e.altKey || e.metaKey) && this.context.router) {
e.preventDefault();
let state = {...this.context.router.history.location.state};
state.mastodonBackSteps = (state.mastodonBackSteps || 0) + 1;
this.context.router.history.push(destination, state);
}
e.stopPropagation();
}
handleOpenVideo = (options) => {
this.props.onOpenVideo(this.props.status.getIn(['media_attachments', 0]), options);
}
_measureHeight (heightJustChanged) {
if (this.props.measureHeight && this.node) {
scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 }));
if (this.props.onHeightChange && heightJustChanged) {
this.props.onHeightChange();
}
}
}
setRef = c => {
this.node = c;
this._measureHeight();
}
componentDidUpdate (prevProps, prevState) {
this._measureHeight(prevState.height !== this.state.height);
}
handleChildUpdate = () => {
this._measureHeight();
}
handleModalLink = e => {
e.preventDefault();
let href;
if (e.target.nodeName !== 'A') {
href = e.target.parentNode.href;
} else {
href = e.target.href;
}
window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
}
render () {
const status = (this.props.status && this.props.status.get('reblog')) ? this.props.status.get('reblog') : this.props.status;
const { expanded, onToggleHidden, settings, usingPiP, intl } = this.props;
const outerStyle = { boxSizing: 'border-box' };
const { compact } = this.props;
if (!status) {
return null;
}
let media = [];
let mediaIcons = [];
let applicationLink = '';
let reblogLink = '';
let reblogIcon = 'retweet';
let favouriteLink = '';
let edited = '';
if (this.props.measureHeight) {
outerStyle.height = `${this.state.height}px`;
}
if (usingPiP) {
media.push(<PictureInPicturePlaceholder />);
mediaIcons.push('video-camera');
} else if (status.get('media_attachments').size > 0) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
media.push(<AttachmentList media={status.get('media_attachments')} />);
} else if (status.getIn(['media_attachments', 0, 'type']) === 'audio') {
const attachment = status.getIn(['media_attachments', 0]);
media.push(
<Audio
src={attachment.get('url')}
alt={attachment.get('description')}
duration={attachment.getIn(['meta', 'original', 'duration'], 0)}
poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])}
backgroundColor={attachment.getIn(['meta', 'colors', 'background'])}
foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])}
accentColor={attachment.getIn(['meta', 'colors', 'accent'])}
height={150}
/>,
);
mediaIcons.push('music');
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const attachment = status.getIn(['media_attachments', 0]);
media.push(
<Video
preview={attachment.get('preview_url')}
frameRate={attachment.getIn(['meta', 'original', 'frame_rate'])}
blurhash={attachment.get('blurhash')}
src={attachment.get('url')}
alt={attachment.get('description')}
inline
sensitive={status.get('sensitive')}
letterbox={settings.getIn(['media', 'letterbox'])}
fullwidth={settings.getIn(['media', 'fullwidth'])}
preventPlayback={!expanded}
onOpenVideo={this.handleOpenVideo}
autoplay
visible={this.props.showMedia}
onToggleVisibility={this.props.onToggleMediaVisibility}
/>,
);
mediaIcons.push('video-camera');
} else {
media.push(
<MediaGallery
standalone
sensitive={status.get('sensitive')}
media={status.get('media_attachments')}
letterbox={settings.getIn(['media', 'letterbox'])}
fullwidth={settings.getIn(['media', 'fullwidth'])}
hidden={!expanded}
onOpenMedia={this.props.onOpenMedia}
visible={this.props.showMedia}
onToggleVisibility={this.props.onToggleMediaVisibility}
/>,
);
mediaIcons.push('picture-o');
}
} else if (status.get('card')) {
media.push(<Card sensitive={status.get('sensitive')} onOpenMedia={this.props.onOpenMedia} card={status.get('card')} />);
mediaIcons.push('link');
}
if (status.get('poll')) {
media.push(<PollContainer pollId={status.get('poll')} />);
mediaIcons.push('tasks');
}
if (status.get('application')) {
applicationLink = <React.Fragment> · <a className='detailed-status__application' href={status.getIn(['application', 'website'])} target='_blank' rel='noopener noreferrer'>{status.getIn(['application', 'name'])}</a></React.Fragment>;
}
const visibilityLink = <React.Fragment> · <VisibilityIcon visibility={status.get('visibility')} /></React.Fragment>;
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (!['unlisted', 'public'].includes(status.get('visibility'))) {
reblogLink = null;
} else if (this.context.router) {
reblogLink = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<Link to={`/@${status.getIn(['account', 'acct'])}/${status.get('id')}/reblogs`} className='detailed-status__link'>
<Icon id={reblogIcon} />
<span className='detailed-status__reblogs'>
<AnimatedNumber value={status.get('reblogs_count')} />
</span>
</Link>
</React.Fragment>
);
} else {
reblogLink = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<a href={`/interact/${status.get('id')}?type=reblog`} className='detailed-status__link' onClick={this.handleModalLink}>
<Icon id={reblogIcon} />
<span className='detailed-status__reblogs'>
<AnimatedNumber value={status.get('reblogs_count')} />
</span>
</a>
</React.Fragment>
);
}
if (this.context.router) {
favouriteLink = (
<Link to={`/@${status.getIn(['account', 'acct'])}/${status.get('id')}/favourites`} className='detailed-status__link'>
<Icon id='star' />
<span className='detailed-status__favorites'>
<AnimatedNumber value={status.get('favourites_count')} />
</span>
</Link>
);
} else {
favouriteLink = (
<a href={`/interact/${status.get('id')}?type=favourite`} className='detailed-status__link' onClick={this.handleModalLink}>
<Icon id='star' />
<span className='detailed-status__favorites'>
<AnimatedNumber value={status.get('favourites_count')} />
</span>
</a>
);
}
if (status.get('edited_at')) {
edited = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<EditedTimestamp statusId={status.get('id')} timestamp={status.get('edited_at')} />
</React.Fragment>
);
}
return (
<div style={outerStyle}>
<div ref={this.setRef} className={classNames('detailed-status', `detailed-status-${status.get('visibility')}`, { compact })} data-status-by={status.getIn(['account', 'acct'])}>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='detailed-status__display-name'>
<div className='detailed-status__display-avatar'><Avatar account={status.get('account')} size={48} /></div>
<DisplayName account={status.get('account')} localDomain={this.props.domain} />
</a>
<StatusContent
status={status}
media={media}
mediaIcons={mediaIcons}
expanded={expanded}
collapsed={false}
onExpandedToggle={onToggleHidden}
parseClick={this.parseClick}
onUpdate={this.handleChildUpdate}
tagLinks={settings.get('tag_misleading_links')}
rewriteMentions={settings.get('rewrite_mentions')}
disabled
/>
<div className='detailed-status__meta'>
<a className='detailed-status__datetime' href={status.get('url')} target='_blank' rel='noopener noreferrer'>
<FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' />
</a>{edited}{visibilityLink}{applicationLink}{reblogLink} · {favouriteLink}
</div>
</div>
</div>
);
}
}
|
ajax/libs/babel-polyfill/6.9.0/polyfill.js
|
wout/cdnjs
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (global){
/*istanbul ignore next*/"use strict";
/*istanbul ignore next*/_dereq_(296);
/*istanbul ignore next*/_dereq_(2);
/*istanbul ignore next*/_dereq_(3);
/* eslint max-len: 0 */
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
}
global._babelPolyfill = true;
// Should be removed in the next major release:
var DEFINE_PROPERTY = "defineProperty";
function define(O, key, value) {
O[key] || Object[DEFINE_PROPERTY](O, key, {
writable: true,
configurable: true,
value: value
});
}
define(String.prototype, "padLeft", "".padStart);
define(String.prototype, "padRight", "".padEnd);
"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) {
[][key] && define(Array, key, Function.call.bind([][key]));
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"2":2,"296":296,"3":3}],2:[function(_dereq_,module,exports){
module.exports = _dereq_(297);
},{"297":297}],3:[function(_dereq_,module,exports){
_dereq_(121);
module.exports = _dereq_(24).RegExp.escape;
},{"121":121,"24":24}],4:[function(_dereq_,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],5:[function(_dereq_,module,exports){
var cof = _dereq_(19);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
},{"19":19}],6:[function(_dereq_,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = _dereq_(118)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)_dereq_(41)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
},{"118":118,"41":41}],7:[function(_dereq_,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],8:[function(_dereq_,module,exports){
var isObject = _dereq_(50);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"50":50}],9:[function(_dereq_,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = _dereq_(110)
, toIndex = _dereq_(106)
, toLength = _dereq_(109);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"106":106,"109":109,"110":110}],10:[function(_dereq_,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = _dereq_(110)
, toIndex = _dereq_(106)
, toLength = _dereq_(109);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
},{"106":106,"109":109,"110":110}],11:[function(_dereq_,module,exports){
var forOf = _dereq_(38);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"38":38}],12:[function(_dereq_,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = _dereq_(108)
, toLength = _dereq_(109)
, toIndex = _dereq_(106);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"106":106,"108":108,"109":109}],13:[function(_dereq_,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = _dereq_(26)
, IObject = _dereq_(46)
, toObject = _dereq_(110)
, toLength = _dereq_(109)
, asc = _dereq_(16);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"109":109,"110":110,"16":16,"26":26,"46":46}],14:[function(_dereq_,module,exports){
var aFunction = _dereq_(4)
, toObject = _dereq_(110)
, IObject = _dereq_(46)
, toLength = _dereq_(109);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"109":109,"110":110,"4":4,"46":46}],15:[function(_dereq_,module,exports){
var isObject = _dereq_(50)
, isArray = _dereq_(48)
, SPECIES = _dereq_(118)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"118":118,"48":48,"50":50}],16:[function(_dereq_,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = _dereq_(15);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"15":15}],17:[function(_dereq_,module,exports){
'use strict';
var aFunction = _dereq_(4)
, isObject = _dereq_(50)
, invoke = _dereq_(45)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
},{"4":4,"45":45,"50":50}],18:[function(_dereq_,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = _dereq_(19)
, TAG = _dereq_(118)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"118":118,"19":19}],19:[function(_dereq_,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],20:[function(_dereq_,module,exports){
'use strict';
var dP = _dereq_(68).f
, create = _dereq_(67)
, hide = _dereq_(41)
, redefineAll = _dereq_(87)
, ctx = _dereq_(26)
, anInstance = _dereq_(7)
, defined = _dereq_(28)
, forOf = _dereq_(38)
, $iterDefine = _dereq_(54)
, step = _dereq_(56)
, setSpecies = _dereq_(92)
, DESCRIPTORS = _dereq_(29)
, fastKey = _dereq_(63).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"26":26,"28":28,"29":29,"38":38,"41":41,"54":54,"56":56,"63":63,"67":67,"68":68,"7":7,"87":87,"92":92}],21:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = _dereq_(18)
, from = _dereq_(11);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"11":11,"18":18}],22:[function(_dereq_,module,exports){
'use strict';
var redefineAll = _dereq_(87)
, getWeak = _dereq_(63).getWeak
, anObject = _dereq_(8)
, isObject = _dereq_(50)
, anInstance = _dereq_(7)
, forOf = _dereq_(38)
, createArrayMethod = _dereq_(13)
, $has = _dereq_(40)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"13":13,"38":38,"40":40,"50":50,"63":63,"7":7,"8":8,"87":87}],23:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(39)
, $export = _dereq_(33)
, redefine = _dereq_(88)
, redefineAll = _dereq_(87)
, meta = _dereq_(63)
, forOf = _dereq_(38)
, anInstance = _dereq_(7)
, isObject = _dereq_(50)
, fails = _dereq_(35)
, $iterDetect = _dereq_(55)
, setToStringTag = _dereq_(93)
, inheritIfRequired = _dereq_(44);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"33":33,"35":35,"38":38,"39":39,"44":44,"50":50,"55":55,"63":63,"7":7,"87":87,"88":88,"93":93}],24:[function(_dereq_,module,exports){
var core = module.exports = {version: '2.3.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],25:[function(_dereq_,module,exports){
'use strict';
var $defineProperty = _dereq_(68)
, createDesc = _dereq_(86);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"68":68,"86":86}],26:[function(_dereq_,module,exports){
// optional / simple context binding
var aFunction = _dereq_(4);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"4":4}],27:[function(_dereq_,module,exports){
'use strict';
var anObject = _dereq_(8)
, toPrimitive = _dereq_(111)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
},{"111":111,"8":8}],28:[function(_dereq_,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],29:[function(_dereq_,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !_dereq_(35)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"35":35}],30:[function(_dereq_,module,exports){
var isObject = _dereq_(50)
, document = _dereq_(39).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"39":39,"50":50}],31:[function(_dereq_,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],32:[function(_dereq_,module,exports){
// all enumerable object keys, includes symbols
var getKeys = _dereq_(77)
, gOPS = _dereq_(74)
, pIE = _dereq_(78);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"74":74,"77":77,"78":78}],33:[function(_dereq_,module,exports){
var global = _dereq_(39)
, core = _dereq_(24)
, hide = _dereq_(41)
, redefine = _dereq_(88)
, ctx = _dereq_(26)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"24":24,"26":26,"39":39,"41":41,"88":88}],34:[function(_dereq_,module,exports){
var MATCH = _dereq_(118)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
},{"118":118}],35:[function(_dereq_,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],36:[function(_dereq_,module,exports){
'use strict';
var hide = _dereq_(41)
, redefine = _dereq_(88)
, fails = _dereq_(35)
, defined = _dereq_(28)
, wks = _dereq_(118);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
},{"118":118,"28":28,"35":35,"41":41,"88":88}],37:[function(_dereq_,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = _dereq_(8);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
},{"8":8}],38:[function(_dereq_,module,exports){
var ctx = _dereq_(26)
, call = _dereq_(52)
, isArrayIter = _dereq_(47)
, anObject = _dereq_(8)
, toLength = _dereq_(109)
, getIterFn = _dereq_(119);
module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
call(iterator, f, step.value, entries);
}
};
},{"109":109,"119":119,"26":26,"47":47,"52":52,"8":8}],39:[function(_dereq_,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],40:[function(_dereq_,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],41:[function(_dereq_,module,exports){
var dP = _dereq_(68)
, createDesc = _dereq_(86);
module.exports = _dereq_(29) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"29":29,"68":68,"86":86}],42:[function(_dereq_,module,exports){
module.exports = _dereq_(39).document && document.documentElement;
},{"39":39}],43:[function(_dereq_,module,exports){
module.exports = !_dereq_(29) && !_dereq_(35)(function(){
return Object.defineProperty(_dereq_(30)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"29":29,"30":30,"35":35}],44:[function(_dereq_,module,exports){
var isObject = _dereq_(50)
, setPrototypeOf = _dereq_(91).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
},{"50":50,"91":91}],45:[function(_dereq_,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],46:[function(_dereq_,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = _dereq_(19);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"19":19}],47:[function(_dereq_,module,exports){
// check on default Array iterator
var Iterators = _dereq_(57)
, ITERATOR = _dereq_(118)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"118":118,"57":57}],48:[function(_dereq_,module,exports){
// 7.2.2 IsArray(argument)
var cof = _dereq_(19);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"19":19}],49:[function(_dereq_,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = _dereq_(50)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"50":50}],50:[function(_dereq_,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],51:[function(_dereq_,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = _dereq_(50)
, cof = _dereq_(19)
, MATCH = _dereq_(118)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"118":118,"19":19,"50":50}],52:[function(_dereq_,module,exports){
// call something on iterator step with safe closing on error
var anObject = _dereq_(8);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"8":8}],53:[function(_dereq_,module,exports){
'use strict';
var create = _dereq_(67)
, descriptor = _dereq_(86)
, setToStringTag = _dereq_(93)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
_dereq_(41)(IteratorPrototype, _dereq_(118)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"118":118,"41":41,"67":67,"86":86,"93":93}],54:[function(_dereq_,module,exports){
'use strict';
var LIBRARY = _dereq_(59)
, $export = _dereq_(33)
, redefine = _dereq_(88)
, hide = _dereq_(41)
, has = _dereq_(40)
, Iterators = _dereq_(57)
, $iterCreate = _dereq_(53)
, setToStringTag = _dereq_(93)
, getPrototypeOf = _dereq_(75)
, ITERATOR = _dereq_(118)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"118":118,"33":33,"40":40,"41":41,"53":53,"57":57,"59":59,"75":75,"88":88,"93":93}],55:[function(_dereq_,module,exports){
var ITERATOR = _dereq_(118)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"118":118}],56:[function(_dereq_,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],57:[function(_dereq_,module,exports){
module.exports = {};
},{}],58:[function(_dereq_,module,exports){
var getKeys = _dereq_(77)
, toIObject = _dereq_(108);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"108":108,"77":77}],59:[function(_dereq_,module,exports){
module.exports = false;
},{}],60:[function(_dereq_,module,exports){
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
},{}],61:[function(_dereq_,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],62:[function(_dereq_,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],63:[function(_dereq_,module,exports){
var META = _dereq_(115)('meta')
, isObject = _dereq_(50)
, has = _dereq_(40)
, setDesc = _dereq_(68).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !_dereq_(35)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"115":115,"35":35,"40":40,"50":50,"68":68}],64:[function(_dereq_,module,exports){
var Map = _dereq_(151)
, $export = _dereq_(33)
, shared = _dereq_(95)('metadata')
, store = shared.store || (shared.store = new (_dereq_(257)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
},{"151":151,"257":257,"33":33,"95":95}],65:[function(_dereq_,module,exports){
var global = _dereq_(39)
, macrotask = _dereq_(105).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = _dereq_(19)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
},{"105":105,"19":19,"39":39}],66:[function(_dereq_,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = _dereq_(77)
, gOPS = _dereq_(74)
, pIE = _dereq_(78)
, toObject = _dereq_(110)
, IObject = _dereq_(46)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || _dereq_(35)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
},{"110":110,"35":35,"46":46,"74":74,"77":77,"78":78}],67:[function(_dereq_,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = _dereq_(8)
, dPs = _dereq_(69)
, enumBugKeys = _dereq_(31)
, IE_PROTO = _dereq_(94)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = _dereq_(30)('iframe')
, i = enumBugKeys.length
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
_dereq_(42).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"30":30,"31":31,"42":42,"69":69,"8":8,"94":94}],68:[function(_dereq_,module,exports){
var anObject = _dereq_(8)
, IE8_DOM_DEFINE = _dereq_(43)
, toPrimitive = _dereq_(111)
, dP = Object.defineProperty;
exports.f = _dereq_(29) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"111":111,"29":29,"43":43,"8":8}],69:[function(_dereq_,module,exports){
var dP = _dereq_(68)
, anObject = _dereq_(8)
, getKeys = _dereq_(77);
module.exports = _dereq_(29) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"29":29,"68":68,"77":77,"8":8}],70:[function(_dereq_,module,exports){
// Forced replacement prototype accessors methods
module.exports = _dereq_(59)|| !_dereq_(35)(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete _dereq_(39)[K];
});
},{"35":35,"39":39,"59":59}],71:[function(_dereq_,module,exports){
var pIE = _dereq_(78)
, createDesc = _dereq_(86)
, toIObject = _dereq_(108)
, toPrimitive = _dereq_(111)
, has = _dereq_(40)
, IE8_DOM_DEFINE = _dereq_(43)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = _dereq_(29) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"108":108,"111":111,"29":29,"40":40,"43":43,"78":78,"86":86}],72:[function(_dereq_,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = _dereq_(108)
, gOPN = _dereq_(73).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"108":108,"73":73}],73:[function(_dereq_,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = _dereq_(76)
, hiddenKeys = _dereq_(31).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"31":31,"76":76}],74:[function(_dereq_,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],75:[function(_dereq_,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = _dereq_(40)
, toObject = _dereq_(110)
, IE_PROTO = _dereq_(94)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"110":110,"40":40,"94":94}],76:[function(_dereq_,module,exports){
var has = _dereq_(40)
, toIObject = _dereq_(108)
, arrayIndexOf = _dereq_(12)(false)
, IE_PROTO = _dereq_(94)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"108":108,"12":12,"40":40,"94":94}],77:[function(_dereq_,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = _dereq_(76)
, enumBugKeys = _dereq_(31);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"31":31,"76":76}],78:[function(_dereq_,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],79:[function(_dereq_,module,exports){
// most Object methods by ES6 should accept primitives
var $export = _dereq_(33)
, core = _dereq_(24)
, fails = _dereq_(35);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"24":24,"33":33,"35":35}],80:[function(_dereq_,module,exports){
var getKeys = _dereq_(77)
, toIObject = _dereq_(108)
, isEnum = _dereq_(78).f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"108":108,"77":77,"78":78}],81:[function(_dereq_,module,exports){
// all object keys, includes non-enumerable and symbols
var gOPN = _dereq_(73)
, gOPS = _dereq_(74)
, anObject = _dereq_(8)
, Reflect = _dereq_(39).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"39":39,"73":73,"74":74,"8":8}],82:[function(_dereq_,module,exports){
var $parseFloat = _dereq_(39).parseFloat
, $trim = _dereq_(103).trim;
module.exports = 1 / $parseFloat(_dereq_(104) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
},{"103":103,"104":104,"39":39}],83:[function(_dereq_,module,exports){
var $parseInt = _dereq_(39).parseInt
, $trim = _dereq_(103).trim
, ws = _dereq_(104)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
},{"103":103,"104":104,"39":39}],84:[function(_dereq_,module,exports){
'use strict';
var path = _dereq_(85)
, invoke = _dereq_(45)
, aFunction = _dereq_(4);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
},{"4":4,"45":45,"85":85}],85:[function(_dereq_,module,exports){
module.exports = _dereq_(39);
},{"39":39}],86:[function(_dereq_,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],87:[function(_dereq_,module,exports){
var redefine = _dereq_(88);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
},{"88":88}],88:[function(_dereq_,module,exports){
var global = _dereq_(39)
, hide = _dereq_(41)
, has = _dereq_(40)
, SRC = _dereq_(115)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
_dereq_(24).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"115":115,"24":24,"39":39,"40":40,"41":41}],89:[function(_dereq_,module,exports){
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
},{}],90:[function(_dereq_,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],91:[function(_dereq_,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = _dereq_(50)
, anObject = _dereq_(8);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = _dereq_(26)(Function.call, _dereq_(71).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"26":26,"50":50,"71":71,"8":8}],92:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(39)
, dP = _dereq_(68)
, DESCRIPTORS = _dereq_(29)
, SPECIES = _dereq_(118)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"118":118,"29":29,"39":39,"68":68}],93:[function(_dereq_,module,exports){
var def = _dereq_(68).f
, has = _dereq_(40)
, TAG = _dereq_(118)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"118":118,"40":40,"68":68}],94:[function(_dereq_,module,exports){
var shared = _dereq_(95)('keys')
, uid = _dereq_(115);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"115":115,"95":95}],95:[function(_dereq_,module,exports){
var global = _dereq_(39)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"39":39}],96:[function(_dereq_,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = _dereq_(8)
, aFunction = _dereq_(4)
, SPECIES = _dereq_(118)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"118":118,"4":4,"8":8}],97:[function(_dereq_,module,exports){
var fails = _dereq_(35);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
},{"35":35}],98:[function(_dereq_,module,exports){
var toInteger = _dereq_(107)
, defined = _dereq_(28);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"107":107,"28":28}],99:[function(_dereq_,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = _dereq_(51)
, defined = _dereq_(28);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"28":28,"51":51}],100:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, fails = _dereq_(35)
, defined = _dereq_(28)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
},{"28":28,"33":33,"35":35}],101:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = _dereq_(109)
, repeat = _dereq_(102)
, defined = _dereq_(28);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"102":102,"109":109,"28":28}],102:[function(_dereq_,module,exports){
'use strict';
var toInteger = _dereq_(107)
, defined = _dereq_(28);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
},{"107":107,"28":28}],103:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, defined = _dereq_(28)
, fails = _dereq_(35)
, spaces = _dereq_(104)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"104":104,"28":28,"33":33,"35":35}],104:[function(_dereq_,module,exports){
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
},{}],105:[function(_dereq_,module,exports){
var ctx = _dereq_(26)
, invoke = _dereq_(45)
, html = _dereq_(42)
, cel = _dereq_(30)
, global = _dereq_(39)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(_dereq_(19)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"19":19,"26":26,"30":30,"39":39,"42":42,"45":45}],106:[function(_dereq_,module,exports){
var toInteger = _dereq_(107)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"107":107}],107:[function(_dereq_,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],108:[function(_dereq_,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = _dereq_(46)
, defined = _dereq_(28);
module.exports = function(it){
return IObject(defined(it));
};
},{"28":28,"46":46}],109:[function(_dereq_,module,exports){
// 7.1.15 ToLength
var toInteger = _dereq_(107)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"107":107}],110:[function(_dereq_,module,exports){
// 7.1.13 ToObject(argument)
var defined = _dereq_(28);
module.exports = function(it){
return Object(defined(it));
};
},{"28":28}],111:[function(_dereq_,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = _dereq_(50);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"50":50}],112:[function(_dereq_,module,exports){
'use strict';
if(_dereq_(29)){
var LIBRARY = _dereq_(59)
, global = _dereq_(39)
, fails = _dereq_(35)
, $export = _dereq_(33)
, $typed = _dereq_(114)
, $buffer = _dereq_(113)
, ctx = _dereq_(26)
, anInstance = _dereq_(7)
, propertyDesc = _dereq_(86)
, hide = _dereq_(41)
, redefineAll = _dereq_(87)
, isInteger = _dereq_(49)
, toInteger = _dereq_(107)
, toLength = _dereq_(109)
, toIndex = _dereq_(106)
, toPrimitive = _dereq_(111)
, has = _dereq_(40)
, same = _dereq_(90)
, classof = _dereq_(18)
, isObject = _dereq_(50)
, toObject = _dereq_(110)
, isArrayIter = _dereq_(47)
, create = _dereq_(67)
, getPrototypeOf = _dereq_(75)
, gOPN = _dereq_(73).f
, isIterable = _dereq_(120)
, getIterFn = _dereq_(119)
, uid = _dereq_(115)
, wks = _dereq_(118)
, createArrayMethod = _dereq_(13)
, createArrayIncludes = _dereq_(12)
, speciesConstructor = _dereq_(96)
, ArrayIterators = _dereq_(132)
, Iterators = _dereq_(57)
, $iterDetect = _dereq_(55)
, setSpecies = _dereq_(92)
, arrayFill = _dereq_(10)
, arrayCopyWithin = _dereq_(9)
, $DP = _dereq_(68)
, $GOPD = _dereq_(71)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
},{"10":10,"106":106,"107":107,"109":109,"110":110,"111":111,"113":113,"114":114,"115":115,"118":118,"119":119,"12":12,"120":120,"13":13,"132":132,"18":18,"26":26,"29":29,"33":33,"35":35,"39":39,"40":40,"41":41,"47":47,"49":49,"50":50,"55":55,"57":57,"59":59,"67":67,"68":68,"7":7,"71":71,"73":73,"75":75,"86":86,"87":87,"9":9,"90":90,"92":92,"96":96}],113:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(39)
, DESCRIPTORS = _dereq_(29)
, LIBRARY = _dereq_(59)
, $typed = _dereq_(114)
, hide = _dereq_(41)
, redefineAll = _dereq_(87)
, fails = _dereq_(35)
, anInstance = _dereq_(7)
, toInteger = _dereq_(107)
, toLength = _dereq_(109)
, gOPN = _dereq_(73).f
, dP = _dereq_(68).f
, arrayFill = _dereq_(10)
, setToStringTag = _dereq_(93)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, parseInt = global.parseInt
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, min = Math.min
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
},{"10":10,"107":107,"109":109,"114":114,"29":29,"35":35,"39":39,"41":41,"59":59,"68":68,"7":7,"73":73,"87":87,"93":93}],114:[function(_dereq_,module,exports){
var global = _dereq_(39)
, hide = _dereq_(41)
, uid = _dereq_(115)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
},{"115":115,"39":39,"41":41}],115:[function(_dereq_,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],116:[function(_dereq_,module,exports){
var global = _dereq_(39)
, core = _dereq_(24)
, LIBRARY = _dereq_(59)
, wksExt = _dereq_(117)
, defineProperty = _dereq_(68).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"117":117,"24":24,"39":39,"59":59,"68":68}],117:[function(_dereq_,module,exports){
exports.f = _dereq_(118);
},{"118":118}],118:[function(_dereq_,module,exports){
var store = _dereq_(95)('wks')
, uid = _dereq_(115)
, Symbol = _dereq_(39).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"115":115,"39":39,"95":95}],119:[function(_dereq_,module,exports){
var classof = _dereq_(18)
, ITERATOR = _dereq_(118)('iterator')
, Iterators = _dereq_(57);
module.exports = _dereq_(24).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"118":118,"18":18,"24":24,"57":57}],120:[function(_dereq_,module,exports){
var classof = _dereq_(18)
, ITERATOR = _dereq_(118)('iterator')
, Iterators = _dereq_(57);
module.exports = _dereq_(24).isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
},{"118":118,"18":18,"24":24,"57":57}],121:[function(_dereq_,module,exports){
// https://github.com/benjamingr/RexExp.escape
var $export = _dereq_(33)
, $re = _dereq_(89)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
},{"33":33,"89":89}],122:[function(_dereq_,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = _dereq_(33);
$export($export.P, 'Array', {copyWithin: _dereq_(9)});
_dereq_(6)('copyWithin');
},{"33":33,"6":6,"9":9}],123:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $every = _dereq_(13)(4);
$export($export.P + $export.F * !_dereq_(97)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
},{"13":13,"33":33,"97":97}],124:[function(_dereq_,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = _dereq_(33);
$export($export.P, 'Array', {fill: _dereq_(10)});
_dereq_(6)('fill');
},{"10":10,"33":33,"6":6}],125:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $filter = _dereq_(13)(2);
$export($export.P + $export.F * !_dereq_(97)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
},{"13":13,"33":33,"97":97}],126:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = _dereq_(33)
, $find = _dereq_(13)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(6)(KEY);
},{"13":13,"33":33,"6":6}],127:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = _dereq_(33)
, $find = _dereq_(13)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(6)(KEY);
},{"13":13,"33":33,"6":6}],128:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $forEach = _dereq_(13)(0)
, STRICT = _dereq_(97)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"13":13,"33":33,"97":97}],129:[function(_dereq_,module,exports){
'use strict';
var ctx = _dereq_(26)
, $export = _dereq_(33)
, toObject = _dereq_(110)
, call = _dereq_(52)
, isArrayIter = _dereq_(47)
, toLength = _dereq_(109)
, createProperty = _dereq_(25)
, getIterFn = _dereq_(119);
$export($export.S + $export.F * !_dereq_(55)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"109":109,"110":110,"119":119,"25":25,"26":26,"33":33,"47":47,"52":52,"55":55}],130:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $indexOf = _dereq_(12)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(97)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"12":12,"33":33,"97":97}],131:[function(_dereq_,module,exports){
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = _dereq_(33);
$export($export.S, 'Array', {isArray: _dereq_(48)});
},{"33":33,"48":48}],132:[function(_dereq_,module,exports){
'use strict';
var addToUnscopables = _dereq_(6)
, step = _dereq_(56)
, Iterators = _dereq_(57)
, toIObject = _dereq_(108);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = _dereq_(54)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"108":108,"54":54,"56":56,"57":57,"6":6}],133:[function(_dereq_,module,exports){
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = _dereq_(33)
, toIObject = _dereq_(108)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (_dereq_(46) != Object || !_dereq_(97)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
},{"108":108,"33":33,"46":46,"97":97}],134:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toIObject = _dereq_(108)
, toInteger = _dereq_(107)
, toLength = _dereq_(109)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(97)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
},{"107":107,"108":108,"109":109,"33":33,"97":97}],135:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $map = _dereq_(13)(1);
$export($export.P + $export.F * !_dereq_(97)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
},{"13":13,"33":33,"97":97}],136:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, createProperty = _dereq_(25);
// WebKit Array.of isn't generic
$export($export.S + $export.F * _dereq_(35)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
},{"25":25,"33":33,"35":35}],137:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $reduce = _dereq_(14);
$export($export.P + $export.F * !_dereq_(97)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"14":14,"33":33,"97":97}],138:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $reduce = _dereq_(14);
$export($export.P + $export.F * !_dereq_(97)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
},{"14":14,"33":33,"97":97}],139:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, html = _dereq_(42)
, cof = _dereq_(19)
, toIndex = _dereq_(106)
, toLength = _dereq_(109)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * _dereq_(35)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
},{"106":106,"109":109,"19":19,"33":33,"35":35,"42":42}],140:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $some = _dereq_(13)(3);
$export($export.P + $export.F * !_dereq_(97)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
},{"13":13,"33":33,"97":97}],141:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, aFunction = _dereq_(4)
, toObject = _dereq_(110)
, fails = _dereq_(35)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !_dereq_(97)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
},{"110":110,"33":33,"35":35,"4":4,"97":97}],142:[function(_dereq_,module,exports){
_dereq_(92)('Array');
},{"92":92}],143:[function(_dereq_,module,exports){
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = _dereq_(33);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
},{"33":33}],144:[function(_dereq_,module,exports){
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = _dereq_(33)
, fails = _dereq_(35)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
},{"33":33,"35":35}],145:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toObject = _dereq_(110)
, toPrimitive = _dereq_(111);
$export($export.P + $export.F * _dereq_(35)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
},{"110":110,"111":111,"33":33,"35":35}],146:[function(_dereq_,module,exports){
var TO_PRIMITIVE = _dereq_(118)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))_dereq_(41)(proto, TO_PRIMITIVE, _dereq_(27));
},{"118":118,"27":27,"41":41}],147:[function(_dereq_,module,exports){
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
_dereq_(88)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
},{"88":88}],148:[function(_dereq_,module,exports){
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = _dereq_(33);
$export($export.P, 'Function', {bind: _dereq_(17)});
},{"17":17,"33":33}],149:[function(_dereq_,module,exports){
'use strict';
var isObject = _dereq_(50)
, getPrototypeOf = _dereq_(75)
, HAS_INSTANCE = _dereq_(118)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))_dereq_(68).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
},{"118":118,"50":50,"68":68,"75":75}],150:[function(_dereq_,module,exports){
var dP = _dereq_(68).f
, createDesc = _dereq_(86)
, has = _dereq_(40)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || _dereq_(29) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
},{"29":29,"40":40,"68":68,"86":86}],151:[function(_dereq_,module,exports){
'use strict';
var strong = _dereq_(20);
// 23.1 Map Objects
module.exports = _dereq_(23)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"20":20,"23":23}],152:[function(_dereq_,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = _dereq_(33)
, log1p = _dereq_(61)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"33":33,"61":61}],153:[function(_dereq_,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = _dereq_(33)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
},{"33":33}],154:[function(_dereq_,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = _dereq_(33)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"33":33}],155:[function(_dereq_,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = _dereq_(33)
, sign = _dereq_(62);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"33":33,"62":62}],156:[function(_dereq_,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"33":33}],157:[function(_dereq_,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = _dereq_(33)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"33":33}],158:[function(_dereq_,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = _dereq_(33)
, $expm1 = _dereq_(60);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
},{"33":33,"60":60}],159:[function(_dereq_,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = _dereq_(33)
, sign = _dereq_(62)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
},{"33":33,"62":62}],160:[function(_dereq_,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = _dereq_(33)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"33":33}],161:[function(_dereq_,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = _dereq_(33)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * _dereq_(35)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"33":33,"35":35}],162:[function(_dereq_,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
},{"33":33}],163:[function(_dereq_,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {log1p: _dereq_(61)});
},{"33":33,"61":61}],164:[function(_dereq_,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
},{"33":33}],165:[function(_dereq_,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {sign: _dereq_(62)});
},{"33":33,"62":62}],166:[function(_dereq_,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = _dereq_(33)
, expm1 = _dereq_(60)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * _dereq_(35)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"33":33,"35":35,"60":60}],167:[function(_dereq_,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = _dereq_(33)
, expm1 = _dereq_(60)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"33":33,"60":60}],168:[function(_dereq_,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = _dereq_(33);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"33":33}],169:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_(39)
, has = _dereq_(40)
, cof = _dereq_(19)
, inheritIfRequired = _dereq_(44)
, toPrimitive = _dereq_(111)
, fails = _dereq_(35)
, gOPN = _dereq_(73).f
, gOPD = _dereq_(71).f
, dP = _dereq_(68).f
, $trim = _dereq_(103).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(_dereq_(67)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = _dereq_(29) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
_dereq_(88)(global, NUMBER, $Number);
}
},{"103":103,"111":111,"19":19,"29":29,"35":35,"39":39,"40":40,"44":44,"67":67,"68":68,"71":71,"73":73,"88":88}],170:[function(_dereq_,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = _dereq_(33);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
},{"33":33}],171:[function(_dereq_,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = _dereq_(33)
, _isFinite = _dereq_(39).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
},{"33":33,"39":39}],172:[function(_dereq_,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = _dereq_(33);
$export($export.S, 'Number', {isInteger: _dereq_(49)});
},{"33":33,"49":49}],173:[function(_dereq_,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = _dereq_(33);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
},{"33":33}],174:[function(_dereq_,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = _dereq_(33)
, isInteger = _dereq_(49)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"33":33,"49":49}],175:[function(_dereq_,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = _dereq_(33);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
},{"33":33}],176:[function(_dereq_,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = _dereq_(33);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
},{"33":33}],177:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, $parseFloat = _dereq_(82);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
},{"33":33,"82":82}],178:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, $parseInt = _dereq_(83);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
},{"33":33,"83":83}],179:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, anInstance = _dereq_(7)
, toInteger = _dereq_(107)
, aNumberValue = _dereq_(5)
, repeat = _dereq_(102)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !_dereq_(35)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
},{"102":102,"107":107,"33":33,"35":35,"5":5,"7":7}],180:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $fails = _dereq_(35)
, aNumberValue = _dereq_(5)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
},{"33":33,"35":35,"5":5}],181:[function(_dereq_,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = _dereq_(33);
$export($export.S + $export.F, 'Object', {assign: _dereq_(66)});
},{"33":33,"66":66}],182:[function(_dereq_,module,exports){
var $export = _dereq_(33)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: _dereq_(67)});
},{"33":33,"67":67}],183:[function(_dereq_,module,exports){
var $export = _dereq_(33);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !_dereq_(29), 'Object', {defineProperties: _dereq_(69)});
},{"29":29,"33":33,"69":69}],184:[function(_dereq_,module,exports){
var $export = _dereq_(33);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !_dereq_(29), 'Object', {defineProperty: _dereq_(68).f});
},{"29":29,"33":33,"68":68}],185:[function(_dereq_,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = _dereq_(50)
, meta = _dereq_(63).onFreeze;
_dereq_(79)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"50":50,"63":63,"79":79}],186:[function(_dereq_,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = _dereq_(108)
, $getOwnPropertyDescriptor = _dereq_(71).f;
_dereq_(79)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"108":108,"71":71,"79":79}],187:[function(_dereq_,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
_dereq_(79)('getOwnPropertyNames', function(){
return _dereq_(72).f;
});
},{"72":72,"79":79}],188:[function(_dereq_,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = _dereq_(110)
, $getPrototypeOf = _dereq_(75);
_dereq_(79)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"110":110,"75":75,"79":79}],189:[function(_dereq_,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = _dereq_(50);
_dereq_(79)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"50":50,"79":79}],190:[function(_dereq_,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = _dereq_(50);
_dereq_(79)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"50":50,"79":79}],191:[function(_dereq_,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = _dereq_(50);
_dereq_(79)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"50":50,"79":79}],192:[function(_dereq_,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = _dereq_(33);
$export($export.S, 'Object', {is: _dereq_(90)});
},{"33":33,"90":90}],193:[function(_dereq_,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = _dereq_(110)
, $keys = _dereq_(77);
_dereq_(79)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"110":110,"77":77,"79":79}],194:[function(_dereq_,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = _dereq_(50)
, meta = _dereq_(63).onFreeze;
_dereq_(79)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
},{"50":50,"63":63,"79":79}],195:[function(_dereq_,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = _dereq_(50)
, meta = _dereq_(63).onFreeze;
_dereq_(79)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
},{"50":50,"63":63,"79":79}],196:[function(_dereq_,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = _dereq_(33);
$export($export.S, 'Object', {setPrototypeOf: _dereq_(91).set});
},{"33":33,"91":91}],197:[function(_dereq_,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = _dereq_(18)
, test = {};
test[_dereq_(118)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
_dereq_(88)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
},{"118":118,"18":18,"88":88}],198:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, $parseFloat = _dereq_(82);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
},{"33":33,"82":82}],199:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, $parseInt = _dereq_(83);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
},{"33":33,"83":83}],200:[function(_dereq_,module,exports){
'use strict';
var LIBRARY = _dereq_(59)
, global = _dereq_(39)
, ctx = _dereq_(26)
, classof = _dereq_(18)
, $export = _dereq_(33)
, isObject = _dereq_(50)
, anObject = _dereq_(8)
, aFunction = _dereq_(4)
, anInstance = _dereq_(7)
, forOf = _dereq_(38)
, setProto = _dereq_(91).set
, speciesConstructor = _dereq_(96)
, task = _dereq_(105).set
, microtask = _dereq_(65)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[_dereq_(118)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = _dereq_(87)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
_dereq_(93)($Promise, PROMISE);
_dereq_(92)(PROMISE);
Wrapper = _dereq_(24)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && _dereq_(55)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"105":105,"118":118,"18":18,"24":24,"26":26,"33":33,"38":38,"39":39,"4":4,"50":50,"55":55,"59":59,"65":65,"7":7,"8":8,"87":87,"91":91,"92":92,"93":93,"96":96}],201:[function(_dereq_,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = _dereq_(33)
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(target, thisArgument, argumentsList);
}
});
},{"33":33}],202:[function(_dereq_,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = _dereq_(33)
, create = _dereq_(67)
, aFunction = _dereq_(4)
, anObject = _dereq_(8)
, isObject = _dereq_(50)
, bind = _dereq_(17);
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * _dereq_(35)(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
if(args != undefined)switch(anObject(args).length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"17":17,"33":33,"35":35,"4":4,"50":50,"67":67,"8":8}],203:[function(_dereq_,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = _dereq_(68)
, $export = _dereq_(33)
, anObject = _dereq_(8)
, toPrimitive = _dereq_(111);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * _dereq_(35)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
},{"111":111,"33":33,"35":35,"68":68,"8":8}],204:[function(_dereq_,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = _dereq_(33)
, gOPD = _dereq_(71).f
, anObject = _dereq_(8);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"33":33,"71":71,"8":8}],205:[function(_dereq_,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = _dereq_(33)
, anObject = _dereq_(8);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
_dereq_(53)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
},{"33":33,"53":53,"8":8}],206:[function(_dereq_,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = _dereq_(71)
, $export = _dereq_(33)
, anObject = _dereq_(8);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
},{"33":33,"71":71,"8":8}],207:[function(_dereq_,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = _dereq_(33)
, getProto = _dereq_(75)
, anObject = _dereq_(8);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
},{"33":33,"75":75,"8":8}],208:[function(_dereq_,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = _dereq_(71)
, getPrototypeOf = _dereq_(75)
, has = _dereq_(40)
, $export = _dereq_(33)
, isObject = _dereq_(50)
, anObject = _dereq_(8);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
},{"33":33,"40":40,"50":50,"71":71,"75":75,"8":8}],209:[function(_dereq_,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = _dereq_(33);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
},{"33":33}],210:[function(_dereq_,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = _dereq_(33)
, anObject = _dereq_(8)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"33":33,"8":8}],211:[function(_dereq_,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = _dereq_(33);
$export($export.S, 'Reflect', {ownKeys: _dereq_(81)});
},{"33":33,"81":81}],212:[function(_dereq_,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = _dereq_(33)
, anObject = _dereq_(8)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
},{"33":33,"8":8}],213:[function(_dereq_,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = _dereq_(33)
, setProto = _dereq_(91);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
},{"33":33,"91":91}],214:[function(_dereq_,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = _dereq_(68)
, gOPD = _dereq_(71)
, getPrototypeOf = _dereq_(75)
, has = _dereq_(40)
, $export = _dereq_(33)
, createDesc = _dereq_(86)
, anObject = _dereq_(8)
, isObject = _dereq_(50);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
},{"33":33,"40":40,"50":50,"68":68,"71":71,"75":75,"8":8,"86":86}],215:[function(_dereq_,module,exports){
var global = _dereq_(39)
, inheritIfRequired = _dereq_(44)
, dP = _dereq_(68).f
, gOPN = _dereq_(73).f
, isRegExp = _dereq_(51)
, $flags = _dereq_(37)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(_dereq_(29) && (!CORRECT_NEW || _dereq_(35)(function(){
re2[_dereq_(118)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
_dereq_(88)(global, 'RegExp', $RegExp);
}
_dereq_(92)('RegExp');
},{"118":118,"29":29,"35":35,"37":37,"39":39,"44":44,"51":51,"68":68,"73":73,"88":88,"92":92}],216:[function(_dereq_,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
if(_dereq_(29) && /./g.flags != 'g')_dereq_(68).f(RegExp.prototype, 'flags', {
configurable: true,
get: _dereq_(37)
});
},{"29":29,"37":37,"68":68}],217:[function(_dereq_,module,exports){
// @@match logic
_dereq_(36)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
},{"36":36}],218:[function(_dereq_,module,exports){
// @@replace logic
_dereq_(36)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
},{"36":36}],219:[function(_dereq_,module,exports){
// @@search logic
_dereq_(36)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
},{"36":36}],220:[function(_dereq_,module,exports){
// @@split logic
_dereq_(36)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = _dereq_(51)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
},{"36":36,"51":51}],221:[function(_dereq_,module,exports){
'use strict';
_dereq_(216);
var anObject = _dereq_(8)
, $flags = _dereq_(37)
, DESCRIPTORS = _dereq_(29)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
_dereq_(88)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(_dereq_(35)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
},{"216":216,"29":29,"35":35,"37":37,"8":8,"88":88}],222:[function(_dereq_,module,exports){
'use strict';
var strong = _dereq_(20);
// 23.2 Set Objects
module.exports = _dereq_(23)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
},{"20":20,"23":23}],223:[function(_dereq_,module,exports){
'use strict';
// B.2.3.2 String.prototype.anchor(name)
_dereq_(100)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
},{"100":100}],224:[function(_dereq_,module,exports){
'use strict';
// B.2.3.3 String.prototype.big()
_dereq_(100)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
},{"100":100}],225:[function(_dereq_,module,exports){
'use strict';
// B.2.3.4 String.prototype.blink()
_dereq_(100)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
},{"100":100}],226:[function(_dereq_,module,exports){
'use strict';
// B.2.3.5 String.prototype.bold()
_dereq_(100)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
},{"100":100}],227:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $at = _dereq_(98)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
},{"33":33,"98":98}],228:[function(_dereq_,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = _dereq_(33)
, toLength = _dereq_(109)
, context = _dereq_(99)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * _dereq_(34)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"109":109,"33":33,"34":34,"99":99}],229:[function(_dereq_,module,exports){
'use strict';
// B.2.3.6 String.prototype.fixed()
_dereq_(100)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
},{"100":100}],230:[function(_dereq_,module,exports){
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
_dereq_(100)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
},{"100":100}],231:[function(_dereq_,module,exports){
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
_dereq_(100)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
},{"100":100}],232:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, toIndex = _dereq_(106)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"106":106,"33":33}],233:[function(_dereq_,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = _dereq_(33)
, context = _dereq_(99)
, INCLUDES = 'includes';
$export($export.P + $export.F * _dereq_(34)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"33":33,"34":34,"99":99}],234:[function(_dereq_,module,exports){
'use strict';
// B.2.3.9 String.prototype.italics()
_dereq_(100)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
},{"100":100}],235:[function(_dereq_,module,exports){
'use strict';
var $at = _dereq_(98)(true);
// 21.1.3.27 String.prototype[@@iterator]()
_dereq_(54)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"54":54,"98":98}],236:[function(_dereq_,module,exports){
'use strict';
// B.2.3.10 String.prototype.link(url)
_dereq_(100)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
},{"100":100}],237:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, toIObject = _dereq_(108)
, toLength = _dereq_(109);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
},{"108":108,"109":109,"33":33}],238:[function(_dereq_,module,exports){
var $export = _dereq_(33);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: _dereq_(102)
});
},{"102":102,"33":33}],239:[function(_dereq_,module,exports){
'use strict';
// B.2.3.11 String.prototype.small()
_dereq_(100)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
},{"100":100}],240:[function(_dereq_,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = _dereq_(33)
, toLength = _dereq_(109)
, context = _dereq_(99)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * _dereq_(34)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"109":109,"33":33,"34":34,"99":99}],241:[function(_dereq_,module,exports){
'use strict';
// B.2.3.12 String.prototype.strike()
_dereq_(100)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
},{"100":100}],242:[function(_dereq_,module,exports){
'use strict';
// B.2.3.13 String.prototype.sub()
_dereq_(100)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
},{"100":100}],243:[function(_dereq_,module,exports){
'use strict';
// B.2.3.14 String.prototype.sup()
_dereq_(100)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
},{"100":100}],244:[function(_dereq_,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
_dereq_(103)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
},{"103":103}],245:[function(_dereq_,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = _dereq_(39)
, has = _dereq_(40)
, DESCRIPTORS = _dereq_(29)
, $export = _dereq_(33)
, redefine = _dereq_(88)
, META = _dereq_(63).KEY
, $fails = _dereq_(35)
, shared = _dereq_(95)
, setToStringTag = _dereq_(93)
, uid = _dereq_(115)
, wks = _dereq_(118)
, wksExt = _dereq_(117)
, wksDefine = _dereq_(116)
, keyOf = _dereq_(58)
, enumKeys = _dereq_(32)
, isArray = _dereq_(48)
, anObject = _dereq_(8)
, toIObject = _dereq_(108)
, toPrimitive = _dereq_(111)
, createDesc = _dereq_(86)
, _create = _dereq_(67)
, gOPNExt = _dereq_(72)
, $GOPD = _dereq_(71)
, $DP = _dereq_(68)
, $keys = _dereq_(77)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
var D = gOPD(it = toIObject(it), key = toPrimitive(key, true));
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]);
return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, {
configurable: true,
set: function(value){
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
}
});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
_dereq_(73).f = gOPNExt.f = $getOwnPropertyNames;
_dereq_(78).f = $propertyIsEnumerable;
_dereq_(74).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !_dereq_(59)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_(41)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"108":108,"111":111,"115":115,"116":116,"117":117,"118":118,"29":29,"32":32,"33":33,"35":35,"39":39,"40":40,"41":41,"48":48,"58":58,"59":59,"63":63,"67":67,"68":68,"71":71,"72":72,"73":73,"74":74,"77":77,"78":78,"8":8,"86":86,"88":88,"93":93,"95":95}],246:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, $typed = _dereq_(114)
, buffer = _dereq_(113)
, anObject = _dereq_(8)
, toIndex = _dereq_(106)
, toLength = _dereq_(109)
, isObject = _dereq_(50)
, TYPED_ARRAY = _dereq_(118)('typed_array')
, ArrayBuffer = _dereq_(39).ArrayBuffer
, speciesConstructor = _dereq_(96)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * _dereq_(35)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
_dereq_(92)(ARRAY_BUFFER);
},{"106":106,"109":109,"113":113,"114":114,"118":118,"33":33,"35":35,"39":39,"50":50,"8":8,"92":92,"96":96}],247:[function(_dereq_,module,exports){
var $export = _dereq_(33);
$export($export.G + $export.W + $export.F * !_dereq_(114).ABV, {
DataView: _dereq_(113).DataView
});
},{"113":113,"114":114,"33":33}],248:[function(_dereq_,module,exports){
_dereq_(112)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],249:[function(_dereq_,module,exports){
_dereq_(112)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],250:[function(_dereq_,module,exports){
_dereq_(112)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],251:[function(_dereq_,module,exports){
_dereq_(112)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],252:[function(_dereq_,module,exports){
_dereq_(112)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],253:[function(_dereq_,module,exports){
_dereq_(112)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],254:[function(_dereq_,module,exports){
_dereq_(112)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],255:[function(_dereq_,module,exports){
_dereq_(112)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"112":112}],256:[function(_dereq_,module,exports){
_dereq_(112)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
},{"112":112}],257:[function(_dereq_,module,exports){
'use strict';
var each = _dereq_(13)(0)
, redefine = _dereq_(88)
, meta = _dereq_(63)
, assign = _dereq_(66)
, weak = _dereq_(22)
, isObject = _dereq_(50)
, has = _dereq_(40)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = _dereq_(23)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"13":13,"22":22,"23":23,"40":40,"50":50,"63":63,"66":66,"88":88}],258:[function(_dereq_,module,exports){
'use strict';
var weak = _dereq_(22);
// 23.4 WeakSet Objects
_dereq_(23)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
},{"22":22,"23":23}],259:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = _dereq_(33)
, $includes = _dereq_(12)(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
_dereq_(6)('includes');
},{"12":12,"33":33,"6":6}],260:[function(_dereq_,module,exports){
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = _dereq_(33)
, microtask = _dereq_(65)()
, process = _dereq_(39).process
, isNode = _dereq_(19)(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
},{"19":19,"33":33,"39":39,"65":65}],261:[function(_dereq_,module,exports){
// https://github.com/ljharb/proposal-is-error
var $export = _dereq_(33)
, cof = _dereq_(19);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
},{"19":19,"33":33}],262:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = _dereq_(33);
$export($export.P + $export.R, 'Map', {toJSON: _dereq_(21)('Map')});
},{"21":21,"33":33}],263:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(33);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
},{"33":33}],264:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(33);
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
},{"33":33}],265:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(33);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
},{"33":33}],266:[function(_dereq_,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = _dereq_(33);
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
},{"33":33}],267:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toObject = _dereq_(110)
, aFunction = _dereq_(4)
, $defineProperty = _dereq_(68);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
_dereq_(29) && $export($export.P + _dereq_(70), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
},{"110":110,"29":29,"33":33,"4":4,"68":68,"70":70}],268:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toObject = _dereq_(110)
, aFunction = _dereq_(4)
, $defineProperty = _dereq_(68);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
_dereq_(29) && $export($export.P + _dereq_(70), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
},{"110":110,"29":29,"33":33,"4":4,"68":68,"70":70}],269:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = _dereq_(33)
, $entries = _dereq_(80)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
},{"33":33,"80":80}],270:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = _dereq_(33)
, ownKeys = _dereq_(81)
, toIObject = _dereq_(108)
, gOPD = _dereq_(71)
, createProperty = _dereq_(25);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
},{"108":108,"25":25,"33":33,"71":71,"81":81}],271:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toObject = _dereq_(110)
, toPrimitive = _dereq_(111)
, getPrototypeOf = _dereq_(75)
, getOwnPropertyDescriptor = _dereq_(71).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
_dereq_(29) && $export($export.P + _dereq_(70), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
},{"110":110,"111":111,"29":29,"33":33,"70":70,"71":71,"75":75}],272:[function(_dereq_,module,exports){
'use strict';
var $export = _dereq_(33)
, toObject = _dereq_(110)
, toPrimitive = _dereq_(111)
, getPrototypeOf = _dereq_(75)
, getOwnPropertyDescriptor = _dereq_(71).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
_dereq_(29) && $export($export.P + _dereq_(70), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
},{"110":110,"111":111,"29":29,"33":33,"70":70,"71":71,"75":75}],273:[function(_dereq_,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = _dereq_(33)
, $values = _dereq_(80)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
},{"33":33,"80":80}],274:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
},{"64":64,"8":8}],275:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
},{"64":64,"8":8}],276:[function(_dereq_,module,exports){
var Set = _dereq_(222)
, from = _dereq_(11)
, metadata = _dereq_(64)
, anObject = _dereq_(8)
, getPrototypeOf = _dereq_(75)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"11":11,"222":222,"64":64,"75":75,"8":8}],277:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, getPrototypeOf = _dereq_(75)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"64":64,"75":75,"8":8}],278:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"64":64,"8":8}],279:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"64":64,"8":8}],280:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, getPrototypeOf = _dereq_(75)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"64":64,"75":75,"8":8}],281:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"64":64,"8":8}],282:[function(_dereq_,module,exports){
var metadata = _dereq_(64)
, anObject = _dereq_(8)
, aFunction = _dereq_(4)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
},{"4":4,"64":64,"8":8}],283:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = _dereq_(33);
$export($export.P + $export.R, 'Set', {toJSON: _dereq_(21)('Set')});
},{"21":21,"33":33}],284:[function(_dereq_,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = _dereq_(33)
, $at = _dereq_(98)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
},{"33":33,"98":98}],285:[function(_dereq_,module,exports){
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = _dereq_(33)
, defined = _dereq_(28)
, toLength = _dereq_(109)
, isRegExp = _dereq_(51)
, getFlags = _dereq_(37)
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
_dereq_(53)($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
},{"109":109,"28":28,"33":33,"37":37,"51":51,"53":53}],286:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = _dereq_(33)
, $pad = _dereq_(101);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"101":101,"33":33}],287:[function(_dereq_,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = _dereq_(33)
, $pad = _dereq_(101);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"101":101,"33":33}],288:[function(_dereq_,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
_dereq_(103)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
},{"103":103}],289:[function(_dereq_,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
_dereq_(103)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
},{"103":103}],290:[function(_dereq_,module,exports){
_dereq_(116)('asyncIterator');
},{"116":116}],291:[function(_dereq_,module,exports){
_dereq_(116)('observable');
},{"116":116}],292:[function(_dereq_,module,exports){
// https://github.com/ljharb/proposal-global
var $export = _dereq_(33);
$export($export.S, 'System', {global: _dereq_(39)});
},{"33":33,"39":39}],293:[function(_dereq_,module,exports){
var $iterators = _dereq_(132)
, redefine = _dereq_(88)
, global = _dereq_(39)
, hide = _dereq_(41)
, Iterators = _dereq_(57)
, wks = _dereq_(118)
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
},{"118":118,"132":132,"39":39,"41":41,"57":57,"88":88}],294:[function(_dereq_,module,exports){
var $export = _dereq_(33)
, $task = _dereq_(105);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"105":105,"33":33}],295:[function(_dereq_,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = _dereq_(39)
, $export = _dereq_(33)
, invoke = _dereq_(45)
, partial = _dereq_(84)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"33":33,"39":39,"45":45,"84":84}],296:[function(_dereq_,module,exports){
_dereq_(245);
_dereq_(182);
_dereq_(184);
_dereq_(183);
_dereq_(186);
_dereq_(188);
_dereq_(193);
_dereq_(187);
_dereq_(185);
_dereq_(195);
_dereq_(194);
_dereq_(190);
_dereq_(191);
_dereq_(189);
_dereq_(181);
_dereq_(192);
_dereq_(196);
_dereq_(197);
_dereq_(148);
_dereq_(150);
_dereq_(149);
_dereq_(199);
_dereq_(198);
_dereq_(169);
_dereq_(179);
_dereq_(180);
_dereq_(170);
_dereq_(171);
_dereq_(172);
_dereq_(173);
_dereq_(174);
_dereq_(175);
_dereq_(176);
_dereq_(177);
_dereq_(178);
_dereq_(152);
_dereq_(153);
_dereq_(154);
_dereq_(155);
_dereq_(156);
_dereq_(157);
_dereq_(158);
_dereq_(159);
_dereq_(160);
_dereq_(161);
_dereq_(162);
_dereq_(163);
_dereq_(164);
_dereq_(165);
_dereq_(166);
_dereq_(167);
_dereq_(168);
_dereq_(232);
_dereq_(237);
_dereq_(244);
_dereq_(235);
_dereq_(227);
_dereq_(228);
_dereq_(233);
_dereq_(238);
_dereq_(240);
_dereq_(223);
_dereq_(224);
_dereq_(225);
_dereq_(226);
_dereq_(229);
_dereq_(230);
_dereq_(231);
_dereq_(234);
_dereq_(236);
_dereq_(239);
_dereq_(241);
_dereq_(242);
_dereq_(243);
_dereq_(143);
_dereq_(145);
_dereq_(144);
_dereq_(147);
_dereq_(146);
_dereq_(131);
_dereq_(129);
_dereq_(136);
_dereq_(133);
_dereq_(139);
_dereq_(141);
_dereq_(128);
_dereq_(135);
_dereq_(125);
_dereq_(140);
_dereq_(123);
_dereq_(138);
_dereq_(137);
_dereq_(130);
_dereq_(134);
_dereq_(122);
_dereq_(124);
_dereq_(127);
_dereq_(126);
_dereq_(142);
_dereq_(132);
_dereq_(215);
_dereq_(221);
_dereq_(216);
_dereq_(217);
_dereq_(218);
_dereq_(219);
_dereq_(220);
_dereq_(200);
_dereq_(151);
_dereq_(222);
_dereq_(257);
_dereq_(258);
_dereq_(246);
_dereq_(247);
_dereq_(252);
_dereq_(255);
_dereq_(256);
_dereq_(250);
_dereq_(253);
_dereq_(251);
_dereq_(254);
_dereq_(248);
_dereq_(249);
_dereq_(201);
_dereq_(202);
_dereq_(203);
_dereq_(204);
_dereq_(205);
_dereq_(208);
_dereq_(206);
_dereq_(207);
_dereq_(209);
_dereq_(210);
_dereq_(211);
_dereq_(212);
_dereq_(214);
_dereq_(213);
_dereq_(259);
_dereq_(284);
_dereq_(287);
_dereq_(286);
_dereq_(288);
_dereq_(289);
_dereq_(285);
_dereq_(290);
_dereq_(291);
_dereq_(270);
_dereq_(273);
_dereq_(269);
_dereq_(267);
_dereq_(268);
_dereq_(271);
_dereq_(272);
_dereq_(262);
_dereq_(283);
_dereq_(292);
_dereq_(261);
_dereq_(263);
_dereq_(265);
_dereq_(264);
_dereq_(266);
_dereq_(274);
_dereq_(275);
_dereq_(277);
_dereq_(276);
_dereq_(279);
_dereq_(278);
_dereq_(280);
_dereq_(281);
_dereq_(282);
_dereq_(260);
_dereq_(295);
_dereq_(294);
_dereq_(293);
module.exports = _dereq_(24);
},{"122":122,"123":123,"124":124,"125":125,"126":126,"127":127,"128":128,"129":129,"130":130,"131":131,"132":132,"133":133,"134":134,"135":135,"136":136,"137":137,"138":138,"139":139,"140":140,"141":141,"142":142,"143":143,"144":144,"145":145,"146":146,"147":147,"148":148,"149":149,"150":150,"151":151,"152":152,"153":153,"154":154,"155":155,"156":156,"157":157,"158":158,"159":159,"160":160,"161":161,"162":162,"163":163,"164":164,"165":165,"166":166,"167":167,"168":168,"169":169,"170":170,"171":171,"172":172,"173":173,"174":174,"175":175,"176":176,"177":177,"178":178,"179":179,"180":180,"181":181,"182":182,"183":183,"184":184,"185":185,"186":186,"187":187,"188":188,"189":189,"190":190,"191":191,"192":192,"193":193,"194":194,"195":195,"196":196,"197":197,"198":198,"199":199,"200":200,"201":201,"202":202,"203":203,"204":204,"205":205,"206":206,"207":207,"208":208,"209":209,"210":210,"211":211,"212":212,"213":213,"214":214,"215":215,"216":216,"217":217,"218":218,"219":219,"220":220,"221":221,"222":222,"223":223,"224":224,"225":225,"226":226,"227":227,"228":228,"229":229,"230":230,"231":231,"232":232,"233":233,"234":234,"235":235,"236":236,"237":237,"238":238,"239":239,"24":24,"240":240,"241":241,"242":242,"243":243,"244":244,"245":245,"246":246,"247":247,"248":248,"249":249,"250":250,"251":251,"252":252,"253":253,"254":254,"255":255,"256":256,"257":257,"258":258,"259":259,"260":260,"261":261,"262":262,"263":263,"264":264,"265":265,"266":266,"267":267,"268":268,"269":269,"270":270,"271":271,"272":272,"273":273,"274":274,"275":275,"276":276,"277":277,"278":278,"279":279,"280":280,"281":281,"282":282,"283":283,"284":284,"285":285,"286":286,"287":287,"288":288,"289":289,"290":290,"291":291,"292":292,"293":293,"294":294,"295":295}],297:[function(_dereq_,module,exports){
(function (global){
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var hasOwn = Object.prototype.hasOwnProperty;
var undefined; // More compressible than void 0.
var iteratorSymbol =
typeof Symbol === "function" && Symbol.iterator || "@@iterator";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided, then outerFn.prototype instanceof Generator.
var generator = Object.create((outerFn || Generator).prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype;
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `value instanceof AwaitArgument` to determine if the yielded value is
// meant to be awaited. Some may consider the name of this method too
// cutesy, but they are curmudgeons.
runtime.awrap = function(arg) {
return new AwaitArgument(arg);
};
function AwaitArgument(arg) {
this.arg = arg;
}
function AsyncIterator(generator) {
// This invoke function is written in a style that assumes some
// calling function (or Promise) will handle exceptions.
function invoke(method, arg) {
var result = generator[method](arg);
var value = result.value;
return value instanceof AwaitArgument
? Promise.resolve(value.arg).then(invokeNext, invokeThrow)
: Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
return result;
});
}
if (typeof process === "object" && process.domain) {
invoke = process.domain.bind(invoke);
}
var invokeNext = invoke.bind(generator, "next");
var invokeThrow = invoke.bind(generator, "throw");
var invokeReturn = invoke.bind(generator, "return");
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return invoke(method, arg);
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : new Promise(function (resolve) {
resolve(callInvokeWithMethodAndArg());
});
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
while (true) {
var delegate = context.delegate;
if (delegate) {
if (method === "return" ||
(method === "throw" && delegate.iterator[method] === undefined)) {
// A return or throw (when the delegate iterator has no throw
// method) always terminates the yield* loop.
context.delegate = null;
// If the delegate iterator has a return method, give it a
// chance to clean up.
var returnMethod = delegate.iterator["return"];
if (returnMethod) {
var record = tryCatch(returnMethod, delegate.iterator, arg);
if (record.type === "throw") {
// If the return method threw an exception, let that
// exception prevail over the original return or throw.
method = "throw";
arg = record.arg;
continue;
}
}
if (method === "return") {
// Continue with the outer return, now that the delegate
// iterator has been terminated.
continue;
}
}
var record = tryCatch(
delegate.iterator[method],
delegate.iterator,
arg
);
if (record.type === "throw") {
context.delegate = null;
// Like returning generator.throw(uncaught), but without the
// overhead of an extra function call.
method = "throw";
arg = record.arg;
continue;
}
// Delegate generator ran and handled its own exceptions so
// regardless of what the method was, we continue as if it is
// "next" with an undefined arg.
method = "next";
arg = undefined;
var info = record.arg;
if (info.done) {
context[delegate.resultName] = info.value;
context.next = delegate.nextLoc;
} else {
state = GenStateSuspendedYield;
return info;
}
context.delegate = null;
}
if (method === "next") {
context._sent = arg;
if (state === GenStateSuspendedYield) {
context.sent = arg;
} else {
context.sent = undefined;
}
} else if (method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw arg;
}
if (context.dispatchException(arg)) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
method = "next";
arg = undefined;
}
} else if (method === "return") {
context.abrupt("return", arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
var info = {
value: record.arg,
done: context.done
};
if (record.arg === ContinueSentinel) {
if (context.delegate && method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
arg = undefined;
}
} else {
return info;
}
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(arg) call above.
method = "throw";
arg = record.arg;
}
}
};
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
this.sent = undefined;
this.done = false;
this.delegate = null;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
return !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.next = finallyEntry.finallyLoc;
} else {
this.complete(record);
}
return ContinueSentinel;
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = record.arg;
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);
|
ajax/libs/forerunnerdb/1.3.133/fdb-core+views.js
|
brix/cdnjs
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":28}],2:[function(_dereq_,module,exports){
var Core = _dereq_('./Core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":29,"./Core":1}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":27}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (!(index instanceof Array)) {
// Convert the index object to an array of key val objects
index = this.keys(index);
}
}
return this.$super.call(this, index);
});
BinaryTree.prototype.keys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return true;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._index.length; i++) {
indexData = this._index[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._index.length; i++) {
indexData = this._index[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._index[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'key':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._key,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Shared":27}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (this._state !== 'dropped') {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log('Dropping collection ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
}
}
return this.$super.apply(this, arguments);
});
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log('Updating some collection data for collection "' + this.name() + '"');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, referencedDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!');
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')');
}
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = undefined;
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
* @private
*/
Collection.prototype.deferEmit = function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); }
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return true;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
matcher = function (doc) {
return self._match(doc, query, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
op.time('tableScan: ' + scanLength);
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = sortKey;
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
buckets = this.bucket(keyObj.___fdbKey, arr);
// Loop buckets and sort contents
for (i in buckets) {
if (buckets.hasOwnProperty(i)) {
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i]));
}
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
buckets = {};
for (i = 0; i < arr.length; i++) {
buckets[arr[i][key]] = buckets[arr[i][key]] || [];
buckets[arr[i][key]].push(arr[i]);
}
return buckets;
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log('Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw('ForerunnerDB.Db "' + this.name() + '": Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":27}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function () {
if (this._state !== 'dropped') {
var i,
collArr,
viewArr;
if (this._debug) {
console.log('Dropping collection group ' + this._name);
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":27}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
callback();
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":13,"./Overload":24,"./Shared":27}],8:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
module.exports = Db;
},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":24,"./Shared":27}],10:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":25,"./Shared":27}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":25,"./Shared":27}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":27}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":23,"./Shared":27}],14:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],15:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides a class with chain reaction capabilities.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && arrItem._state !== 'dropped')) {
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],16:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return JSON.parse(JSON.stringify(data));
} else {
var i,
json = JSON.stringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(JSON.parse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
])
};
module.exports = Common;
},{"./Overload":24}],17:[function(_dereq_,module,exports){
"use strict";
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount;
// Handle global emit
if (this._listeners[event]['*']) {
var arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
var listenerIdArr = this._listeners[event],
listenerIdCount,
listenerIdIndex;
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{"./Overload":24}],19:[function(_dereq_,module,exports){
"use strict";
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
}
return -1;
}
};
module.exports = Matching;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":24}],22:[function(_dereq_,module,exports){
"use strict";
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "' + prop + '" for "' + this.name() + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for "' + this.name() + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item from the array stack.
* @param {Object} doc The document to modify.
* @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false;
if (doc.length > 0) {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":25,"./Shared":27}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":27}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
ReactorIO.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":27}],27:[function(_dereq_,module,exports){
"use strict";
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.133',
modules: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
this.modules[name] = module;
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
this.modules[name]._fdbFinished = true;
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: function (obj, mixinName) {
var system = this.mixins[mixinName];
if (system) {
for (var i in system) {
if (system.hasOwnProperty(i)) {
obj[i] = system[i];
}
}
} else {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
},
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: _dereq_('./Overload'),
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],28:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection('__FDB__view_privateData_' + this._name);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the collection from which the view will assemble its data.
* @param {Collection} collection The collection to use to assemble view data.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (collection) {
var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" collection and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(collection, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = collection.find(this._querySettings.query, this._querySettings.options);
this._transformPrimaryKey(collection.primaryKey());
this._transformSetData(collData);
this._privateData.primaryKey(collection.primaryKey());
this._privateData.setData(collData);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
//tempData,
//dataIsArray,
updates,
//finalUpdates,
primaryKey,
tQuery,
item,
currentIndex,
i;
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
// Modify transform data
this._transformSetData(collData);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
if (this._transformEnabled && this._transformIn) {
primaryKey = this._publicData.primaryKey();
for (i = 0; i < updates.length; i++) {
tQuery = {};
item = updates[i];
tQuery[primaryKey] = item[primaryKey];
this._transformUpdate(tQuery, item);
}
}
break;
case 'remove':
if (this.debug()) {
console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Modify transform data
this._transformRemove(chainPacket.data.query, chainPacket.options);
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._privateData.distinct.apply(this._privateData, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._privateData.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function () {
if (this._state !== 'dropped') {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log('ForerunnerDB.View: Dropping view ' + this._name);
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
View.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
this.privateData().db(db);
this.publicData().db(db);
return this;
}
return this._db;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._privateData && this._privateData._data ? this._privateData._data.length : 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
// Update the transformed data object
this._transformPrimaryKey(this.privateData().primaryKey());
this._transformSetData(this.privateData().find());
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* Updates the public data object to match data from the private data object
* by running private data through the dataIn method provided in
* the transform() call.
* @private
*/
View.prototype._transformSetData = function (data) {
if (this._transformEnabled) {
// Clear existing data
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
this._publicData.setData(data);
}
};
View.prototype._transformInsert = function (data, index) {
if (this._transformEnabled && this._publicData) {
this._publicData.insert(data, index);
}
};
View.prototype._transformUpdate = function (query, update, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.update(query, update, options);
}
};
View.prototype._transformRemove = function (query, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.remove(query, options);
}
};
View.prototype._transformPrimaryKey = function (key) {
if (this._transformEnabled && this._publicData) {
this._publicData.primaryKey(key);
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log('Db.View: Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":26,"./Shared":27}]},{},[2]);
|
decisionz/lib/jquery_ui/js/jquery-1.7.2.min.js
|
dee-bee/decisionz
|
/*! jQuery v1.7.2 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cu(a){if(!cj[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ck||(ck=c.createElement("iframe"),ck.frameBorder=ck.width=ck.height=0),b.appendChild(ck);if(!cl||!ck.createElement)cl=(ck.contentWindow||ck.contentDocument).document,cl.write((f.support.boxModel?"<!doctype html>":"")+"<html><body>"),cl.close();d=cl.createElement(a),cl.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ck)}cj[a]=e}return cj[a]}function ct(a,b){var c={};f.each(cp.concat.apply([],cp.slice(0,b)),function(){c[this]=a});return c}function cs(){cq=b}function cr(){setTimeout(cs,0);return cq=f.now()}function ci(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ch(){try{return new a.XMLHttpRequest}catch(b){}}function cb(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function ca(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function b_(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bD.test(a)?d(a,e):b_(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&f.type(b)==="object")for(var e in b)b_(a+"["+e+"]",b[e],c,d);else d(a,b)}function b$(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function bZ(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bS,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bZ(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bZ(a,c,d,e,"*",g));return l}function bY(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bO),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bB(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?1:0,g=4;if(d>0){if(c!=="border")for(;e<g;e+=2)c||(d-=parseFloat(f.css(a,"padding"+bx[e]))||0),c==="margin"?d+=parseFloat(f.css(a,c+bx[e]))||0:d-=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0;return d+"px"}d=by(a,b);if(d<0||d==null)d=a.style[b];if(bt.test(d))return d;d=parseFloat(d)||0;if(c)for(;e<g;e+=2)d+=parseFloat(f.css(a,"padding"+bx[e]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+bx[e]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+bx[e]))||0);return d+"px"}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;b.nodeType===1&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?b.outerHTML=a.outerHTML:c!=="input"||a.type!=="checkbox"&&a.type!=="radio"?c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text):(a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value)),b.removeAttribute(f.expando),b.removeAttribute("_submit_attached"),b.removeAttribute("_change_attached"))}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c,i[c][d])}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?+d:j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){if(typeof c!="string"||!c)return null;var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h,i){var j,k=d==null,l=0,m=a.length;if(d&&typeof d=="object"){for(l in d)e.access(a,c,l,d[l],1,h,f);g=1}else if(f!==b){j=i===b&&e.isFunction(f),k&&(j?(j=c,c=function(a,b,c){return j.call(e(a),c)}):(c.call(a,f),c=null));if(c)for(;l<m;l++)c(a[l],d,j?f.call(a[l],l,c(a[l],d)):f,i);g=1}return g?a:k?c.call(a):m?c(a[0],d):h},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m,n=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?n(g):h==="function"&&(!a.unique||!p.has(g))&&c.push(g)},o=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,j=!0,m=k||0,k=0,l=c.length;for(;c&&m<l;m++)if(c[m].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}j=!1,c&&(a.once?e===!0?p.disable():c=[]:d&&d.length&&(e=d.shift(),p.fireWith(e[0],e[1])))},p={add:function(){if(c){var a=c.length;n(arguments),j?l=c.length:e&&e!==!0&&(k=a,o(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){j&&f<=l&&(l--,f<=m&&m--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&p.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(j?a.once||d.push([b,c]):(!a.once||!e)&&o(b,c));return this},fire:function(){p.fireWith(this,arguments);return this},fired:function(){return!!i}};return p};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p=c.createElement("div"),q=c.documentElement;p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=p.getElementsByTagName("*"),e=p.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=p.getElementsByTagName("input")[0],b={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:p.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,pixelMargin:!0},f.boxModel=b.boxModel=c.compatMode==="CSS1Compat",i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete p.test}catch(r){b.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",function(){b.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),i.setAttribute("name","t"),p.appendChild(i),j=c.createDocumentFragment(),j.appendChild(p.lastChild),b.checkClone=j.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,j.removeChild(i),j.appendChild(p);if(p.attachEvent)for(n in{submit:1,change:1,focusin:1})m="on"+n,o=m in p,o||(p.setAttribute(m,"return;"),o=typeof p[m]=="function"),b[n+"Bubbles"]=o;j.removeChild(p),j=g=h=p=i=null,f(function(){var d,e,g,h,i,j,l,m,n,q,r,s,t,u=c.getElementsByTagName("body")[0];!u||(m=1,t="padding:0;margin:0;border:",r="position:absolute;top:0;left:0;width:1px;height:1px;",s=t+"0;visibility:hidden;",n="style='"+r+t+"5px solid #000;",q="<div "+n+"display:block;'><div style='"+t+"0;display:block;overflow:hidden;'></div></div>"+"<table "+n+"' cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",d=c.createElement("div"),d.style.cssText=s+"width:0;height:0;position:static;top:0;margin-top:"+m+"px",u.insertBefore(d,u.firstChild),p=c.createElement("div"),d.appendChild(p),p.innerHTML="<table><tr><td style='"+t+"0;display:none'></td><td>t</td></tr></table>",k=p.getElementsByTagName("td"),o=k[0].offsetHeight===0,k[0].style.display="",k[1].style.display="none",b.reliableHiddenOffsets=o&&k[0].offsetHeight===0,a.getComputedStyle&&(p.innerHTML="",l=c.createElement("div"),l.style.width="0",l.style.marginRight="0",p.style.width="2px",p.appendChild(l),b.reliableMarginRight=(parseInt((a.getComputedStyle(l,null)||{marginRight:0}).marginRight,10)||0)===0),typeof p.style.zoom!="undefined"&&(p.innerHTML="",p.style.width=p.style.padding="1px",p.style.border=0,p.style.overflow="hidden",p.style.display="inline",p.style.zoom=1,b.inlineBlockNeedsLayout=p.offsetWidth===3,p.style.display="block",p.style.overflow="visible",p.innerHTML="<div style='width:5px;'></div>",b.shrinkWrapBlocks=p.offsetWidth!==3),p.style.cssText=r+s,p.innerHTML=q,e=p.firstChild,g=e.firstChild,i=e.nextSibling.firstChild.firstChild,j={doesNotAddBorder:g.offsetTop!==5,doesAddBorderForTableAndCells:i.offsetTop===5},g.style.position="fixed",g.style.top="20px",j.fixedPosition=g.offsetTop===20||g.offsetTop===15,g.style.position=g.style.top="",e.style.overflow="hidden",e.style.position="relative",j.subtractsBorderForOverflowNotVisible=g.offsetTop===-5,j.doesNotIncludeMarginInBodyOffset=u.offsetTop!==m,a.getComputedStyle&&(p.style.marginTop="1%",b.pixelMargin=(a.getComputedStyle(p,null)||{marginTop:0}).marginTop!=="1%"),typeof d.style.zoom!="undefined"&&(d.style.zoom=1),u.removeChild(d),l=p=d=null,f.extend(b,j))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h,i,j=this[0],k=0,m=null;if(a===b){if(this.length){m=f.data(j);if(j.nodeType===1&&!f._data(j,"parsedAttrs")){g=j.attributes;for(i=g.length;k<i;k++)h=g[k].name,h.indexOf("data-")===0&&(h=f.camelCase(h.substring(5)),l(j,h,m[h]));f._data(j,"parsedAttrs",!0)}}return m}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!";return f.access(this,function(c){if(c===b){m=this.triggerHandler("getData"+e,[d[0]]),m===b&&j&&(m=f.data(j,a),m=l(j,a,m));return m===b&&d[1]?this.data(d[0]):m}d[1]=c,this.each(function(){var b=f(this);b.triggerHandler("setData"+e,d),f.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1)},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){var d=2;typeof a!="string"&&(c=a,a="fx",d--);if(arguments.length<d)return f.queue(this[0],a);return c===b?this:this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise(c)}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,f.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,f.prop,a,b,arguments.length>1)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.type]||f.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.type]||f.valHooks[g.nodeName.toLowerCase()];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h,i=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;i<g;i++)e=d[i],e&&(c=f.propFix[e]||e,h=u.test(e),h||f.attr(a,e,""),a.removeAttribute(v?e:c),h&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0,coords:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/(?:^|\s)hover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(
a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler,g=p.selector),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:g&&G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=f.event.special[c.type]||{},j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(!i.preDispatch||i.preDispatch.call(this,c)!==!1){if(e&&(!c.button||c.type!=="click")){n=f(this),n.context=this.ownerDocument||this;for(m=c.target;m!=this;m=m.parentNode||this)if(m.disabled!==!0){p={},r=[],n[0]=m;for(k=0;k<e;k++)s=d[k],t=s.selector,p[t]===b&&(p[t]=s.quick?H(m,s.quick):n.is(t)),p[t]&&r.push(s);r.length&&j.push({elem:m,matches:r})}}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){q=j[k],c.currentTarget=q.elem;for(l=0;l<q.matches.length&&!c.isImmediatePropagationStopped();l++){s=q.matches[l];if(h||!c.namespace&&!s.namespace||c.namespace_re&&c.namespace_re.test(s.namespace))c.data=s.data,c.handleObj=s,o=((f.event.special[s.origType]||{}).handle||s.handler).apply(q.elem,g),o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()))}}i.postDispatch&&i.postDispatch.call(this,c);return c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),d._submit_attached=!0)})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9||d===11){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));o.match.globalPOS=p;var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.globalPOS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")[\\s/>]","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){return f.access(this,function(a){return a===b?f.text(this):this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f
.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){return f.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(f.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(g){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,function(a,b){b.src?f.ajax({type:"GET",global:!1,url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||f.isXMLDoc(a)||!bc.test("<"+a.nodeName+">")?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g,h,i,j=[];b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);for(var k=0,l;(l=a[k])!=null;k++){typeof l=="number"&&(l+="");if(!l)continue;if(typeof l=="string")if(!_.test(l))l=b.createTextNode(l);else{l=l.replace(Y,"<$1></$2>");var m=(Z.exec(l)||["",""])[1].toLowerCase(),n=bg[m]||bg._default,o=n[0],p=b.createElement("div"),q=bh.childNodes,r;b===c?bh.appendChild(p):U(b).appendChild(p),p.innerHTML=n[1]+l+n[2];while(o--)p=p.lastChild;if(!f.support.tbody){var s=$.test(l),t=m==="table"&&!s?p.firstChild&&p.firstChild.childNodes:n[1]==="<table>"&&!s?p.childNodes:[];for(i=t.length-1;i>=0;--i)f.nodeName(t[i],"tbody")&&!t[i].childNodes.length&&t[i].parentNode.removeChild(t[i])}!f.support.leadingWhitespace&&X.test(l)&&p.insertBefore(b.createTextNode(X.exec(l)[0]),p.firstChild),l=p.childNodes,p&&(p.parentNode.removeChild(p),q.length>0&&(r=q[q.length-1],r&&r.parentNode&&r.parentNode.removeChild(r)))}var u;if(!f.support.appendChecked)if(l[0]&&typeof (u=l.length)=="number")for(i=0;i<u;i++)bn(l[i]);else bn(l);l.nodeType?j.push(l):j=f.merge(j,l)}if(d){g=function(a){return!a.type||be.test(a.type)};for(k=0;j[k];k++){h=j[k];if(e&&f.nodeName(h,"script")&&(!h.type||be.test(h.type)))e.push(h.parentNode?h.parentNode.removeChild(h):h);else{if(h.nodeType===1){var v=f.grep(h.getElementsByTagName("script"),g);j.splice.apply(j,[k+1,0].concat(v))}d.appendChild(h)}}}return j},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bp=/alpha\([^)]*\)/i,bq=/opacity=([^)]*)/,br=/([A-Z]|^ms)/g,bs=/^[\-+]?(?:\d*\.)?\d+$/i,bt=/^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,bu=/^([\-+])=([\-+.\de]+)/,bv=/^margin/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Top","Right","Bottom","Left"],by,bz,bA;f.fn.css=function(a,c){return f.access(this,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)},a,c,arguments.length>1)},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=by(a,"opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bu.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(by)return by(a,c)},swap:function(a,b,c){var d={},e,f;for(f in b)d[f]=a.style[f],a.style[f]=b[f];e=c.call(a);for(f in b)a.style[f]=d[f];return e}}),f.curCSS=f.css,c.defaultView&&c.defaultView.getComputedStyle&&(bz=function(a,b){var c,d,e,g,h=a.style;b=b.replace(br,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b))),!f.support.pixelMargin&&e&&bv.test(b)&&bt.test(c)&&(g=h.width,h.width=c,c=e.width,h.width=g);return c}),c.documentElement.currentStyle&&(bA=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f==null&&g&&(e=g[b])&&(f=e),bt.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),by=bz||bA,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0?bB(a,b,d):f.swap(a,bw,function(){return bB(a,b,d)})},set:function(a,b){return bs.test(b)?b+"px":b}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bq.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bp,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bp.test(g)?g.replace(bp,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){return f.swap(a,{display:"inline-block"},function(){return b?by(a,"margin-right"):a.style.marginRight})}})}),f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)}),f.each({margin:"",padding:"",border:"Width"},function(a,b){f.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bx[d]+b]=e[d]||e[d-2]||e[0];return f}}});var bC=/%20/g,bD=/\[\]$/,bE=/\r?\n/g,bF=/#.*$/,bG=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bH=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bI=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bJ=/^(?:GET|HEAD)$/,bK=/^\/\//,bL=/\?/,bM=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bN=/^(?:select|textarea)/i,bO=/\s+/,bP=/([?&])_=[^&]*/,bQ=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bR=f.fn.load,bS={},bT={},bU,bV,bW=["*/"]+["*"];try{bU=e.href}catch(bX){bU=c.createElement("a"),bU.href="",bU=bU.href}bV=bQ.exec(bU.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bR)return bR.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bM,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bN.test(this.nodeName)||bH.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bE,"\r\n")}}):{name:b.name,value:c.replace(bE,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b$(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b$(a,b);return a},ajaxSettings:{url:bU,isLocal:bI.test(bV[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bW},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bY(bS),ajaxTransport:bY(bT),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?ca(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cb(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bG.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bF,"").replace(bK,bV[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bO),d.crossDomain==null&&(r=bQ.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bV[1]&&r[2]==bV[2]&&(r[3]||(r[1]==="http:"?80:443))==(bV[3]||(bV[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bZ(bS,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bJ.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bL.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bP,"$1_="+x);d.url=y+(y===d.url?(bL.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bW+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bZ(bT,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)b_(g,a[g],c,e);return d.join("&").replace(bC,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cc=f.now(),cd=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cc++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=typeof b.data=="string"&&/^application\/x\-www\-form\-urlencoded/.test(b.contentType);if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cd.test(b.url)||e&&cd.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cd,l),b.url===j&&(e&&(k=k.replace(cd,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ce=a.ActiveXObject?function(){for(var a in cg)cg[a](0,1)}:!1,cf=0,cg;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ch()||ci()}:ch,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ce&&delete cg[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n);try{m.text=h.responseText}catch(a){}try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cf,ce&&(cg||(cg={},f(a).unload(ce)),cg[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cj={},ck,cl,cm=/^(?:toggle|show|hide)$/,cn=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,co,cp=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cq;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(ct("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),(e===""&&f.css(d,"display")==="none"||!f.contains(d.ownerDocument.documentElement,d))&&f._data(d,"olddisplay",cu(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ct("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(ct("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o,p,q;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]);if((k=f.cssHooks[g])&&"expand"in k){l=k.expand(a[g]),delete a[g];for(i in l)i in a||(a[i]=l[i])}}for(g in a){h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cu(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cm.test(h)?(q=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),q?(f._data(this,"toggle"+i,q==="show"?"hide":"show"),j[q]()):j[h]()):(m=cn.exec(h),n=j.cur(),m?(o=parseFloat(m[2]),p=m[3]||(f.cssNumber[i]?"":"px"),p!=="px"&&(f.style(this,i,(o||1)+p),n=(o||1)/j.cur()*n,f.style(this,i,n+p)),m[1]&&(o=(m[1]==="-="?-1:1)*o+n),j.custom(n,o,p)):j.custom(n,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:ct("show",1),slideUp:ct("hide",1),slideToggle:ct("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a){return a},swing:function(a){return-Math.cos(a*Math.PI)/2+.5}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cq||cr(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){f._data(e.elem,"fxshow"+e.prop)===b&&(e.options.hide?f._data(e.elem,"fxshow"+e.prop,e.start):e.options.show&&f._data(e.elem,"fxshow"+e.prop,e.end))},h()&&f.timers.push(h)&&!co&&(co=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cq||cr(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(co),co=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(cp.concat.apply([],cp),function(a,b){b.indexOf("margin")&&(f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)})}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cv,cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?cv=function(a,b,c,d){try{d=a.getBoundingClientRect()}catch(e){}if(!d||!f.contains(c,a))return d?{top:d.top,left:d.left}:{top:0,left:0};var g=b.body,h=cy(b),i=c.clientTop||g.clientTop||0,j=c.clientLeft||g.clientLeft||0,k=h.pageYOffset||f.support.boxModel&&c.scrollTop||g.scrollTop,l=h.pageXOffset||f.support.boxModel&&c.scrollLeft||g.scrollLeft,m=d.top+k-i,n=d.left+l-j;return{top:m,left:n}}:cv=function(a,b,c){var d,e=a.offsetParent,g=a,h=b.body,i=b.defaultView,j=i?i.getComputedStyle(a,null):a.currentStyle,k=a.offsetTop,l=a.offsetLeft;while((a=a.parentNode)&&a!==h&&a!==c){if(f.support.fixedPosition&&j.position==="fixed")break;d=i?i.getComputedStyle(a,null):a.currentStyle,k-=a.scrollTop,l-=a.scrollLeft,a===e&&(k+=a.offsetTop,l+=a.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(a.nodeName))&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),g=e,e=a.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"&&(k+=parseFloat(d.borderTopWidth)||0,l+=parseFloat(d.borderLeftWidth)||0),j=d}if(j.position==="relative"||j.position==="static")k+=h.offsetTop,l+=h.offsetLeft;f.support.fixedPosition&&j.position==="fixed"&&(k+=Math.max(c.scrollTop,h.scrollTop),l+=Math.max(c.scrollLeft,h.scrollLeft));return{top:k,left:l}},f.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){f.offset.setOffset(this,a,b)});var c=this[0],d=c&&c.ownerDocument;if(!d)return null;if(c===d.body)return f.offset.bodyOffset(c);return cv(c,d,d.documentElement)},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);f.fn[a]=function(e){return f.access(this,function(a,e,g){var h=cy(a);if(g===b)return h?c in h?h[c]:f.support.boxModel&&h.document.documentElement[e]||h.document.body[e]:a[e];h?h.scrollTo(d?f(h).scrollLeft():g,d?g:f(h).scrollTop()):a[e]=g},a,e,arguments.length,null)}}),f.each({Height:"height",Width:"width"},function(a,c){var d="client"+a,e="scroll"+a,g="offset"+a;f.fn["inner"+a]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,c,"padding")):this[c]():null},f.fn["outer"+a]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,c,a?"margin":"border")):this[c]():null},f.fn[c]=function(a){return f.access(this,function(a,c,h){var i,j,k,l;if(f.isWindow(a)){i=a.document,j=i.documentElement[d];return f.support.boxModel&&j||i.body&&i.body[d]||j}if(a.nodeType===9){i=a.documentElement;if(i[d]>=i[e])return i[d];return Math.max(a.body[e],i[e],a.body[g],i[g])}if(h===b){k=f.css(a,c),l=parseFloat(k);return f.isNumeric(l)?l:k}f(a).css(c,h)},c,a,arguments.length,null)}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
|
docs/pages/components/chips.js
|
kybarg/material-ui
|
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
const req = require.context('docs/src/pages/components/chips', false, /\.(md|js|tsx)$/);
const reqSource = require.context(
'!raw-loader!../../src/pages/components/chips',
false,
/\.(js|tsx)$/,
);
const reqPrefix = 'pages/components/chips';
export default function Page() {
return <MarkdownDocs req={req} reqSource={reqSource} reqPrefix={reqPrefix} />;
}
|
src/app/components/resourses/planetsheet/OneItem.js
|
mazahell/eve-react-app
|
import React from 'react';
import Helper from './../../../../app/helpers';
import { map } from 'lodash';
const OneItem = props => {
const { item, price_input_type, input_prices } = props;
const outputValue = Helper.price(item.profit);
const percColor = item.profit >= 0 ? 'txt-yellow' : 'profit-minus';
let outputCost = 0;
let inputItems = map(item.input, (v, i) => {
let amount = input_prices[price_input_type][v.item_id] * v.quantity;
outputCost += amount;
return (
<div key={i} className="row">
<div className="col-md-12 col-sm-12 col-xs-12 flex-between">
<span>
<img className="img16 pen" alt={v.item_name} src={`https://image.eveonline.com/Type/${v.item_id}_32.png`} />
{v.item_name} {v.quantity} x {Helper.price(input_prices[price_input_type][v.item_id])} isk
</span>
<span>{Helper.price(amount)}</span>
</div>
</div>
);
});
return (
<div className="row">
<div className="col-md-12">
<table className="inside">
<thead>
<tr>
<th colSpan="2">
<div className="flex-between">
<div className="item-output">
<div>{item.schema_name} x {item.quantity}</div>
<div className={percColor}>{outputValue} isk</div>
</div>
<span className="txt-normal">{Helper.price(outputCost)}</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td colSpan="2" className="inside-table">
{inputItems}
</td>
</tr>
</tbody>
</table>
</div>
</div>
);
};
export default OneItem;
|
src/svg-icons/av/repeat-one.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRepeatOne = (props) => (
<SvgIcon {...props}>
<path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4zm-4-2V9h-1l-2 1v1h1.5v4H13z"/>
</SvgIcon>
);
AvRepeatOne = pure(AvRepeatOne);
AvRepeatOne.displayName = 'AvRepeatOne';
AvRepeatOne.muiName = 'SvgIcon';
export default AvRepeatOne;
|
src/shared/components/FunFact/index.js
|
CharlesMangwa/Chloe
|
/* @flow */
import React from 'react'
import { Text, View } from 'react-native'
import styles from './styles'
type Props = {
color: string,
fact: string,
}
const FunFact = (props: Props): React$Element<any> => {
const { color, fact } = props
return (
<View style={styles.container}>
<View style={[styles.tile, { backgroundColor: color }]}>
<Text style={styles.questionMark}>?</Text>
</View>
<View style={styles.wrapper}>
<Text style={styles.title}>LE SAVIEZ-VOUS ?</Text>
<Text style={styles.text}>{fact}</Text>
</View>
</View>
)
}
export default FunFact
|
techCurriculum/ui/solutions/4.2/src/components/CardForm.js
|
jennybkim/engineeringessentials
|
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import TextInput from './TextInput.js'
class CardForm extends React.Component {
render() {
return (
<form className='card-form'>
<h2>Add a Card</h2>
<TextInput name='username' label='Username'/>
<TextInput name='message' label='Message'/>
</form>
);
}
}
export default CardForm;
|
src/components/Winner.js
|
ivangeorgiew/voteApp
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as actions from '../actions';
import '../index.scss';
export default connect(mapStateToProps)(Winner);
/* MAP STATE TO PROPS */
function mapStateToProps(state) {
return {
winner: state.winner || '',
restart: actions.restart
}
}
/* WINNER */
Winner.propTypes = {
winner: PropTypes.string.isRequired,
restart: PropTypes.func.isRequired
}
function Winner(props) {
if(!props.winner)
return false;
return (
<div className='results'>
<div className='winner'>
Winner is {props.winner}
</div>
<div className='management'>
<button
className='next'
onClick={() => props.dispatch(props.restart())}
>
Restart
</button>
</div>
</div>
);
}
|
node_modules/react-icons/md/casino.js
|
bairrada97/festival
|
import React from 'react'
import Icon from 'react-icon-base'
const MdCasino = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m27.5 15c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m0 15c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m-7.5-7.5c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m-7.5-7.5c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m0 15c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m19.1-25c1.8 0 3.4 1.6 3.4 3.4v23.2c0 1.8-1.6 3.4-3.4 3.4h-23.2c-1.8 0-3.4-1.6-3.4-3.4v-23.2c0-1.8 1.6-3.4 3.4-3.4h23.2z"/></g>
</Icon>
)
export default MdCasino
|
src/pages/paper/edit/editAuthors.js
|
sunway-official/acm-admin
|
import React from 'react';
import { Field } from 'redux-form';
import { MenuItem, Divider } from 'material-ui';
import CustomInput from 'components/CustomInput';
import { renderSelectField } from 'components/render';
import renderCheckbox from 'components/renderCheckbox';
import { Subheader } from 'material-ui';
import { countryData } from '../countryData';
import { titleData } from '../authorTitleData';
import { connect } from 'react-redux';
import { paperOperations } from 'store/ducks/paper';
const styles = {
divider: {
marginTop: '10px',
marginBottom: '10px',
},
smallIcon: {
width: 36,
height: 36,
},
small: {
width: 72,
height: 72,
padding: 16,
},
};
class EditAuthors extends React.Component {
constructor() {
super();
this.state = {
deleteIds: [],
};
}
componentDidMount() {
this.props.fields.removeAll();
const authors = this.props.authors.editAuthors;
const length = authors.length;
for (let i = 0; i < length; i = i + 1) {
let author = {};
let name = [];
let corresponding = false;
name = authors[i].author_name.split(' ');
if (authors[i].corresponding === 2) {
corresponding = true;
} else {
corresponding = false;
}
author = {
id: authors[i].id,
firstname: name[1],
lastname: name[0],
title: authors[i].author_title,
email: authors[i].author_email,
organization: authors[i].author_organization,
authorStreet: authors[i].author_street,
authorCountry: authors[i].author_country,
authorCity: authors[i].author_city,
authorZipcode: authors[i].author_zipcode,
corresponding: corresponding,
};
this.props.fields.push(author);
}
}
render() {
const { fields, meta: { error, submitFailed } } = this.props;
if (!fields) return <div />;
return (
<div>
{fields.map((author, index) => (
<div key={index}>
{index === 0 ? (
''
) : (
<div>
<Divider style={styles.divider} />
<div className="d-flex align-items-center justify-content-space-around" />
</div>
)}
<section className="paper-section">
<div className="paper-card card-add-paper" around="xs">
<Subheader className="subheader submit-header">
Author #{index + 1}
</Subheader>
<div className="d-flex form-group">
<label>First name :</label>
<Field
name={`${author}.firstname`}
component={CustomInput}
fullWidth={true}
hintText="Enter the first name"
/>
</div>
<div className="d-flex form-group">
<label>Last name :</label>
<Field
name={`${author}.lastname`}
component={CustomInput}
fullWidth={true}
hintText="Enter the last name"
/>
</div>
<div className="d-flex form-group">
<label>Title :</label>
<Field
name={`${author}.title`}
component={renderSelectField}
fullWidth={true}
hintText="Choose a title"
>
{titleData.map(title => {
return (
<MenuItem
key={title.value}
value={title.value}
primaryText={title.primaryText}
/>
);
})}
</Field>
</div>
<div className="d-flex form-group">
<label>Email:</label>
<Field
name={`${author}.email`}
component={CustomInput}
fullWidth={true}
hintText="Enter the email"
/>
</div>
<div className="d-flex form-group">
<label>Institution:</label>
<Field
name={`${author}.organization`}
component={CustomInput}
fullWidth={true}
hintText="Enter the institution"
/>
</div>
<div className="d-flex form-group">
<label>Street :</label>
<Field
name={`${author}.authorStreet`}
component={CustomInput}
fullWidth={true}
hintText="Enter the street"
/>
</div>
<div className="d-flex form-group">
<label>City :</label>
<Field
name={`${author}.authorCity`}
component={CustomInput}
fullWidth={true}
hintText="Enter the city"
/>
</div>
<div className="d-flex form-group">
<label>Country :</label>
<Field
name={`${author}.authorCountry`}
component={renderSelectField}
fullWidth={true}
hintText="Choose the country"
>
{countryData.map(country => {
return (
<MenuItem
key={country.label}
value={country.label}
primaryText={country.label}
/>
);
})}
</Field>
</div>
<div className="d-flex form-group">
<label>Zipcode :</label>
<Field
name={`${author}.authorZipcode`}
component={CustomInput}
fullWidth={true}
type="number"
hintText="Enter the zipcode"
/>
</div>
<div className="form-group">
<div className="f-right pb-6">
<Field
label="Corresponding"
name={`${author}.corresponding`}
value={false}
component={renderCheckbox}
type="checkbox"
/>
</div>
</div>
</div>
</section>
</div>
))}
<div className="d-flex add-schedule-icon btn-group">
{/* <FloatingActionButton
mini={true}
className="f-right mb-20"
onClick={() => fields.push({})}
tooltip="Edit Author"
disabled={this.props.checkError}
>
<ContentAdd />
</FloatingActionButton> */}
{submitFailed && error && <span>{error}</span>}
</div>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
deleteAuthors: ids =>
dispatch(paperOperations.deleteAuthorIdsOperation(ids)),
};
};
export default connect(undefined, mapDispatchToProps)(EditAuthors);
|
modules/gui/src/app/home/body/process/recipe/ccdcSlice/panels/source/assetSection.js
|
openforis/sepal
|
import {AssetInput} from 'widget/assetInput'
import {Form} from 'widget/form/form'
import {Layout} from 'widget/layout'
import {Subject} from 'rxjs'
import {compose} from 'compose'
import {connect} from 'store'
import {msg} from 'translate'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
const J_DAYS = 0
const FRACTIONAL_YEARS = 1
const UNIX_TIME_MILLIS = 2
class AssetSection extends React.Component {
constructor(props) {
super(props)
this.assetChanged$ = new Subject()
this.onLoaded = this.onLoaded.bind(this)
}
render() {
const {inputs: {asset, dateFormat}} = this.props
return (
<Layout>
<AssetInput
input={asset}
label={msg('process.ccdcSlice.panel.source.form.asset.label')}
placeholder={msg('process.ccdcSlice.panel.source.form.asset.placeholder')}
autoFocus
onLoaded={this.onLoaded}
/>
<Form.Buttons
label={msg('process.ccdc.panel.dates.form.dateFormat.label')}
input={dateFormat}
disabled={!asset.value}
multiple={false}
options={[
{
value: J_DAYS,
label: msg('process.ccdc.panel.dates.form.dateFormat.jDays.label')
},
{
value: FRACTIONAL_YEARS,
label: msg('process.ccdc.panel.dates.form.dateFormat.fractionalYears.label')
},
{
value: UNIX_TIME_MILLIS,
label: msg('process.ccdc.panel.dates.form.dateFormat.unixTimeMillis.label')
}
]}
/>
</Layout>
)
}
onLoaded({metadata}) {
const {inputs} = this.props
const {bands, properties: {dateFormat}} = metadata
const assetBands = _.intersection(...['coefs', 'magnitude', 'rmse']
.map(postfix => bands
.map(assetBand => assetBand.match(`(.*)_${postfix}`))
.map(match => match && match[1])
.filter(band => band)
)
)
if (assetBands.length) {
dateFormat && inputs.dateFormat.set(dateFormat)
} else {
inputs.asset.setInvalid(msg('process.ccdcSlice.panel.source.asset.notCcdc'))
}
}
}
AssetSection.propTypes = {
inputs: PropTypes.object.isRequired
}
export default compose(
AssetSection,
connect()
)
|
src/routes/RequestPayment/components/Submitted.js
|
vijayasankar/ML2.0
|
import Button from 'react-bootstrap/lib/Button'
import Col from 'react-bootstrap/lib/Col'
import Link from 'react-router/lib/Link'
import React from 'react'
import Row from 'react-bootstrap/lib/Row'
class RequestPaymentSubmitted extends React.Component {
constructor (props) {
super(props)
this.handleFormReset = this.handleFormReset.bind(this)
}
handleFormReset (event) {
this.props.formReset('requestPayment')
}
render () {
return (
<div className={`${this.props.cssName}`}>
<Row>
<Col xs={12} md={9} className='full-width'>
<Row className='pb-2'>
<Col xs={12} md={12}>
<div className={`${this.props.cssName}-text`}>
<strong className={`${this.props.cssName}-text-heading`}>
Please monitor your dashboard for information about this payment request.
</strong>
</div>
</Col>
</Row>
<Row className='text-right'>
<Col xs={12} md={12}>
<Button
className={`${this.props.cssName}-trigger is-another btn primary-btn`}
onClick={this.handleFormReset}
>
Request another payment
</Button>
<Link to='/providerportal/'
className={`${this.props.cssName}-trigger is-done btn primary-btn`}
>
Done
</Link>
</Col>
</Row>
</Col>
</Row>
</div>
)
}
}
RequestPaymentSubmitted.propTypes = {
cssName: React.PropTypes.string,
formReset: React.PropTypes.func
}
export default RequestPaymentSubmitted
|
yymobile/progress/__tests__/index.test.native.js
|
77ircloud/yymobile2
|
import React from 'react';
import renderer from 'react-test-renderer';
// import { shallow } from 'enzyme';
import Progress from '../index';
describe('Progress', () => {
it('renders correctly', () => {
const wrapper = renderer.create(
<Progress percent={30} position="fixed" />,
);
expect(wrapper.toJSON()).toMatchSnapshot();
});
});
|
src/pages/paypal-donate.js
|
ScottDowne/donate.mozilla.org
|
import React from 'react';
import MozillaFooter from '../components/mozilla/footer.js';
import Header from '../components/header.js';
import AmountButtons from '../components/amount-buttons.js';
import Frequency from '../components/donation-frequency.js';
import SubmitButton from '../components/submit-button.js';
import DonateButton from '../components/donate-button.js';
import {paypalLocales} from '../../intl-config.js';
import amountModifier from '../lib/amount-modifier.js';
import listener from '../lib/listener.js';
import form from '../lib/form.js';
var PaypalForm = React.createClass({
contextTypes: {
intl: React.PropTypes.object
},
getInitialState: function() {
return {
amount: "",
currency: {}
};
},
componentDidMount: function() {
listener.on("fieldUpdated", this.onFieldUpdated);
listener.on("stateUpdated", this.onStateUpdated);
},
componentWillUnmount: function() {
listener.off("fieldUpdated", this.onFieldUpdated);
listener.off("stateUpdated", this.onStateUpdated);
},
onFieldUpdated: function(e) {
var detail = e.detail;
if (detail.field === "amount") {
this.setState({
amount: detail.value
});
}
},
onStateUpdated: function(e) {
var detail = e.detail;
if (detail.state === "currency") {
this.setState({
currency: detail.value
});
}
},
submit: function(frequency) {
if (frequency === "monthly") {
this.refs.paypalRecurring.submit();
} else {
this.refs.paypalOneTime.submit();
}
},
render: function() {
var amount = this.state.amount;
var currencyCode = this.state.currency.code || "";
var locale = this.context.intl.locale;
return (
<span>
<form action={process.env.PAYPAL_ENDPOINT + "/cgi-bin/webscr"} method="post" target="_top" ref="paypalOneTime">
<input type="hidden" name="cmd" value="_donations"/>
<input type="hidden" name="business" value={process.env.PAYPAL_EMAIL}/>
<input type="hidden" name="lc" value={paypalLocales[locale]}/>
<input type="hidden" name="item_name" value={this.context.intl.formatMessage({id: "mozilla_donation"})}/>
<input type="hidden" name="no_note" value="1"/>
<input type="hidden" name="no_shipping" value="1"/>
<input type="hidden" name="rm" value="1"/>
{/* Donation Amount */}
<input type="hidden" name="amount" value={amountModifier.paypal(amount, currencyCode)}/>
<input type="hidden" name="return" value={process.env.APPLICATION_URI + "/" + locale + "/thank-you/"}/>
<input type="hidden" name="currency_code" value={currencyCode.toUpperCase()}/>
</form>
<form action={process.env.PAYPAL_ENDPOINT + "/cgi-bin/webscr"} method="post" ref="paypalRecurring">
<input type="hidden" name="cmd" value="_xclick-subscriptions"/>
<input type="hidden" name="business" value={process.env.PAYPAL_EMAIL}/>
<input type="hidden" name="lc" value={paypalLocales[locale]}/>
<input type="hidden" name="item_name" value={this.context.intl.formatMessage({id: "mozilla_monthly_donation"})}/>
<input type="hidden" name="no_note" value="1"/>
<input type="hidden" name="no_shipping" value="2"/>
<input type="hidden" name="return" value={process.env.APPLICATION_URI + "/" + locale + "/thank-you/"}/>
<input type="hidden" name="src" value="1"/>
<input type="hidden" name="p3" value="1"/>
<input type="hidden" name="currency_code" value={currencyCode.toUpperCase()}/>
<input type="hidden" name="t3" value="M"/>
<input name="srt" type="hidden" value="0"/>
<input type="hidden" name="a3" value={amountModifier.paypal(amount, currencyCode)}/>
</form>
</span>
);
}
});
var PAYPAL_SUBMITTING = 3;
var simplePaypal = React.createClass({
mixins: [require('../mixins/form.js')],
simplePaypal: function(validate, props) {
var valid = form.validate(validate);
var submitProps = {};
if (valid) {
this.setState({
submitting: PAYPAL_SUBMITTING
});
submitProps = form.buildProps(props);
this.refs.paypalForm.submit(submitProps.frequency);
}
},
render: function() {
var className = "row";
if (this.props.test) {
className += " " + this.props.test;
}
return (
<div className={className}>
<Header>
<h3>
{this.context.intl.formatMessage({id: "donate_now"})}
</h3>
</Header>
<div className="simple-paypal">
<div className="container">
<div className="wrap">
<div className="row">
<img src="/assets/images/paypal_logo@2x.603485f928e450e7098eb55bc982e19a.png" alt="PayPal Logo" width="140" height="58"/>
<p id="secure-label">
<i className="fa fa-lock"></i>
{this.context.intl.formatMessage({id: "secure"})}
</p>
</div>
<div className="row">
<div className="full">
<h4>{this.context.intl.formatMessage({id: "select_donation"})}</h4>
</div>
</div>
<div className="row">
<div className="full">
<AmountButtons name="amount"/>
<Frequency name="frequency"/>
<SubmitButton
submitting={this.state.submitting === PAYPAL_SUBMITTING}
validate={["amount"]}
onSubmit={this.simplePaypal}
submit={["amount", "frequency"]}
>
<DonateButton/>
</SubmitButton>
</div>
</div>
</div>
</div>
<div className="row">
<p className="donation-notice">
{this.context.intl.formatMessage({id: "donation_notice"})}
</p>
</div>
<PaypalForm ref="paypalForm"/>
</div>
<MozillaFooter/>
</div>
);
}
});
module.exports = simplePaypal;
|
src/main/webapp/pkgs/backbone.js/backbone.js
|
haxwell/quizki
|
// Backbone.js 1.1.2
// (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = require('underscore');
factory(root, exports, _);
// Finally, as a browser global.
} else {
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
// Initial Setup
// -------------
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.1.2';
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = $;
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj) (listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = options;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
options = this._pending;
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = _.extend({validate: true}, options);
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !options.wait) {
if (!this.set(attrs, options)) return false;
} else {
if (!this._validate(attrs, options)) return false;
}
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return !this.has(this.idAttribute);
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.extend({merge: false}, options, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
var singular = !_.isArray(models);
models = singular ? [models] : _.clone(models);
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = models[i] = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model, options);
}
return singular ? models[0] : models;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults({}, options, setOptions);
if (options.parse) models = this.parse(models, options);
var singular = !_.isArray(models);
models = singular ? (models ? [models] : []) : _.clone(models);
var i, l, id, model, attrs, existing, sort;
var at = options.at;
var targetModel = this.model;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
var add = options.add, merge = options.merge, remove = options.remove;
var order = !sortable && add && remove ? [] : false;
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
attrs = models[i] || {};
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute || 'id'];
}
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(attrs, options);
if (!model) continue;
toAdd.push(model);
this._addReference(model, options);
}
// Do not add multiple models with the same `id`.
model = existing || model;
if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
modelMap[model.id] = true;
}
// Remove nonexistent models if appropriate.
if (remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length || (order && order.length)) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
for (i = 0, l = toAdd.length; i < l; i++) {
this.models.splice(at + i, 0, toAdd[i]);
}
} else {
if (order) this.models.length = 0;
var orderedModels = order || toAdd;
for (i = 0, l = orderedModels.length; i < l; i++) {
this.models.push(orderedModels[i]);
}
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
if (sort || (order && order.length)) this.trigger('sort', this, options);
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
// Add a model to the end of the collection.
push: function(model, options) {
return this.add(model, _.extend({at: this.length}, options));
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
return this.add(model, _.extend({at: 0}, options));
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function() {
return slice.apply(this.models, arguments);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
options.success = function(model, resp) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) return attrs;
options = options ? _.clone(options) : {};
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
// Internal method to create a model's ties to a collection.
_addReference: function(model, options) {
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
if (!model.collection) model.collection = this;
model.on('all', this._onModelEvent, this);
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model, options) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
'lastIndexOf', 'isEmpty', 'chain', 'sample'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be preferred to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && noXhrPatch) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
var noXhrPatch =
typeof window !== 'undefined' && !!window.ActiveXObject &&
!(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
router.execute(callback, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Execute a route handler with the provided parameters. This is an
// excellent place to do pre-route setup or post-route cleanup.
execute: function(callback, args) {
if (callback) callback.apply(this, args);
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^/?]+)';
})
.replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param, i) {
// Don't decode the search params.
if (i === params.length - 1) return param || null;
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Cached regex for stripping urls of hash.
var pathStripper = /#.*$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Are we at the app root?
atRoot: function() {
return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
},
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = decodeURI(this.location.pathname + this.location.search);
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">');
this.iframe = frame.hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !this.atRoot()) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && this.atRoot() && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment);
}
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragment) {
fragment = this.fragment = this.getFragment(fragment);
return _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: !!options};
var url = this.root + (fragment = this.getFragment(fragment || ''));
// Strip the hash for matching.
fragment = fragment.replace(pathStripper, '');
if (this.fragment === fragment) return;
this.fragment = fragment;
// Don't include a trailing slash on the root.
if (fragment === '' && url !== '/') url = url.slice(0, -1);
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function(model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
return Backbone;
}));
|
src/routes/login/Login.js
|
fkn/ndo
|
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import {
FormGroup,
Button,
ControlLabel,
FormControl,
HelpBlock,
PageHeader,
} from 'react-bootstrap';
import s from './Login.css';
class Login extends React.Component {
static contextTypes = {
fetch: PropTypes.func.isRequired,
};
state = {
email: '',
password: '',
};
getValidationState() {
const { email } = this.state;
if (!email.length) return null;
if (/^[a-zA-Z0-9+.\-_]+@[a-zA-Z0-9+.\-_]+$/.test(email)) {
return 'success';
}
return 'error';
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value,
});
};
render() {
const { email, password } = this.state;
return (
<div className={s.root}>
<div className={s.container}>
<PageHeader>Log in to NDO</PageHeader>
<form action="/login" method="post">
<FormGroup
bsSize="large"
controlId="email"
validationState={this.getValidationState()}
>
<ControlLabel>Username or email address</ControlLabel>
<FormControl
required
type="email"
name="usernameOrEmail"
autoFocus
value={email}
onChange={this.handleChange}
/>
<FormControl.Feedback />
</FormGroup>
<FormGroup bsSize="large" controlId="password">
<ControlLabel>Password</ControlLabel>
<FormControl
required
minLength={6}
type="password"
name="password"
value={password}
onChange={this.handleChange}
/>
<HelpBlock>Make sure it`s at least 6 characters.</HelpBlock>
</FormGroup>
<FormGroup>
<Button bsSize="large" bsStyle="primary" type="submit" block>
Log in
</Button>
</FormGroup>
{/* <HelpBlock>
Don`t have an account?
<Button bsStyle="link" href="/register">
Sign up
</Button>
</HelpBlock> */}
<Button bsStyle="link" href="login/facebook" block>
<svg
className={s.icon}
width="30"
height="30"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M22 16l1-5h-5V7c0-1.544.784-2 3-2h2V0h-4c-4.072 0-7 2.435-7 7v4H7v5h5v14h6V16h4z" />
</svg>
Log in with Facebook
</Button>
</form>
</div>
</div>
);
}
}
export default withStyles(s)(Login);
|
webpack/scenes/Subscriptions/UpstreamSubscriptions/UpstreamSubscriptionsPage.js
|
pmoravec/katello
|
import React, { Component } from 'react';
import _ from 'lodash';
import { translate as __ } from 'foremanReact/common/I18n';
import PropTypes from 'prop-types';
import { LinkContainer } from 'react-router-bootstrap';
import { Grid, Row, Col } from 'react-bootstrap';
import BreadcrumbsBar from 'foremanReact/components/BreadcrumbBar';
import { Button } from 'patternfly-react';
import { stringIsPositiveNumber } from 'foremanReact/common/helpers';
import { urlBuilder } from 'foremanReact/common/urlHelpers';
import { LoadingState } from '../../../move_to_pf/LoadingState';
import { Table } from '../../../move_to_foreman/components/common/table';
import { columns } from './UpstreamSubscriptionsTableSchema';
class UpstreamSubscriptionsPage extends Component {
constructor(props) {
super(props);
this.state = {
selectedRows: [],
};
}
componentDidMount() {
this.loadData();
}
onChange = (value, rowData) => {
const { selectedRows } = this.state;
const pool = {
...rowData,
id: rowData.id,
updatedQuantity: value,
selected: true,
};
const match = this.poolInSelectedRows(pool);
const index = _.indexOf(selectedRows, match);
if (value) {
if (match) {
selectedRows.splice(index, 1, pool);
} else {
selectedRows.push(pool);
}
} else if (match) {
selectedRows.splice(index, 1);
}
this.setState({ selectedRows });
};
// eslint-disable-next-line class-methods-use-this
quantityValidation(pool) {
const origQuantity = pool.updatedQuantity;
if (origQuantity && stringIsPositiveNumber(origQuantity)) {
const parsedQuantity = parseInt(origQuantity, 10);
const aboveZeroMsg = [false, __('Please enter a positive number above zero')];
if (parsedQuantity.toString().length > 10) return [false, __('Please limit number to 10 digits')];
if (!pool.available) return [false, __('No pools available')];
// handling unlimited subscriptions, they show as -1
if (pool.available === -1) return parsedQuantity ? [true, ''] : aboveZeroMsg;
if (parsedQuantity > pool.available) return [false, __(`Quantity must not be above ${pool.available}`)];
if (parsedQuantity <= 0) return aboveZeroMsg;
} else {
return [false, __('Please enter digits only')];
}
return [true, ''];
}
poolInSelectedRows(pool) {
const { selectedRows } = this.state;
return _.find(
selectedRows,
foundPool => pool.id === foundPool.id,
);
}
quantityValidationInput = (pool) => {
if (!pool || pool.updatedQuantity === undefined) return null;
if (this.quantityValidation(pool)[0]) {
return 'success';
}
return 'error';
};
validateSelectedRows = () => Array.isArray(this.state.selectedRows) &&
this.state.selectedRows.length &&
this.state.selectedRows.every(pool => this.quantityValidation(pool)[0]);
saveUpstreamSubscriptions = async () => {
const updatedPools = _.map(
this.state.selectedRows,
pool => ({ ...pool, quantity: parseInt(pool.updatedQuantity, 10) }),
);
const updatedSubscriptions = { pools: updatedPools };
await this.props.saveUpstreamSubscriptions(updatedSubscriptions);
const { task } = this.props.upstreamSubscriptions;
// TODO: could probably factor this out into a task response component
if (task) {
const message = (
<span>
<span>{__('Subscriptions have been saved and are being updated. ')}</span>
<a href={urlBuilder('foreman_tasks/tasks', '', task.id)}>
{__('Click here to go to the tasks page for the task.')}
</a>
</span>
);
window.tfm.toastNotifications.notify({ message, type: 'success' });
this.props.history.push('/subscriptions');
}
};
loadData() {
this.props.loadUpstreamSubscriptions();
}
render() {
const { upstreamSubscriptions } = this.props;
const getSubscriptionActions = () => {
let actions = '';
if (upstreamSubscriptions.results.length > 0) {
actions = (
<Row>
<Col sm={12}>
<Button
style={{ marginTop: '10px', marginRight: '5px' }}
bsStyle="primary"
type="submit"
disabled={upstreamSubscriptions.loading ||
!this.validateSelectedRows()}
onClick={this.saveUpstreamSubscriptions}
>
{__('Submit')}
</Button>
<LinkContainer to="/subscriptions" style={{ marginTop: '10px' }}>
<Button>
{__('Cancel')}
</Button>
</LinkContainer>
</Col>
</Row>
);
}
return actions;
};
const onPaginationChange = (pagination) => {
this.props.loadUpstreamSubscriptions({
...pagination,
});
};
const getSelectedUpstreamSubscriptions = () => {
const newUpstreamSubscriptions = [];
upstreamSubscriptions.results.forEach((sub) => {
let row = this.poolInSelectedRows(sub);
if (row) {
row = { ...row, selected: true };
} else {
const foundRow = upstreamSubscriptions.results.find(foundSub => sub.id === foundSub.id);
row = { ...foundRow, selected: false };
}
newUpstreamSubscriptions.push(row);
});
return newUpstreamSubscriptions;
};
const emptyStateData = () => ({
header: __('There are no Subscription Allocations to display'),
description: __('Subscription Allocations allow you to export subscriptions from the Red Hat Customer Portal to ' +
'an on-premise subscription management application such as Red Hat Satellite.'),
action: {
title: __('Import a Manifest to Begin'),
url: '/subscriptions',
},
});
const checkAllRowsSelected = () =>
upstreamSubscriptions.results.length === this.state.selectedRows.length;
const selectionController = {
allRowsSelected: () => checkAllRowsSelected(),
selectAllRows: () => {
if (checkAllRowsSelected()) {
this.setState({ selectedRows: [] });
} else {
this.setState({ selectedRows: [...upstreamSubscriptions.results] });
}
},
selectRow: ({ rowData }) => {
let { selectedRows } = this.state;
if (selectedRows.find(r => r.id === rowData.id)) {
selectedRows = selectedRows.filter(e => e.id !== rowData.id);
} else {
selectedRows.push(rowData);
}
this.setState({ selectedRows });
},
isSelected: ({ rowData }) => (
this.state.selectedRows.find(r => r.id === rowData.id) !== undefined
),
};
const tableColumns = columns(this, selectionController);
const rows = getSelectedUpstreamSubscriptions();
return (
<Grid bsClass="container-fluid">
<BreadcrumbsBar data={{
isSwitchable: false,
breadcrumbItems: [
{
caption: __('Subscriptions'),
onClick: () => this.props.history.push('/subscriptions'),
},
{
caption: __('Add Subscriptions'),
},
],
}}
/>
<LoadingState loading={upstreamSubscriptions.loading} loadingText={__('Loading')}>
<Row>
<Col sm={12}>
<Table
rows={rows}
columns={tableColumns}
emptyState={emptyStateData()}
itemCount={upstreamSubscriptions.itemCount}
pagination={upstreamSubscriptions.pagination}
onPaginationChange={onPaginationChange}
/>
</Col>
</Row>
{getSubscriptionActions()}
</LoadingState>
</Grid>
);
}
}
UpstreamSubscriptionsPage.propTypes = {
loadUpstreamSubscriptions: PropTypes.func.isRequired,
saveUpstreamSubscriptions: PropTypes.func.isRequired,
upstreamSubscriptions: PropTypes.shape({
loading: PropTypes.bool,
itemCount: PropTypes.number,
results: PropTypes.array,
pagination: PropTypes.shape({}),
task: PropTypes.shape({
id: PropTypes.number,
}),
}).isRequired,
history: PropTypes.shape({ push: PropTypes.func.isRequired }).isRequired,
};
export default UpstreamSubscriptionsPage;
|
pages/index.js
|
kepatopoc/gatsby-starter-clean
|
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from "react-helmet"
import { config } from 'config'
export default class Index extends React.Component {
render () {
return (
<div>
<Helmet
title={config.siteTitle}
meta={[
{"name": "description", "content": "Sample"},
{"name": "keywords", "content": "sample, something"},
]}
/>
<h1>
Hello World!
</h1>
<p>Welcome to your new clean Gatsby site</p>
<p>Welcome to your new clean Gatsby site</p>
## Новый текст
</div>
)
}
}
|
components/default/aside.js
|
JobLeonard/idyll-p5
|
const React = require('react');
const IdyllComponent = require('idyll-component');
class Aside extends IdyllComponent {
render() {
return (
<div className={'aside-container'}>
<div className={'aside'}>
{this.props.children}
</div>
</div>
);
}
}
module.exports = Aside;
|
examples/with-custom-webpack-config/src/client.js
|
jaredpalmer/react-production-starter
|
import React from 'react';
import { hydrate } from 'react-dom';
import App from './App';
hydrate(<App />, document.getElementById('root'));
if (module.hot) {
module.hot.accept();
}
|
app/containers/HomePage.js
|
dfucci/Borrowr
|
import React, { Component } from 'react';
import Home from '../components/Home';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { removeBook } from '../actions/books';
function mapStateToProps(state) {
return {
filter: state.filter
};
}
function mapDispatchToProps(dispatch) {
// return bindActionCreators(bookActions, dispatch);
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
|
src/app/components/Header.js
|
zendra1994/react-ssr
|
import React from 'react';
import { Link } from 'react-router';
export default class Header extends React.Component {
render() {
return (
<header>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</header>
)
}
}
|
packages/react-static/src/static/__mocks__/pages/404.js
|
nozzle/react-static
|
import React from 'react'
//
export default () => (
<div>
<h1>404 - Oh no's! We couldn't find that page :(</h1>
</div>
)
|
heesong/src/App.js
|
hanheesong/hanheesong.github.io
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
|
src/svg-icons/hardware/scanner.js
|
rscnt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareScanner = (props) => (
<SvgIcon {...props}>
<path d="M19.8 10.7L4.2 5l-.7 1.9L17.6 12H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-5.5c0-.8-.5-1.6-1.2-1.8zM7 17H5v-2h2v2zm12 0H9v-2h10v2z"/>
</SvgIcon>
);
HardwareScanner = pure(HardwareScanner);
HardwareScanner.displayName = 'HardwareScanner';
export default HardwareScanner;
|
ajax/libs/yui/3.10.1/event-focus/event-focus-debug.js
|
pombredanne/cdnjs
|
YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@', {"requires": ["event-synthetic"]});
|
es6/Checkbox/CheckBoxButton.js
|
yurizhang/ishow
|
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import CheckBox from './CheckBox';
var CheckboxButton = function (_CheckBox) {
_inherits(CheckboxButton, _CheckBox);
function CheckboxButton() {
_classCallCheck(this, CheckboxButton);
return _possibleConstructorReturn(this, (CheckboxButton.__proto__ || Object.getPrototypeOf(CheckboxButton)).apply(this, arguments));
}
_createClass(CheckboxButton, [{
key: 'render',
value: function render() {
var group = this.context.ElCheckboxGroup;
return React.createElement(
'label',
{ style: this.style(), className: this.className('ishowcheckbox-button', group.props.size ? 'ishowcheckbox-button--' + group.props.size : '', {
'is-disabled': this.props.disabled,
'is-checked': this.state.checked,
'is-focus': this.state.focus
}) },
React.createElement('input', {
className: 'ishowcheckbox-button__original',
type: 'checkbox',
checked: this.state.checked,
disabled: this.props.disabled,
onFocus: this.onFocus.bind(this),
onBlur: this.onBlur.bind(this),
onChange: this.onChange.bind(this)
}),
React.createElement(
'span',
{ className: 'ishowcheckbox-button__inner', style: this.state.checked ? {
boxShadow: '-1px 0 0 0 ' + group.props.fill,
backgroundColor: group.props.fill || '',
borderColor: group.props.fill || '',
color: group.props.textColor || ''
} : {} },
this.state.label || this.props.children
)
);
}
}]);
return CheckboxButton;
}(CheckBox);
CheckboxButton.elementType = 'CheckboxButton';
export default CheckboxButton;
|
ajax/libs/yasqe/1.2.2/yasqe.min.js
|
KOLANICH/cdnjs
|
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=i[s]={exports:{}};e[s][0].call(u.exports,function(t){var i=e[s][1][t];return n(i?i:t)},u,u.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e){$=jquery=e("jquery"),$.deparam=function(e,t){var i={},r={"true":!0,"false":!1,"null":null};return $.each(e.replace(/\+/g," ").split("&"),function(e,n){var o,s=n.split("="),a=decodeURIComponent(s[0]),l=i,u=0,p=a.split("]["),c=p.length-1;if(/\[/.test(p[0])&&/\]$/.test(p[c])?(p[c]=p[c].replace(/\]$/,""),p=p.shift().split("[").concat(p),c=p.length-1):c=0,2===s.length)if(o=decodeURIComponent(s[1]),t&&(o=o&&!isNaN(o)?+o:"undefined"===o?void 0:void 0!==r[o]?r[o]:o),c)for(;c>=u;u++)a=""===p[u]?l.length:p[u],l=l[a]=c>u?l[a]||(p[u+1]&&isNaN(p[u+1])?{}:[]):o;else $.isArray(i[a])?i[a].push(o):i[a]=void 0!==i[a]?[i[a],o]:o;else a&&(i[a]=t?void 0:"")}),i}},{jquery:9}],2:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)}(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",E="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+E+")";"sparql11"==u?(e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?",t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"):(e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?",t="_:"+e);var f="("+p+")?:",m=f+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",L="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",I="\\+"+x,T="\\+"+N,y="\\+"+L,A="-"+x,S="-"+N,C="-"+L,R="\\\\[tbnrf\\\\\"']",b="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+")*'",O='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+')*"',P="'''(('|'')?([^'\\\\]|"+R+"))*'''",D='"""(("|"")?([^"\\\\]|'+R+'))*"""',_="[\\x20\\x09\\x0D\\x0A]",M="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",w="("+_+"|("+M+"))*",G="\\("+w+"\\)",k="\\["+w+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+_+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+M),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+L),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+b),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+O),style:"string"},{name:"NIL",regex:new RegExp("^"+G),style:"punc"},{name:"ANON",regex:new RegExp("^"+k),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+f),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return B}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<E.length;++i)if(t=e.match(E[i].regex,!0,!1))return{cat:E[i].name,style:E[i].style,text:t[0]};return(t=e.match(s,!0,!1))?{cat:e.current().toUpperCase(),style:"keyword",text:t[0]}:(t=e.match(a,!0,!1))?{cat:e.current(),style:"punc",text:t[0]}:(t=e.match(/^.[A-Za-z0-9]*/,!0,!1),{cat:"<invalid_token>",style:"error",text:t[0]})}function n(){var i=e.column();t.errorStartPos=i,t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat)return 1==t.OK&&(t.OK=!1,n()),t.complete=!1,c.style;if("WS"==c.cat||"COMMENT"==c.cat)return t.possibleCurrent=t.possibleNext,c.style;for(var d,h=!1,f=c.cat;t.stack.length>0&&f&&t.OK&&!h;)if(d=t.stack.pop(),o[d]){var m=o[d][f];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else t.OK=!1,t.complete=!1,n(),t.stack.push(d)}else if(d==f){h=!0,l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v,t.storeProperty&&"punc"!=f.cat&&(t.lastProperty=c.text,t.storeProperty=!1)}else t.OK=!1,t.complete=!1,n();return!h&&t.OK&&(t.OK=!1,t.complete=!1,n()),t.possibleCurrent=t.possibleNext,t.possibleNext=i(t.stack[t.stack.length-1]),c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];s&&(r+=s,--n)}for(;n>=0;--n){var s=f[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),E=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},f={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}}),e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:8}],3:[function(e,t){t.exports=Trie=function(){this.words=0,this.prefixes=0,this.children=[]},Trie.prototype={insert:function(e,t){if(0!=e.length){var i,r,n=this;if(void 0===t&&(t=0),t===e.length)return void n.words++;n.prefixes++,i=e[t],void 0===n.children[i]&&(n.children[i]=new Trie),r=n.children[i],r.insert(e,t+1)}},remove:function(e,t){if(0!=e.length){var i,r,n=this;if(void 0===t&&(t=0),void 0!==n){if(t===e.length)return void n.words--;n.prefixes--,i=e[t],r=n.children[i],r.remove(e,t+1)}}},update:function(e,t){0!=e.length&&0!=t.length&&(this.remove(e),this.insert(t))},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;return void 0===t&&(t=0),t===e.length?n.words:(i=e[t],r=n.children[i],void 0!==r&&(o=r.countWord(e,t+1)),o)},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;if(void 0===t&&(t=0),t===e.length)return n.prefixes;var i=e[t];return r=n.children[i],void 0!==r&&(o=r.countPrefix(e,t+1)),o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];if(void 0===e&&(e=""),void 0===r)return[];r.words>0&&n.push(e);for(t in r.children)i=r.children[t],n=n.concat(i.getAllWords(e+t));return n},autoComplete:function(e,t){if(0==e.length)return[];var i,r,n=this;return void 0===t&&(t=0),i=e[t],r=n.children[i],void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],4:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var E=e.getLine(d);if(E){var h=i>0?0:E.length-1,f=i>0?E.length:-1;if(!(E.length>o))for(d==t.line&&(h=t.ch-(0>i?1:0));h!=f;h+=i){var m=E.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c})),p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){l&&(l(),l=null),l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n),i&&(t.state.matchBrackets="object"==typeof i?i:{},t.on("cursorActivity",n))}),e.defineExtension("matchBrackets",function(){r(this,!0)}),e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)}),e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":8}],5:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";function t(e,t){this.cm=e,this.options=this.buildOptions(t),this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i,o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t,this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints",this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var E=p.appendChild(document.createElement("li")),h=c[d],f=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(f=h.className+" "+f),E.className=f,h.render?h.render(E,o,h):E.appendChild(document.createTextNode(h.displayText||i(h))),E.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px",p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),L=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var I=p.getBoundingClientRect(),T=I.bottom-L;if(T>0){var y=I.bottom-I.top,A=I.top-(m.bottom-m.top);if(A-y>0)p.style.top=(v=A-y)+"px",x=!1;else if(y>L){p.style.height=L-5+"px",p.style.top=(v=m.bottom-I.top)+"px";var S=u.getCursor();o.from.ch!=S.ch&&(m=u.cursorCoords(S),p.style.left=(g=m.left)+"px",I=p.getBoundingClientRect())}}var C=I.left-N;if(C>0&&(I.right-I.left>N&&(p.style.width=N-5+"px",C-=I.right-I.left-N),p.style.left=(g=m.left-C)+"px"),u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o})),t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)}),u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();return u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);return x||(n+=p.offsetHeight),n<=i.top||n>=i.bottom?t.close():(p.style.top=r+"px",void(p.style.left=g+b.left-e.left+"px"))}),e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);t&&null!=t.hintId&&(l.changeActive(t.hintId),l.pick())}),e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);i&&null!=i.hintId&&(l.changeActive(i.hintId),t.options.completeOnSingleClick&&l.pick())}),e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)}),e.signal(o,"select",c[0],p.firstChild),!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)},e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n)return e.signal(this,"startCompletion",this),n.async?void n(this,function(e){r.showHints(e)},r.options):r.showHints(n(this,r.options))}}),t.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.widget&&this.widget.close(),this.onClose&&this.onClose(),e.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete"),e.signal(t,"pick",n),this.close()},showHints:function(e){return e&&e.list.length&&this.active()?void(this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e)):this.close()},showWidget:function(t){function i(){l||(l=!0,p.close(),p.cm.off("cursorActivity",a),t&&e.signal(t,"close"))}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){if(t=e,!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close(),p.widget=new o(p,t)}}function s(){u&&(f(u),u=0)}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);e.line!=d.line||t.length-e.ch!=E-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1))?p.close():(u=h(r),p.widget&&p.widget.close())}this.widget=new o(this,t),e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),E=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},f=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a),this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null,this.hints.parentNode.removeChild(this.hints),this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;this.completion.options.closeOnUnfocus&&(e.off("blur",this.onBlur),e.off("focus",this.onFocus)),e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){if(t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1),this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,""),r=this.hints.childNodes[this.selectedHint=t],r.className+=" "+a,r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)}),e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0}),e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":8}],6:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="",r=function(e,t){if("\n"==e)return u.appendChild(document.createTextNode(a?"\r":e)),void(p=0);for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r),p+=e.length-r;break}p+=n-r,i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-"),c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),E=0,h=c.length;h>E;++E){E&&r("\n");var f=new e.StringStream(c[E]);for(!f.string&&o.blankLine&&o.blankLine(d);!f.eol();){var m=o.token(f,d);r(f.current(),m,E,f.start,d),f.start=f.pos}}}})},{"../../lib/codemirror":8}],7:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";function t(e,t,n,o){if(this.atOccurrence=!1,this.doc=e,null==o&&"string"==typeof t&&(o=!1),n=n?e.clipPos(n):r(0,0),this.pos={from:n,to:n},"string"!=typeof t)t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g")),this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;if(o=u,s=o.index,l=o.index+(o[0].length||1),l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0};else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1)return p=i(l,u,p),{from:r(o.line,p),to:r(o.line,p+s.length)}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1)return p=i(l,u,p)+o.ch,{from:r(o.line,p),to:r(o.line,p+s.length)}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var E=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(e.getLine(s).slice(0,u[n].length)==l[n])return{from:E,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);return i.pos={from:t,to:t},i.atOccurrence=!1,!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n))return this.atOccurrence=!0,this.pos.match||!0;if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to),this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}},e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)}),e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)}),e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":8}],8:[function(t,i,r){!function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}}(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r||{},no(Ns,r,!1),h(r);var n=r.value;"string"==typeof n&&(n=new Ws(n,r.mode)),this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this,p(this),l(this),r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),r.autofocus&&!Jo&&Ei(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new Qn},Bo&&setTimeout(oo(di,this,!0),20),mi(this),No();var s=this;$t(this,function(){s.curOp.forceUpdate=!0,vn(s,n),r.autofocus&&!Jo||ho()==o.input?setTimeout(oo(Ui,s),20):Vi(s);for(var e in Ls)Ls.hasOwnProperty(e)&&Ls[e](s,r[e],Is);for(var t=0;t<Ss.length;++t)Ss[t](s)})}function t(e,t){var i=this,r=i.input=uo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");Wo?r.style.width="1000px":r.setAttribute("wrap","off"),Zo&&(r.style.border="1px solid black"),r.setAttribute("autocorrect","off"),r.setAttribute("autocapitalize","off"),r.setAttribute("spellcheck","false"),i.inputDiv=uo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),i.scrollbarH=uo("div",[uo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar"),i.scrollbarV=uo("div",[uo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i.scrollbarFiller=uo("div",null,"CodeMirror-scrollbar-filler"),i.gutterFiller=uo("div",null,"CodeMirror-gutter-filler"),i.lineDiv=uo("div",null,"CodeMirror-code"),i.selectionDiv=uo("div",null,null,"position: relative; z-index: 1"),i.cursorDiv=uo("div",null,"CodeMirror-cursors"),i.measure=uo("div",null,"CodeMirror-measure"),i.lineMeasure=uo("div",null,"CodeMirror-measure"),i.lineSpace=uo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none"),i.mover=uo("div",[uo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative"),i.sizer=uo("div",[i.mover],"CodeMirror-sizer"),i.heightForcer=uo("div",null,null,"position: absolute; height: "+ta+"px; width: 1px;"),i.gutters=uo("div",null,"CodeMirror-gutters"),i.lineGutter=null,i.scroller=uo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll"),i.scroller.setAttribute("tabIndex","-1"),i.wrapper=uo("div",[i.inputDiv,i.scrollbarH,i.scrollbarV,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror"),Uo&&(i.gutters.style.zIndex=-1,i.scroller.style.paddingRight=0),Zo&&(r.style.width="0px"),Wo||(i.scroller.draggable=!0),Ko&&(i.inputDiv.style.height="1px",i.inputDiv.style.position="absolute"),Uo&&(i.scrollbarH.style.minHeight=i.scrollbarV.style.minWidth="18px"),e.appendChild?e.appendChild(i.wrapper):e(i.wrapper),i.viewFrom=i.viewTo=t.first,i.view=[],i.externalMeasured=null,i.viewOffset=0,i.lastSizeC=0,i.updateLineNumbers=null,i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null,i.prevInput="",i.alignWidgets=!1,i.pollingFast=!1,i.poll=new Qn,i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null,i.inaccurateSelection=!1,i.maxLine=null,i.maxLineLength=0,i.maxLineChanged=!1,i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null,i.shift=!1,i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption),r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.frontier=e.doc.first,vt(e,100),e.state.modeGen++,e.curOp&&ii(e)}function n(e){e.options.lineWrapping?(go(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth=""):(mo(e.display.wrapper,"CodeMirror-wrap"),E(e)),s(e),ii(e),wt(e),setTimeout(function(){m(e)},100)}function o(e){var t=zt(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/Xt(e.display)-3);return function(n){if(Wr(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&In(e,t)})}function a(e){var t=Ps[e.options.keyMap],i=t.style;e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(i?" cm-keymap-"+i:"")}function l(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),wt(e)}function u(e){p(e),ii(e),setTimeout(function(){v(e)},20)}function p(e){var t=e.display.gutters,i=e.options.gutters;po(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(uo("div",null,"CodeMirror-gutter "+n));"CodeMirror-linenumbers"==n&&(e.display.lineGutter=o,o.style.width=(e.display.lineNumWidth||1)+"px")}t.style.display=r?"":"none",c(e)}function c(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px",e.display.scrollbarH.style.left=e.options.fixedGutter?t+"px":0}function d(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=kr(r);){var n=t.find(0,!0);r=n.from.line,i+=n.from.ch-n.to.ch}for(r=e;t=Br(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch,r=n.to.line,i+=r.text.length-n.to.ch}return i}function E(e){var t=e.display,i=e.doc;t.maxLine=xn(i,i.first),t.maxLineLength=d(t.maxLine),t.maxLineChanged=!0,i.iter(function(e){var i=d(e);i>t.maxLineLength&&(t.maxLineLength=i,t.maxLine=e)})}function h(e){var t=to(e.gutters,"CodeMirror-linenumbers");-1==t&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function f(e){var t=e.display.scroller;return{clientHeight:t.clientHeight,barHeight:e.display.scrollbarV.clientHeight,scrollWidth:t.scrollWidth,clientWidth:t.clientWidth,barWidth:e.display.scrollbarH.clientWidth,docHeight:Math.round(e.doc.height+Tt(e.display))}}function m(e,t){t||(t=f(e));var i=e.display,r=t.docHeight+ta,n=t.scrollWidth>t.clientWidth,o=r>t.clientHeight;if(o?(i.scrollbarV.style.display="block",i.scrollbarV.style.bottom=n?Io(i.measure)+"px":"0",i.scrollbarV.firstChild.style.height=Math.max(0,r-t.clientHeight+(t.barHeight||i.scrollbarV.clientHeight))+"px"):(i.scrollbarV.style.display="",i.scrollbarV.firstChild.style.height="0"),n?(i.scrollbarH.style.display="block",i.scrollbarH.style.right=o?Io(i.measure)+"px":"0",i.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||i.scrollbarH.clientWidth)+"px"):(i.scrollbarH.style.display="",i.scrollbarH.firstChild.style.width="0"),n&&o?(i.scrollbarFiller.style.display="block",i.scrollbarFiller.style.height=i.scrollbarFiller.style.width=Io(i.measure)+"px"):i.scrollbarFiller.style.display="",n&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(i.gutterFiller.style.display="block",i.gutterFiller.style.height=Io(i.measure)+"px",i.gutterFiller.style.width=i.gutters.offsetWidth+"px"):i.gutterFiller.style.display="",!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(0===Io(i.measure)){var s=es&&!$o?"12px":"18px";i.scrollbarV.style.minWidth=i.scrollbarH.style.minHeight=s;var a=function(t){jn(t)!=i.scrollbarV&&jn(t)!=i.scrollbarH&&Qt(e,Ni)(t)};Qs(i.scrollbarV,"mousedown",a),Qs(i.scrollbarH,"mousedown",a)}e.state.checkedOverlayScrollbar=!0}}function g(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-It(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=yn(t,r),s=yn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a)return{from:a,to:yn(t,An(xn(t,a))+e.wrapper.clientHeight)};if(Math.min(l,t.lastLine())>=s)return{from:yn(t,An(xn(t,l))-e.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(s,o+1)}}function v(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=L(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function x(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=N(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(uo("div",[uo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s),r.lineNumWidth=r.lineNumInnerWidth+s,r.lineNumChars=r.lineNumInnerWidth?i.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",c(e),!0}return!1}function N(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function L(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function I(e,t,i){for(var r,n=e.display.viewFrom,o=e.display.viewTo,s=g(e.display,e.doc,t),a=!0;;a=!1){var l=e.display.scroller.clientWidth;if(!T(e,s,i))break;r=!0,e.display.maxLineChanged&&!e.options.lineWrapping&&y(e);var u=f(e);if(ht(e),A(e,u),m(e,u),Wo&&e.options.lineWrapping&&S(e,u),a&&e.options.lineWrapping&&l!=e.display.scroller.clientWidth)i=!0;else if(i=!1,t&&null!=t.top&&(t={top:Math.min(u.docHeight-ta-u.clientHeight,t.top)}),s=g(e.display,e.doc,t),s.from>=e.display.viewFrom&&s.to<=e.display.viewTo)break}return e.display.updateLineNumbers=null,r&&(qn(e,"update",e),(e.display.viewFrom!=n||e.display.viewTo!=o)&&qn(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)),r}function T(e,t,i){var r=e.display,n=e.doc;if(!r.wrapper.offsetWidth)return void ni(e);if(!(!i&&t.from>=r.viewFrom&&t.to<=r.viewTo&&0==li(e))){x(e)&&ni(e);var o=b(e),s=n.first+n.size,a=Math.max(t.from-e.options.viewportMargin,n.first),l=Math.min(s,t.to+e.options.viewportMargin);r.viewFrom<a&&a-r.viewFrom<20&&(a=Math.max(n.first,r.viewFrom)),r.viewTo>l&&r.viewTo-l<20&&(l=Math.min(s,r.viewTo)),ss&&(a=Fr(e.doc,a),l=jr(e.doc,l));var u=a!=r.viewFrom||l!=r.viewTo||r.lastSizeC!=r.wrapper.clientHeight;ai(e,a,l),r.viewOffset=An(xn(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var p=li(e);if(u||0!=p||i){var c=ho();return p>4&&(r.lineDiv.style.display="none"),O(e,r.updateLineNumbers,o),p>4&&(r.lineDiv.style.display=""),c&&ho()!=c&&c.offsetHeight&&c.focus(),po(r.cursorDiv),po(r.selectionDiv),u&&(r.lastSizeC=r.wrapper.clientHeight,vt(e,400)),C(e),!0}}}function y(e){var t=e.display,i=Rt(e,t.maxLine,t.maxLine.text.length).left;t.maxLineChanged=!1;var r=Math.max(0,i+3),n=Math.max(0,t.sizer.offsetLeft+r+ta-t.scroller.clientWidth);t.sizer.style.minWidth=r+"px",n<e.doc.scrollLeft&&bi(e,Math.min(t.scroller.scrollLeft,n),!0)}function A(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-ta)+"px"}function S(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth<e.display.scroller.clientWidth-1&&(e.display.sizer.style.minHeight=e.display.heightForcer.style.top="0px",e.display.gutters.style.height=t.docHeight+"px")}function C(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(Uo){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i,i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;if(2>n&&(n=zt(t)),(l>.001||-.001>l)&&(In(o.line,n),R(o.line),o.rest))for(var u=0;u<o.rest.length;u++)R(o.rest[u])}}}function R(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function b(e){for(var t=e.display,i={},r={},n=t.gutters.firstChild,o=0;n;n=n.nextSibling,++o)i[e.options.gutters[o]]=n.offsetLeft,r[e.options.gutters[o]]=n.offsetWidth;return{fixedPos:L(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function O(e,t,i){function r(t){var i=t.nextSibling;return Wo&&es&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;c.changes&&(to(c.changes,"gutter")>-1&&(d=!1),P(e,c,u,i)),d&&(po(c.lineNumber),c.lineNumber.appendChild(document.createTextNode(N(e.options,u)))),a=c.node.nextSibling}else{var E=U(e,c,u,i);s.insertBefore(E,a)}u+=c.size}for(;a;)a=r(a)}function P(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?w(e,t):"gutter"==o?k(e,t,i,r):"class"==o?G(t):"widget"==o&&B(t,r)}t.changes=null}function D(e){return e.node==e.text&&(e.node=uo("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),Uo&&(e.node.style.zIndex=2)),e.node}function _(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;if(t&&(t+=" CodeMirror-linebackground"),e.background)t?e.background.className=t:(e.background.parentNode.removeChild(e.background),e.background=null);else if(t){var i=D(e);e.background=i.insertBefore(uo("div",null,t),i.firstChild)}}function M(e,t){var i=e.display.externalMeasured;return i&&i.line==t.line?(e.display.externalMeasured=null,t.measure=i.measure,i.built):sn(e,t)}function w(e,t){var i=t.text.className,r=M(e,t);t.text==t.node&&(t.node=r.pre),t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,G(t)):i&&(t.text.className=i)}function G(e){_(e),e.line.wrapClass?D(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function k(e,t,i,r){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null);var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=D(t),s=t.gutter=o.insertBefore(uo("div",null,"CodeMirror-gutter-wrapper","position: absolute; left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px"),t.text);if(!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(uo("div",N(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(uo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function B(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}V(e,t)}function U(e,t,i,r){var n=M(e,t);return t.text=t.node=n.pre,n.bgClass&&(t.bgClass=n.bgClass),n.textClass&&(t.textClass=n.textClass),G(t),k(e,t,i,r),V(t,r),t.node}function V(e,t){if(H(e.line,e,t,!0),e.rest)for(var i=0;i<e.rest.length;i++)H(e.rest[i],e,t,!1)}function H(e,t,i,r){if(e.widgets)for(var n=D(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=uo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||(l.ignoreEvents=!0),F(a,l,t,i),r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l),qn(a,"redraw")}}function F(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px",e.coverGutter||(n-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=n+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}function j(e){return as(e.line,e.ch)}function W(e,t){return ls(e,t)<0?t:e
}function q(e,t){return ls(e,t)<0?e:t}function z(e,t){this.ranges=e,this.primIndex=t}function X(e,t){this.anchor=e,this.head=t}function Y(e,t){var i=e[t];e.sort(function(e,t){return ls(e.from(),t.from())}),t=to(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ls(o.to(),n.from())>=0){var s=q(o.from(),n.from()),a=W(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t,e.splice(--r,2,new X(l?a:s,l?s:a))}}return new z(e,t)}function K(e,t){return new z([new X(e,t||e)],0)}function $(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function Q(e,t){if(t.line<e.first)return as(e.first,0);var i=e.first+e.size-1;return t.line>i?as(i,xn(e,i).text.length):Z(t,xn(e,t.line).text.length)}function Z(e,t){var i=e.ch;return null==i||i>t?as(e.line,t):0>i?as(e.line,0):e}function J(e,t){return t>=e.first&&t<e.first+e.size}function et(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=Q(e,t[r]);return i}function tt(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ls(i,n)<0;o!=ls(r,n)<0?(n=i,i=r):o!=ls(i,r)<0&&(i=r)}return new X(n,i)}return new X(r||i,i)}function it(e,t,i,r){lt(e,new z([tt(e,e.sel.primary(),t,i)],0),r)}function rt(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=tt(e,e.sel.ranges[n],t[n],null);var o=Y(r,e.sel.primIndex);lt(e,o,i)}function nt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i,lt(e,Y(n,e.sel.primIndex),r)}function ot(e,t,i,r){lt(e,K(t,i),r)}function st(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new X(Q(e,t[i].anchor),Q(e,t[i].head))}};return Js(e,"beforeSelectionChange",e,i),e.cm&&Js(e.cm,"beforeSelectionChange",e.cm,i),i.ranges!=t.ranges?Y(i.ranges,i.ranges.length-1):t}function at(e,t,i){var r=e.history.done,n=eo(r);n&&n.ranges?(r[r.length-1]=t,ut(e,t,i)):lt(e,t,i)}function lt(e,t,i){ut(e,t,i),_n(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ut(e,t,i){(Kn(e,"beforeSelectionChange")||e.cm&&Kn(e.cm,"beforeSelectionChange"))&&(t=st(e,t));var r=i&&i.bias||(ls(t.primary().head,e.sel.primary().head)<0?-1:1);pt(e,dt(e,t,r,!0)),i&&i.scroll===!1||!e.cm||sr(e.cm)}function pt(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0,Yn(e.cm)),qn(e,"cursorActivity",e))}function ct(e){pt(e,dt(e,e.sel,null,!1),ra)}function dt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=Et(e,s.anchor,i,r),l=Et(e,s.head,i,r);(n||a!=s.anchor||l!=s.head)&&(n||(n=t.ranges.slice(0,o)),n[o]=new X(a,l))}return n?Y(n,t.primIndex):t}function Et(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=xn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r&&(Js(p,"beforeCursorEnter"),p.explicitlyCleared)){if(a.markedSpans){--l;continue}break}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ls(c,o)&&(c.ch+=s,c.ch<0?c=c.line>e.first?Q(e,as(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?as(c.line+1,0):null),!c)){if(n)return r?(e.cantEdit=!0,as(e.first,0)):Et(e,t,i,!0);n=!0,c=t,s=-s}o=c;continue e}}return o}}function ht(e){for(var t=e.display,i=e.doc,r=document.createDocumentFragment(),n=document.createDocumentFragment(),o=0;o<i.sel.ranges.length;o++){var s=i.sel.ranges[o],a=s.empty();(a||e.options.showCursorWhenSelecting)&&ft(e,s,r),a||mt(e,s,n)}if(e.options.moveInputWithCursor){var l=Ht(e,i.sel.primary().head,"div"),u=t.wrapper.getBoundingClientRect(),p=t.lineDiv.getBoundingClientRect(),c=Math.max(0,Math.min(t.wrapper.clientHeight-10,l.top+p.top-u.top)),d=Math.max(0,Math.min(t.wrapper.clientWidth-10,l.left+p.left-u.left));t.inputDiv.style.top=c+"px",t.inputDiv.style.left=d+"px"}co(t.cursorDiv,r),co(t.selectionDiv,n)}function ft(e,t,i){var r=Ht(e,t.head,"div"),n=i.appendChild(uo("div"," ","CodeMirror-cursor"));if(n.style.left=r.left+"px",n.style.top=r.top+"px",n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",r.other){var o=i.appendChild(uo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=r.other.left+"px",o.style.top=r.other.top+"px",o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function mt(e,t,i){function r(e,t,i,r){0>t&&(t=0),t=Math.round(t),r=Math.round(r),a.appendChild(uo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return Vt(e,as(t,i),"div",c,r)}var a,l,c=xn(s,t),d=c.text.length;return Ao(Sn(c),i||0,null==n?d:n,function(e,t,s){var c,E,h,f=o(e,"left");if(e==t)c=f,E=h=f.left;else{if(c=o(t-1,"right"),"rtl"==s){var m=f;f=c,c=m}E=f.left,h=c.right}null==i&&0==e&&(E=u),c.top-f.top>3&&(r(E,f.top,null,f.bottom),E=u,f.bottom<c.top&&r(E,f.bottom,null,c.top)),null==n&&t==d&&(h=p),(!a||f.top<a.top||f.top==a.top&&f.left<a.left)&&(a=f),(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c),u+1>E&&(E=u),r(E,c.top,h-E,c.bottom)}),{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=yt(e.display),u=l.left,p=o.lineSpace.offsetWidth-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var E=xn(s,c.line),h=xn(s,d.line),f=Vr(E)==Vr(h),m=n(c.line,c.ch,f?E.text.length+1:null).end,g=n(d.line,f?0:null,d.ch).start;f&&(m.top<g.top-2?(r(m.right,m.top,null,m.bottom),r(u,g.top,g.left,g.bottom)):r(m.right,m.top,g.left-m.right,m.bottom)),m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function gt(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0&&(t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate))}}function vt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,oo(xt,e))}function xt(e){var t=e.doc;if(t.frontier<t.first&&(t.frontier=t.first),!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Rs(t.mode,Lt(e,t.frontier));$t(e,function(){t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(n){if(t.frontier>=e.display.viewFrom){var o=n.styles,s=tn(e,n,r,!0);n.styles=s.styles,s.classes?n.styleClasses=s.classes:n.styleClasses&&(n.styleClasses=null);for(var a=!o||o.length!=n.styles.length,l=0;!a&&l<o.length;++l)a=o[l]!=n.styles[l];a&&ri(e,t.frontier,"text"),n.stateAfter=Rs(t.mode,r)}else nn(e,n.text,r),n.stateAfter=t.frontier%5==0?Rs(t.mode,r):null;return++t.frontier,+new Date>i?(vt(e,e.options.workDelay),!0):void 0})})}}function Nt(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=xn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=sa(l.text,null,e.options.tabSize);(null==n||r>u)&&(n=a-1,r=u)}return n}function Lt(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=Nt(e,t,i),s=o>r.first&&xn(r,o-1).stateAfter;return s=s?Rs(r.mode,s):bs(r.mode),r.iter(o,t,function(i){nn(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Rs(r.mode,s):null,++o}),i&&(r.frontier=o),s}function It(e){return e.lineSpace.offsetTop}function Tt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function yt(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=co(e.measure,uo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};return isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r),r}function At(e,t,i){var r=e.options.lineWrapping,n=r&&e.display.scroller.clientWidth;if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function St(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Tn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Ct(e,t){t=Vr(t);var i=Tn(t),r=e.display.externalMeasured=new ei(e.doc,t,i);r.lineN=i;var n=r.built=sn(e,r);return r.text=n.pre,co(e.display.lineMeasure,n.pre),r}function Rt(e,t,i,r){return Pt(e,Ot(e,t),i,r)}function bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[oi(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ot(e,t){var i=Tn(t),r=bt(e,i);r&&!r.text?r=null:r&&r.changes&&P(e,r,i,b(e)),r||(r=Ct(e,t));var n=St(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Pt(e,t,i,r){t.before&&(i=-1);var n,o=i+(r||"");return t.cache.hasOwnProperty(o)?n=t.cache[o]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(At(e,t.view,t.rect),t.hasHeights=!0),n=Dt(e,t,i,r),n.bogus||(t.cache[o]=n)),{left:n.left,right:n.right,top:n.top,bottom:n.bottom}}function Dt(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i?(o=0,s=1,a="left"):c>i?(o=i-p,s=o+1):(u==l.length-3||i==c&&l[u+3]>i)&&(s=c-p,o=s-1,i>=c&&(a="right")),null!=o){if(n=l[u+2],p==c&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;)n=l[(u-=3)+2],a="left";if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;)n=l[(u+=3)+2],a="right";break}}var d;if(3==n.nodeType){for(;o&&lo(t.line.text.charAt(p+o));)--o;for(;c>p+s&&lo(t.line.text.charAt(p+s));)++s;if(Vo&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(jo&&e.options.lineWrapping){var E=ua(n,o,s).getClientRects();d=E.length?E["right"==r?E.length-1:0]:ds}else d=ua(n,o,s).getBoundingClientRect()||ds}else{o>0&&(a=r="right");var E;d=e.options.lineWrapping&&(E=n.getClientRects()).length>1?E["right"==r?E.length-1:0]:n.getBoundingClientRect()}if(Vo&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+Xt(e.display),top:h.top,bottom:h.bottom}:ds}for(var f,m=(d.bottom+d.top)/2-t.rect.top,g=t.view.measure.heights,u=0;u<g.length-1&&!(m<g[u]);u++);f=u?g[u-1]:0,m=g[u];var v={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:f,bottom:m};return d.left||d.right||(v.bogus=!0),v}function _t(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Mt(e){e.display.externalMeasure=null,po(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)_t(e.display.view[t])}function wt(e){Mt(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function Gt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function kt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Bt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=Xr(t.widgets[n]);i.top+=o,i.bottom+=o}if("line"==r)return i;r||(r="local");var s=An(t);if("local"==r?s+=It(e.display):s-=e.display.viewOffset,"page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:kt());var l=a.left+("window"==r?0:Gt());i.left+=l,i.right+=l}return i.top+=s,i.bottom+=s,i}function Ut(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i)r-=Gt(),n-=kt();else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left,n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function Vt(e,t,i,r,n){return r||(r=xn(e.doc,t.line)),Bt(e,r,Rt(e,r,t.ch,n),i)}function Ht(e,t,i,r,n){function o(t,o){var s=Pt(e,n,t,o?"right":"left");return o?s.left=s.right:s.right=s.left,Bt(e,r,s,i)}function s(e,t){var i=a[t],r=i.level%2;return e==So(i)&&t&&i.level<a[t-1].level?(i=a[--t],e=Co(i)-(i.level%2?0:1),r=!0):e==Co(i)&&t<a.length-1&&i.level<a[t+1].level&&(i=a[++t],e=So(i)-i.level%2,r=!1),r&&e==i.to&&e>i.from?o(e-1):o(e,r)}r=r||xn(e.doc,t.line),n||(n=Ot(e,r));var a=Sn(r),l=t.ch;if(!a)return o(l);var u=_o(a,l),p=s(l,u);return null!=Ia&&(p.other=s(l,Ia)),p}function Ft(e,t){var i=0,t=Q(e.doc,t);e.options.lineWrapping||(i=Xt(e.display)*t.ch);var r=xn(e.doc,t.line),n=An(r)+It(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function jt(e,t,i,r){var n=as(e,t);return n.xRel=r,i&&(n.outside=!0),n}function Wt(e,t,i){var r=e.doc;if(i+=e.display.viewOffset,0>i)return jt(r.first,0,!0,-1);var n=yn(r,i),o=r.first+r.size-1;if(n>o)return jt(r.first+r.size-1,xn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=xn(r,n);;){var a=qt(e,s,n,t,i),l=Br(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Tn(s=u.to.line)}}function qt(e,t,i,r,n){function o(r){var n=Ht(e,as(i,r),"line",t,u);return a=!0,s>n.bottom?n.left-l:s<n.top?n.left+l:(a=!1,n.left)}var s=n-An(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ot(e,t),p=Sn(t),c=t.text.length,d=Ro(t),E=bo(t),h=o(d),f=a,m=o(E),g=a;if(r>m)return jt(i,E,g,1);for(;;){if(p?E==d||E==wo(t,d,1):1>=E-d){for(var v=h>r||m-r>=r-h?d:E,x=r-(v==d?h:m);lo(t.text.charAt(v));)++v;var N=jt(i,v,v==d?f:g,-1>x?-1:x>1?1:0);return N}var L=Math.ceil(c/2),I=d+L;if(p){I=d;for(var T=0;L>T;++T)I=wo(t,I,1)}var y=o(I);y>r?(E=I,m=y,(g=a)&&(m+=1e3),c=L):(d=I,h=y,f=a,c-=L)}}function zt(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==us){us=uo("pre");for(var t=0;49>t;++t)us.appendChild(document.createTextNode("x")),us.appendChild(uo("br"));us.appendChild(document.createTextNode("x"))}co(e.measure,us);var i=us.offsetHeight/50;return i>3&&(e.cachedTextHeight=i),po(e.measure),i||1}function Xt(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=uo("span","xxxxxxxxxx"),i=uo("pre",[t]);co(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;return n>2&&(e.cachedCharWidth=n),n||10}function Yt(e){e.curOp={viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Es},ea++||(Xs=[])}function Kt(e){var t=e.curOp,i=e.doc,r=e.display;if(e.curOp=null,t.updateMaxLine&&E(e),t.viewChanged||t.forceUpdate||null!=t.scrollTop||t.scrollToPos&&(t.scrollToPos.from.line<r.viewFrom||t.scrollToPos.to.line>=r.viewTo)||r.maxLineChanged&&e.options.lineWrapping){var n=I(e,{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate);e.display.scroller.offsetHeight&&(e.doc.scrollTop=e.display.scroller.scrollTop)}if(!n&&t.selectionChanged&&ht(e),n||t.startHeight==e.doc.height||m(e),null==r.wheelStartX||null==t.scrollTop&&null==t.scrollLeft&&!t.scrollToPos||(r.wheelStartX=r.wheelStartY=null),null!=t.scrollTop&&r.scroller.scrollTop!=t.scrollTop){var o=Math.max(0,Math.min(r.scroller.scrollHeight-r.scroller.clientHeight,t.scrollTop));r.scroller.scrollTop=r.scrollbarV.scrollTop=i.scrollTop=o}if(null!=t.scrollLeft&&r.scroller.scrollLeft!=t.scrollLeft){var s=Math.max(0,Math.min(r.scroller.scrollWidth-r.scroller.clientWidth,t.scrollLeft));r.scroller.scrollLeft=r.scrollbarH.scrollLeft=i.scrollLeft=s,v(e)}if(t.scrollToPos){var a=ir(e,Q(e.doc,t.scrollToPos.from),Q(e.doc,t.scrollToPos.to),t.scrollToPos.margin);t.scrollToPos.isCursor&&e.state.focused&&tr(e,a)}t.selectionChanged&>(e),e.state.focused&&t.updateInput&&di(e,t.typing);var l=t.maybeHiddenMarkers,u=t.maybeUnhiddenMarkers;if(l)for(var p=0;p<l.length;++p)l[p].lines.length||Js(l[p],"hide");if(u)for(var p=0;p<u.length;++p)u[p].lines.length&&Js(u[p],"unhide");var c;if(--ea||(c=Xs,Xs=null),t.changeObjs&&Js(e,"changes",e,t.changeObjs),c)for(var p=0;p<c.length;++p)c[p]();if(t.cursorActivityHandlers)for(var p=0;p<t.cursorActivityHandlers.length;p++)t.cursorActivityHandlers[p](e)}function $t(e,t){if(e.curOp)return t();Yt(e);try{return t()}finally{Kt(e)}}function Qt(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Yt(e);try{return t.apply(e,arguments)}finally{Kt(e)}}}function Zt(e){return function(){if(this.curOp)return e.apply(this,arguments);Yt(this);try{return e.apply(this,arguments)}finally{Kt(this)}}}function Jt(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Yt(t);try{return e.apply(this,arguments)}finally{Kt(t)}}}function ei(e,t,i){this.line=t,this.rest=Hr(t),this.size=this.rest?Tn(eo(this.rest))-i+1:1,this.node=this.text=null,this.hidden=Wr(e,t)}function ti(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new ei(e.doc,xn(e.doc,o),o);r=o+s.size,n.push(s)}return n}function ii(e,t,i,r){null==t&&(t=e.doc.first),null==i&&(i=e.doc.first+e.doc.size),r||(r=0);var n=e.display;if(r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=n.viewTo)ss&&Fr(e.doc,t)<n.viewTo&&ni(e);else if(i<=n.viewFrom)ss&&jr(e.doc,i+r)>n.viewFrom?ni(e):(n.viewFrom+=r,n.viewTo+=r);else if(t<=n.viewFrom&&i>=n.viewTo)ni(e);else if(t<=n.viewFrom){var o=si(e,i,i+r,1);o?(n.view=n.view.slice(o.index),n.viewFrom=o.lineN,n.viewTo+=r):ni(e)}else if(i>=n.viewTo){var o=si(e,t,t,-1);o?(n.view=n.view.slice(0,o.index),n.viewTo=o.lineN):ni(e)}else{var s=si(e,t,t,-1),a=si(e,i,i+r,1);s&&a?(n.view=n.view.slice(0,s.index).concat(ti(e,s.lineN,a.lineN)).concat(n.view.slice(a.index)),n.viewTo+=r):ni(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function ri(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;if(n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null),!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[oi(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==to(s,i)&&s.push(i)}}}function ni(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function oi(e,t){if(t>=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++)if(t-=i[r].size,0>t)return r}function si(e,t,i,r){var n,o=oi(e,t),s=e.display.view;if(!ss||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t,o++}else n=l-t;t+=n,i+=n}for(;Fr(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size,o+=r}return{index:o,lineN:i}}function ai(e,t,i){var r=e.display,n=r.view;0==n.length||t>=r.viewTo||i<=r.viewFrom?(r.view=ti(e,t,i),r.viewFrom=t):(r.viewFrom>t?r.view=ti(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(oi(e,t))),r.viewFrom=t,r.viewTo<i?r.view=r.view.concat(ti(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,oi(e,i)))),r.viewTo=i}function li(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function ui(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){ci(e),e.state.focused&&ui(e)})}function pi(e){function t(){var r=ci(e);r||i?(e.display.pollingFast=!1,ui(e)):(i=!0,e.display.poll.set(60,t))}var i=!1;e.display.pollingFast=!0,e.display.poll.set(20,t)}function ci(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||xa(t)&&!i||fi(e)||e.options.disableInput)return!1;e.state.pasteIncoming&&e.state.fakedLastChar&&(t.value=t.value.substring(0,t.value.length-1),e.state.fakedLastChar=!1);var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(jo&&!Vo&&e.display.inputHasSelection===n)return di(e),!1;var o=!e.curOp;o&&Yt(e),e.display.shift=!1,8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;for(var l=n.slice(s),u=va(l),p=e.state.pasteIncoming&&u.length>1&&r.sel.ranges.length==u.length,c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],E=d.from(),h=d.to();s<i.length?E=as(E.line,E.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=as(h.line,Math.min(xn(r,h.line).text.length,h.ch+eo(u).length)));var f=e.curOp.updateInput,m={from:E,to:h,text:p?[u[c]]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};if(Yi(e.doc,m),qn(e,"inputRead",e,m),l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head);if(g.electricChars){for(var v=0;v<g.electricChars.length;v++)if(l.indexOf(g.electricChars.charAt(v))>-1){lr(e,d.head.line,"smart");break}}else if(g.electricInput){var x=xs(m);g.electricInput.test(xn(r,x.line).text.slice(0,x.ch))&&lr(e,d.head.line,"smart")}}}return sr(e),e.curOp.updateInput=f,e.curOp.typing=!0,n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n,o&&Kt(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function di(e,t){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Na&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s,e.state.focused&&la(e.display.input),jo&&!Vo&&(e.display.inputHasSelection=s)}else t||(e.display.prevInput=e.display.input.value="",jo&&!Vo&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=i}function Ei(e){"nocursor"==e.options.readOnly||Jo&&ho()==e.display.input||e.display.input.focus()}function hi(e){e.state.focused||(Ei(e),Ui(e))}function fi(e){return e.options.readOnly||e.doc.cantEdit}function mi(e){function t(){e.state.focused&&setTimeout(oo(Ei,e),0)}function i(t){Xn(e,t)||$s(t)}function r(t){if(e.somethingSelected())n.inaccurateSelection&&(n.prevInput="",n.inaccurateSelection=!1,n.input.value=e.getSelection(),la(n.input));else{for(var i="",r=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:as(s,0),head:as(s+1,0)};r.push(a),i+=e.getRange(a.anchor,a.head)}"cut"==t.type?e.setSelections(r,null,ra):(n.prevInput="",n.input.value=i,la(n.input))}"cut"==t.type&&(e.state.cutIncoming=!0)}var n=e.display;Qs(n.scroller,"mousedown",Qt(e,Ni)),Bo?Qs(n.scroller,"dblclick",Qt(e,function(t){if(!Xn(e,t)){var i=xi(e,t);if(i&&!Ai(e,t)&&!vi(e.display,t)){Ys(t);var r=Er(e,i);it(e.doc,r.anchor,r.head)}}})):Qs(n.scroller,"dblclick",function(t){Xn(e,t)||Ys(t)}),Qs(n.lineSpace,"selectstart",function(e){vi(n,e)||Ys(e)}),ns||Qs(n.scroller,"contextmenu",function(t){Hi(e,t)}),Qs(n.scroller,"scroll",function(){n.scroller.clientHeight&&(Ri(e,n.scroller.scrollTop),bi(e,n.scroller.scrollLeft,!0),Js(e,"scroll",e))}),Qs(n.scrollbarV,"scroll",function(){n.scroller.clientHeight&&Ri(e,n.scrollbarV.scrollTop)}),Qs(n.scrollbarH,"scroll",function(){n.scroller.clientHeight&&bi(e,n.scrollbarH.scrollLeft)}),Qs(n.scroller,"mousewheel",function(t){Oi(e,t)}),Qs(n.scroller,"DOMMouseScroll",function(t){Oi(e,t)}),Qs(n.scrollbarH,"mousedown",t),Qs(n.scrollbarV,"mousedown",t),Qs(n.wrapper,"scroll",function(){n.wrapper.scrollTop=n.wrapper.scrollLeft=0}),Qs(n.input,"keyup",Qt(e,ki)),Qs(n.input,"input",function(){jo&&!Vo&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),pi(e)}),Qs(n.input,"keydown",Qt(e,wi)),Qs(n.input,"keypress",Qt(e,Bi)),Qs(n.input,"focus",oo(Ui,e)),Qs(n.input,"blur",oo(Vi,e)),e.options.dragDrop&&(Qs(n.scroller,"dragstart",function(t){Ci(e,t)}),Qs(n.scroller,"dragenter",i),Qs(n.scroller,"dragover",i),Qs(n.scroller,"drop",Qt(e,Si))),Qs(n.scroller,"paste",function(t){vi(n,t)||(e.state.pasteIncoming=!0,Ei(e),pi(e))}),Qs(n.input,"paste",function(){if(Wo&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=n.input.selectionStart,i=n.input.selectionEnd;n.input.value+="$",n.input.selectionStart=t,n.input.selectionEnd=i,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,pi(e)}),Qs(n.input,"cut",r),Qs(n.input,"copy",r),Ko&&Qs(n.sizer,"mouseup",function(){ho()==n.input&&n.input.blur(),Ei(e)})}function gi(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function vi(e,t){for(var i=jn(t);i!=e.wrapper;i=i.parentNode)if(!i||i.ignoreEvents||i.parentNode==e.sizer&&i!=e.mover)return!0}function xi(e,t,i,r){var n=e.display;if(!i){var o=jn(t);if(o==n.scrollbarH||o==n.scrollbarV||o==n.scrollbarFiller||o==n.gutterFiller)return null}var s,a,l=n.lineSpace.getBoundingClientRect();try{s=t.clientX-l.left,a=t.clientY-l.top}catch(t){return null}var u,p=Wt(e,s,a);if(r&&1==p.xRel&&(u=xn(e.doc,p.line).text).length==p.ch){var c=sa(u,u.length,e.options.tabSize)-u.length;p=as(p.line,Math.max(0,Math.round((s-yt(e.display).left)/Xt(e.display))-c))}return p}function Ni(e){if(!Xn(this,e)){var t=this,i=t.display;if(i.shift=e.shiftKey,vi(i,e))return void(Wo||(i.scroller.draggable=!1,setTimeout(function(){i.scroller.draggable=!0},100)));if(!Ai(t,e)){var r=xi(t,e);switch(window.focus(),Wn(e)){case 1:r?Li(t,e,r):jn(e)==i.scroller&&Ys(e);break;case 2:Wo&&(t.state.lastMiddleDown=+new Date),r&&it(t.doc,r),setTimeout(oo(Ei,t),20),Ys(e);break;case 3:ns&&Hi(t,e)}}}}function Li(e,t,i){setTimeout(oo(hi,e),0);var r,n=+new Date;cs&&cs.time>n-400&&0==ls(cs.pos,i)?r="triple":ps&&ps.time>n-400&&0==ls(ps.pos,i)?(r="double",cs={time:n,pos:i}):(r="single",ps={time:n,pos:i});var o=e.doc.sel,s=es?t.metaKey:t.ctrlKey;e.options.dragDrop&&ga&&!fi(e)&&"single"==r&&o.contains(i)>-1&&o.somethingSelected()?Ii(e,t,i,s):Ti(e,t,i,r,s)}function Ii(e,t,i,r){var n=e.display,o=Qt(e,function(s){Wo&&(n.scroller.draggable=!1),e.state.draggingText=!1,Zs(document,"mouseup",o),Zs(n.scroller,"drop",o),Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10&&(Ys(s),r||it(e.doc,i),Ei(e),Bo&&!Vo&&setTimeout(function(){document.body.focus(),Ei(e)},20))});Wo&&(n.scroller.draggable=!0),e.state.draggingText=o,n.scroller.dragDrop&&n.scroller.dragDrop(),Qs(document,"mouseup",o),Qs(n.scroller,"drop",o)}function Ti(e,t,i,r,n){function o(t){if(0!=ls(f,t))if(f=t,"rect"==r){for(var n=[],o=e.options.tabSize,s=sa(xn(u,i.line).text,i.ch,o),a=sa(xn(u,t.line).text,t.ch,o),l=Math.min(s,a),E=Math.max(s,a),h=Math.min(i.line,t.line),m=Math.min(e.lastLine(),Math.max(i.line,t.line));m>=h;h++){var g=xn(u,h).text,v=Zn(g,l,o);l==E?n.push(new X(as(h,v),as(h,v))):g.length>v&&n.push(new X(as(h,v),as(h,Zn(g,E,o))))}n.length||n.push(new X(i,i)),lt(u,Y(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var x=p,N=x.anchor,L=t;if("single"!=r){if("double"==r)var I=Er(e,t);else var I=new X(as(t.line,0),Q(u,as(t.line+1,0)));ls(I.anchor,N)>0?(L=I.head,N=q(x.from(),I.anchor)):(L=I.anchor,N=W(x.to(),I.head))}var n=d.ranges.slice(0);n[c]=new X(Q(u,N),L),lt(u,Y(n,c),na)}}function s(t){var i=++v,n=xi(e,t,!0,"rect"==r);if(n)if(0!=ls(n,f)){hi(e),o(n);var a=g(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(Qt(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<m.top?-20:t.clientY>m.bottom?20:0;p&&setTimeout(Qt(e,function(){v==i&&(l.scroller.scrollTop+=p,s(t))}),50)}}function a(t){v=1/0,Ys(t),Ei(e),Zs(document,"mousemove",x),Zs(document,"mouseup",N),u.history.lastSelOrigin=null}var l=e.display,u=e.doc;Ys(t);var p,c,d=u.sel;if(n&&!t.shiftKey?(c=u.sel.contains(i),p=c>-1?u.sel.ranges[c]:new X(i,i)):p=u.sel.primary(),t.altKey)r="rect",n||(p=new X(i,i)),i=xi(e,t,!0,!0),c=-1;else if("double"==r){var E=Er(e,i);p=e.display.shift||u.extend?tt(u,p,E.anchor,E.head):E}else if("triple"==r){var h=new X(as(i.line,0),Q(u,as(i.line+1,0)));p=e.display.shift||u.extend?tt(u,p,h.anchor,h.head):h}else p=tt(u,p,i);n?c>-1?nt(u,c,p,na):(c=u.sel.ranges.length,lt(u,Y(u.sel.ranges.concat([p]),c),{scroll:!1,origin:"*mouse"})):(c=0,lt(u,new z([p],0),na),d=u.sel);var f=i,m=l.wrapper.getBoundingClientRect(),v=0,x=Qt(e,function(e){(jo&&!Ho?e.buttons:Wn(e))?s(e):a(e)}),N=Qt(e,a);Qs(document,"mousemove",x),Qs(document,"mouseup",N)}function yi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&Ys(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Kn(e,i))return Fn(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=yn(e.doc,s),d=e.options.gutters[u];return n(e,i,e,c,d,t),Fn(t)}}}function Ai(e,t){return yi(e,t,"gutterClick",!0,qn)}function Si(e){var t=this;if(!Xn(t,e)&&!vi(t.display,e)){Ys(e),jo&&(hs=+new Date);var i=xi(t,e,!0),r=e.dataTransfer.files;if(i&&!fi(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=Qt(t,function(){if(o[r]=a.result,++s==n){i=Q(t.doc,i);var e={from:i,to:i,text:va(o.join("\n")),origin:"paste"};Yi(t.doc,e),at(t.doc,K(i,xs(e)))}}),a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1)return t.state.draggingText(e),void setTimeout(oo(Ei,t),20);try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(es?e.metaKey:e.ctrlKey))var u=t.listSelections();if(ut(t.doc,K(i,i)),u)for(var l=0;l<u.length;++l)er(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste"),Ei(t)}}catch(e){}}}}function Ci(e,t){if(jo&&(!e.state.draggingText||+new Date-hs<100))return void $s(t);if(!Xn(e,t)&&!vi(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.setDragImage&&!Yo)){var i=uo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",Xo&&(i.width=i.height=1,e.display.wrapper.appendChild(i),i._top=i.offsetTop),t.dataTransfer.setDragImage(i,0,0),Xo&&i.parentNode.removeChild(i)}}function Ri(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,ko||I(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbarV.scrollTop!=t&&(e.display.scrollbarV.scrollTop=t),ko&&I(e),vt(e,100))}function bi(e,t,i){(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)||(t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),e.doc.scrollLeft=t,v(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbarH.scrollLeft!=t&&(e.display.scrollbarH.scrollLeft=t))}function Oi(e,t){var i=t.wheelDeltaX,r=t.wheelDeltaY;null==i&&t.detail&&t.axis==t.HORIZONTAL_AXIS&&(i=t.detail),null==r&&t.detail&&t.axis==t.VERTICAL_AXIS?r=t.detail:null==r&&(r=t.wheelDelta);var n=e.display,o=n.scroller;if(i&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&es&&Wo)e:for(var s=t.target,a=n.view;s!=o;s=s.parentNode)for(var l=0;l<a.length;l++)if(a[l].node==s){e.display.currentWheelTarget=s;break e}if(i&&!ko&&!Xo&&null!=ms)return r&&Ri(e,Math.max(0,Math.min(o.scrollTop+r*ms,o.scrollHeight-o.clientHeight))),bi(e,Math.max(0,Math.min(o.scrollLeft+i*ms,o.scrollWidth-o.clientWidth))),Ys(t),void(n.wheelStartX=null);if(r&&null!=ms){var u=r*ms,p=e.doc.scrollTop,c=p+n.wrapper.clientHeight;0>u?p=Math.max(0,p+u-50):c=Math.min(e.doc.height,c+u+50),I(e,{top:p,bottom:c})}20>fs&&(null==n.wheelStartX?(n.wheelStartX=o.scrollLeft,n.wheelStartY=o.scrollTop,n.wheelDX=i,n.wheelDY=r,setTimeout(function(){if(null!=n.wheelStartX){var e=o.scrollLeft-n.wheelStartX,t=o.scrollTop-n.wheelStartY,i=t&&n.wheelDY&&t/n.wheelDY||e&&n.wheelDX&&e/n.wheelDX;n.wheelStartX=n.wheelStartY=null,i&&(ms=(ms*fs+i)/(fs+1),++fs)}},200)):(n.wheelDX+=i,n.wheelDY+=r))}}function Pi(e,t,i){if("string"==typeof t&&(t=Os[t],!t))return!1;e.display.pollingFast&&ci(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{fi(e)&&(e.state.suppressEdits=!0),i&&(e.display.shift=!1),n=t(e)!=ia}finally{e.display.shift=r,e.state.suppressEdits=!1}return n}function Di(e){var t=e.state.keyMaps.slice(0);return e.options.extraKeys&&t.push(e.options.extraKeys),t.push(e.options.keyMap),t}function _i(e,t){var i=fr(e.options.keyMap),r=i.auto;clearTimeout(gs),r&&!_s(t)&&(gs=setTimeout(function(){fr(e.options.keyMap)==i&&(e.options.keyMap=r.call?r.call(null,e):r,a(e))},50));var n=Ms(t,!0),o=!1;if(!n)return!1;var s=Di(e);return o=t.shiftKey?Ds("Shift-"+n,s,function(t){return Pi(e,t,!0)
})||Ds(n,s,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Pi(e,t):void 0}):Ds(n,s,function(t){return Pi(e,t)}),o&&(Ys(t),gt(e),qn(e,"keyHandled",e,n,t)),o}function Mi(e,t,i){var r=Ds("'"+i+"'",Di(e),function(t){return Pi(e,t,!0)});return r&&(Ys(t),gt(e),qn(e,"keyHandled",e,"'"+i+"'",t)),r}function wi(e){var t=this;if(hi(t),!Xn(t,e)){Bo&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=_i(t,e);Xo&&(vs=r?i:null,!r&&88==i&&!Na&&(es?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||Gi(t)}}function Gi(e){function t(e){18!=e.keyCode&&e.altKey||(mo(i,"CodeMirror-crosshair"),Zs(document,"keyup",t),Zs(document,"mouseover",t))}var i=e.display.lineDiv;go(i,"CodeMirror-crosshair"),Qs(document,"keyup",t),Qs(document,"mouseover",t)}function ki(e){Xn(this,e)||16==e.keyCode&&(this.doc.sel.shift=!1)}function Bi(e){var t=this;if(!Xn(t,e)){var i=e.keyCode,r=e.charCode;if(Xo&&i==vs)return vs=null,void Ys(e);if(!(Xo&&(!e.which||e.which<10)||Ko)||!_i(t,e)){var n=String.fromCharCode(null==r?i:r);Mi(t,e,n)||(jo&&!Vo&&(t.display.inputHasSelection=null),pi(t))}}}function Ui(e){"nocursor"!=e.options.readOnly&&(e.state.focused||(Js(e,"focus",e),e.state.focused=!0,go(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(di(e),Wo&&setTimeout(oo(di,e,!0),0))),ui(e),gt(e))}function Vi(e){e.state.focused&&(Js(e,"blur",e),e.state.focused=!1,mo(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function Hi(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value=""+(t?n.input.value:"");n.prevInput=t?"":"",n.input.selectionStart=1,n.input.selectionEnd=i.length,n.selForContextMenu=e.doc.sel}}function r(){if(n.inputDiv.style.position="relative",n.input.style.cssText=l,Vo&&(n.scrollbarV.scrollTop=n.scroller.scrollTop=s),ui(e),null!=n.input.selectionStart){(!jo||Vo)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?Qt(e,Os.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):di(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!Xn(e,t,"contextmenu")){var n=e.display;if(!vi(n,t)&&!Fi(e,t)){var o=xi(e,t),s=n.scroller.scrollTop;if(o&&!Xo){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&Qt(e,lt)(e.doc,K(o),ra);var l=n.input.style.cssText;if(n.inputDiv.style.position="absolute",n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(jo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",Ei(e),di(e),e.somethingSelected()||(n.input.value=n.prevInput=" "),n.selForContextMenu=e.doc.sel,clearTimeout(n.detectingSelectAll),jo&&!Vo&&i(),ns){$s(t);var u=function(){Zs(window,"mouseup",u),setTimeout(r,20)};Qs(window,"mouseup",u)}else setTimeout(r,50)}}}}function Fi(e,t){return Kn(e,"gutterContextMenu")?yi(e,t,"gutterContextMenu",!1,Js):!1}function ji(e,t){if(ls(e,t.from)<0)return e;if(ls(e,t.to)<=0)return xs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=xs(t).ch-t.to.ch),as(i,r)}function Wi(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new X(ji(n.anchor,t),ji(n.head,t)))}return Y(i,e.sel.primIndex)}function qi(e,t,i){return e.line==t.line?as(i.line,e.ch-t.ch+i.ch):as(i.line+(e.line-t.line),e.ch)}function zi(e,t,i){for(var r=[],n=as(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=qi(a.from,n,o),u=qi(xs(a),n,o);if(n=a.to,o=u,"around"==i){var p=e.sel.ranges[s],c=ls(p.head,p.anchor)<0;r[s]=new X(c?u:l,c?l:u)}else r[s]=new X(l,l)}return new z(r,e.sel.primIndex)}function Xi(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};return i&&(r.update=function(t,i,r,n){t&&(this.from=Q(e,t)),i&&(this.to=Q(e,i)),r&&(this.text=r),void 0!==n&&(this.origin=n)}),Js(e,"beforeChange",e,r),e.cm&&Js(e.cm,"beforeChange",e.cm,r),r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function Yi(e,t,i){if(e.cm){if(!e.cm.curOp)return Qt(e.cm,Yi)(e,t,i);if(e.cm.state.suppressEdits)return}if(!(Kn(e,"beforeChange")||e.cm&&Kn(e.cm,"beforeChange"))||(t=Xi(e,t,!0))){var r=os&&!i&&Or(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)Ki(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else Ki(e,t)}}function Ki(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ls(t.from,t.to)){var i=Wi(e,t);Pn(e,t,i,e.cm?e.cm.curOp.id:0/0),Zi(e,t,i,Cr(e,t));var r=[];gn(e,function(e,i){i||-1!=to(r,e.history)||(Hn(e.history,t),r.push(e.history)),Zi(e,t,null,Cr(e,t))})}}function $i(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length&&(r=s[l],i?!r.ranges||r.equals(e.sel):r.ranges);l++);if(l!=s.length){for(n.lastOrigin=n.lastSelOrigin=null;r=s.pop(),r.ranges;){if(Mn(r,a),i&&!r.equals(e.sel))return void lt(e,r,{clearRedo:!1});o=r}var u=[];Mn(o,a),a.push({changes:u,generation:n.generation}),n.generation=r.generation||++n.maxGeneration;for(var p=Kn(e,"beforeChange")||e.cm&&Kn(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];if(c.origin=t,p&&!Xi(e,c,!1))return void(s.length=0);u.push(Rn(e,c));var d=l?Wi(e,c,null):eo(s);Zi(e,c,d,br(e,c)),!l&&e.cm&&e.cm.scrollIntoView(c);var E=[];gn(e,function(e,t){t||-1!=to(E,e.history)||(Hn(e.history,c),E.push(e.history)),Zi(e,c,null,br(e,c))})}}}}function Qi(e,t){if(0!=t&&(e.first+=t,e.sel=new z(io(e.sel.ranges,function(e){return new X(as(e.anchor.line+t,e.anchor.ch),as(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){ii(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)ri(e.cm,r,"gutter")}}function Zi(e,t,i,r){if(e.cm&&!e.cm.curOp)return Qt(e.cm,Zi)(e,t,i,r);if(t.to.line<e.first)return void Qi(e,t.text.length-1-(t.to.line-t.from.line));if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Qi(e,n),t={from:as(e.first,0),to:as(t.to.line+n,t.to.ch),text:[eo(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:as(o,xn(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Nn(e,t.from,t.to),i||(i=Wi(e,t,null)),e.cm?Ji(e.cm,t,r):hn(e,t,r),ut(e,i,ra)}}function Ji(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;e.options.lineWrapping||(u=Tn(Vr(xn(r,s.line))),r.iter(u,a.line+1,function(e){return e==n.maxLine?(l=!0,!0):void 0})),r.sel.contains(t.from,t.to)>-1&&Yn(e),hn(r,t,i,o(e)),e.options.lineWrapping||(r.iter(u,s.line+t.text.length,function(e){var t=d(e);t>n.maxLineLength&&(n.maxLine=e,n.maxLineLength=t,n.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,s.line),vt(e,400);var p=t.text.length-(a.line-s.line)-1;s.line!=a.line||1!=t.text.length||En(e.doc,t)?ii(e,s.line,a.line+1,p):ri(e,s.line,"text");var c=Kn(e,"changes"),E=Kn(e,"change");if(E||c){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};E&&qn(e,"change",e,h),c&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function er(e,t,i,r,n){if(r||(r=i),ls(r,i)<0){var o=r;r=i,i=o}"string"==typeof t&&(t=va(t)),Yi(e,{from:i,to:r,text:t,origin:n})}function tr(e,t){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;if(t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1),null!=n&&!Qo){var o=uo("div","",null,"position: absolute; top: "+(t.top-i.viewOffset-It(e.display))+"px; height: "+(t.bottom-t.top+ta)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(n),e.display.lineSpace.removeChild(o)}}function ir(e,t,i,r){for(null==r&&(r=0);;){var n=!1,o=Ht(e,t),s=i&&i!=t?Ht(e,i):o,a=nr(e,Math.min(o.left,s.left),Math.min(o.top,s.top)-r,Math.max(o.left,s.left),Math.max(o.bottom,s.bottom)+r),l=e.doc.scrollTop,u=e.doc.scrollLeft;if(null!=a.scrollTop&&(Ri(e,a.scrollTop),Math.abs(e.doc.scrollTop-l)>1&&(n=!0)),null!=a.scrollLeft&&(bi(e,a.scrollLeft),Math.abs(e.doc.scrollLeft-u)>1&&(n=!0)),!n)return o}}function rr(e,t,i,r,n){var o=nr(e,t,i,r,n);null!=o.scrollTop&&Ri(e,o.scrollTop),null!=o.scrollLeft&&bi(e,o.scrollLeft)}function nr(e,t,i,r,n){var o=e.display,s=zt(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-ta,u={},p=e.doc.height+Tt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var E=Math.min(i,(d?p:n)-l);E!=a&&(u.scrollTop=E)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,f=o.scroller.clientWidth-ta;t+=o.gutters.offsetWidth,r+=o.gutters.offsetWidth;var m=o.gutters.offsetWidth,g=m+10>t;return h+m>t||g?(g&&(t=0),u.scrollLeft=Math.max(0,t-10-m)):r>f+h-3&&(u.scrollLeft=r+10-f),u}function or(e,t,i){(null!=t||null!=i)&&ar(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function sr(e){ar(e);var t=e.getCursor(),i=t,r=t;e.options.lineWrapping||(i=t.ch?as(t.line,t.ch-1):t,r=as(t.line,t.ch+1)),e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Ft(e,t.from),r=Ft(e,t.to),n=nr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function lr(e,t,i,r){var n,o=e.doc;null==i&&(i="add"),"smart"==i&&(e.doc.mode.indent?n=Lt(e,t):i="prev");var s=e.options.tabSize,a=xn(o,t),l=sa(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i&&(u=e.doc.mode.indent(n,a.text.slice(p.length),a.text),u==ia)){if(!r)return;i="prev"}}else u=0,i="not";"prev"==i?u=t>o.first?sa(xn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i),u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var E=Math.floor(u/s);E;--E)d+=s,c+=" ";if(u>d&&(c+=Jn(u-d)),c!=p)er(e.doc,c,as(t,0),as(t,p.length),"+input");else for(var E=0;E<o.sel.ranges.length;E++){var h=o.sel.ranges[E];if(h.head.line==t&&h.head.ch<p.length){var d=as(t,p.length);nt(o,E,new X(d,d));break}}a.stateAfter=null}function ur(e,t,i,r){var n=t,o=t,s=e.doc;return"number"==typeof t?o=xn(s,$(s,t)):n=Tn(t),null==n?null:(r(o,n)&&ri(e,n,i),o)}function pr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ls(o.from,eo(r).to)<=0;){var s=r.pop();if(ls(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}$t(e,function(){for(var t=r.length-1;t>=0;t--)er(e.doc,"",r[t].from,r[t].to,"+delete");sr(e)})}function cr(e,t,i,r,n){function o(){var t=a+i;return t<e.first||t>=e.first+e.size?c=!1:(a=t,p=xn(e,t))}function s(e){var t=(n?wo:Go)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?bo:Ro)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=xn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,E="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),f=!0;!(0>i)||s(!f);f=!1){var m=p.text.charAt(l)||"\n",g=so(m,h)?"w":E&&"\n"==m?"n":!E||/\s/.test(m)?null:"p";if(!E||f||g||(g="s"),d&&d!=g){0>i&&(i=1,s());break}if(g&&(d=g),i>0&&!s(!f))break}var v=Et(e,as(a,l),u,!0);return c||(v.hitSide=!0),v}function dr(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*zt(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=Wt(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Er(e,t){var i=e.doc,r=xn(i,t.line).text,n=t.ch,o=t.ch;if(r){var s=e.getHelper(t,"wordChars");(t.xRel<0||o==r.length)&&n?--n:++o;for(var a=r.charAt(n),l=so(a,s)?function(e){return so(e,s)}:/\s/.test(a)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!so(e)};n>0&&l(r.charAt(n-1));)--n;for(;o<r.length&&l(r.charAt(o));)++o}return new X(as(t.line,n),as(t.line,o))}function hr(t,i,r,n){e.defaults[t]=i,r&&(Ls[t]=n?function(e,t,i){i!=Is&&r(e,t,i)}:r)}function fr(e){return"string"==typeof e?Ps[e]:e}function mr(e,t,i,r,n){if(r&&r.shared)return gr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return Qt(e.cm,mr)(e,t,i,r,n);var o=new Gs(e,n),s=ls(t,i);if(r&&no(r,o,!1),s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=uo("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Ur(e,t.line,t,i,o)||t.line!=i.line&&Ur(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");ss=!0}o.addToHistory&&Pn(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;if(e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&Vr(e)==u.display.maxLine&&(a=!0),o.collapsed&&l!=t.line&&In(e,0),yr(e,new Lr(o,l==t.line?t.ch:null,l==i.line?i.ch:null)),++l}),o.collapsed&&e.iter(t.line,i.line+1,function(t){Wr(e,t)&&In(t,0)}),o.clearOnEnter&&Qs(o,"beforeCursorEnter",function(){o.clear()}),o.readOnly&&(os=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++ks,o.atomic=!0),u){if(a&&(u.curOp.updateMaxLine=!0),o.collapsed)ii(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var p=t.line;p<=i.line;p++)ri(u,p,"text");o.atomic&&ct(u.doc),qn(u,"markerAdded",u,o)}return o}function gr(e,t,i,r,n){r=no(r),r.shared=!1;var o=[mr(e,t,i,r,n)],s=o[0],a=r.widgetNode;return gn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0)),o.push(mr(e,Q(e,t),Q(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=eo(o)}),new Bs(o,s)}function vr(e){return e.findMarks(as(e.first,0),e.clipPos(as(e.lastLine())),function(e){return e.parent})}function xr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ls(o,s)){var a=mr(e,o,s,r.primary,r.primary.type);r.markers.push(a),a.parent=r}}}function Nr(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];gn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];-1==to(r,o.doc)&&(o.parent=null,i.markers.splice(n--,1))}}}function Lr(e,t,i){this.marker=e,this.from=t,this.to=i}function Ir(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Tr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function yr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}function Ar(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Lr(s,o.from,l?null:o.to))}}return r}function Sr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Lr(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function Cr(e,t){var i=J(e,t.from.line)&&xn(e,t.from.line).markedSpans,r=J(e,t.to.line)&&xn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ls(t.from,t.to),a=Ar(i,n,s),l=Sr(r,o,s),u=1==t.text.length,p=eo(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var E=Ir(l,d.marker);E?u&&(d.to=null==E.to?null:E.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];if(null!=d.to&&(d.to+=p),null==d.from){var E=Ir(a,d.marker);E||(d.from=p,u&&(a||(a=[])).push(d))}else d.from+=p,u&&(a||(a=[])).push(d)}a&&(a=Rr(a)),l&&l!=a&&(l=Rr(l));var h=[a];if(!u){var f,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(f||(f=[])).push(new Lr(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(f);h.push(l)}return h}function Rr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function br(e,t){var i=kn(e,t),r=Cr(e,t);if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Or(e,t,i){var r=null;if(e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=to(r,i)||(r||(r=[])).push(i)}}),!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ls(u.to,a.from)<0||ls(u.from,a.to)>0)){var p=[l,1],c=ls(u.from,a.from),d=ls(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from}),(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to}),n.splice.apply(n,p),l+=p.length-1}}return n}function Pr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function Dr(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function _r(e){return e.inclusiveLeft?-1:0}function Mr(e){return e.inclusiveRight?1:0}function wr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ls(r.from,n.from)||_r(e)-_r(t);if(o)return-o;var s=ls(r.to,n.to)||Mr(e)-Mr(t);return s?s:t.id-e.id}function Gr(e,t){var i,r=ss&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o)n=r[o],n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||wr(i,n.marker)<0)&&(i=n.marker);return i}function kr(e){return Gr(e,!0)}function Br(e){return Gr(e,!1)}function Ur(e,t,i,r,n){var o=xn(e,t),s=ss&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ls(u.from,i)||_r(l.marker)-_r(n),c=ls(u.to,r)||Mr(l.marker)-Mr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ls(u.to,i)||Mr(l.marker)-_r(n))>0||p>=0&&(ls(u.from,r)||_r(l.marker)-Mr(n))<0))return!0}}}function Vr(e){for(var t;t=kr(e);)e=t.find(-1,!0).line;return e}function Hr(e){for(var t,i;t=Br(e);)e=t.find(1,!0).line,(i||(i=[])).push(e);return i}function Fr(e,t){var i=xn(e,t),r=Vr(i);return i==r?t:Tn(r)}function jr(e,t){if(t>e.lastLine())return t;var i,r=xn(e,t);if(!Wr(e,r))return t;for(;i=Br(r);)r=i.find(1,!0).line;return Tn(r)+1}function Wr(e,t){var i=ss&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n)if(r=i[n],r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&qr(e,t,r))return!0}}function qr(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return qr(e,r.line,Ir(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o)if(n=t.markedSpans[o],n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&qr(e,t,n))return!0}function zr(e,t,i){An(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&or(e,null,i)}function Xr(e){return null!=e.height?e.height:(Eo(document.body,e.node)||co(e.cm.display.measure,uo("div",[e.node],null,"position: relative")),e.height=e.node.offsetHeight)}function Yr(e,t,i,r){var n=new Us(e,i,r);return n.noHScroll&&(e.display.alignWidgets=!0),ur(e,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);if(null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n),n.line=t,!Wr(e.doc,t)){var r=An(t)<e.doc.scrollTop;In(t,t.height+Xr(n)),r&&or(e,null,n.height),e.curOp.forceUpdate=!0}return!0}),n}function Kr(e,t,i,r){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),Pr(e),Dr(e,i);var n=r?r(e):1;n!=e.height&&In(e,n)}function $r(e){e.parent=null,Pr(e)}function Qr(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function Zr(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function Jr(e,t,i){for(var r=0;10>r;r++){var n=e.token(t,i);if(t.pos>t.start)return n}throw new Error("Mode "+e.name+" failed to advance stream.")}function en(t,i,r,n,o,s,a){var l=r.flattenSpans;null==l&&(l=t.options.flattenSpans);var u,p=0,c=null,d=new ws(i,t.options.tabSize);for(""==i&&Qr(Zr(r,n),s);!d.eol();){if(d.pos>t.options.maxHighlightLength?(l=!1,a&&nn(t,i,n,d.pos),d.pos=i.length,u=null):u=Qr(Jr(r,d,n),s),t.options.addModeClass){var E=e.innerMode(r,n).mode.name;E&&(u="m-"+(u?E+" "+u:E))}l&&c==u||(p<d.start&&o(d.start,c),p=d.start,c=u),d.start=d.pos}for(;p<d.pos;){var h=Math.min(d.pos,p+5e4);o(h,c),p=h}}function tn(e,t,i,r){var n=[e.state.modeGen],o={};en(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;en(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r),l+=2,u=Math.min(e,r)}if(t)if(a.opaque)n.splice(i,l-i,e,"cm-overlay "+t),l=i+2;else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function rn(e,t){if(!t.styles||t.styles[0]!=e.state.modeGen){var i=tn(e,t,t.stateAfter=Lt(e,Tn(t)));t.styles=i.styles,i.classes?t.styleClasses=i.classes:t.styleClasses&&(t.styleClasses=null)}return t.styles}function nn(e,t,i,r){var n=e.doc.mode,o=new ws(t,e.options.tabSize);for(o.start=o.pos=r||0,""==t&&Zr(n,i);!o.eol()&&o.pos<=e.options.maxHighlightLength;)Jr(n,o,i),o.start=o.pos}function on(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?Fs:Hs;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function sn(e,t){var i=uo("span",null,null,Wo?"padding-right: .1px":null),r={pre:uo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0,r.addToken=ln,(jo||Wo)&&e.getOption("lineWrapping")&&(r.addToken=un(r.addToken)),yo(e.display.measure)&&(o=Sn(s))&&(r.addToken=pn(r.addToken,o)),r.map=[],dn(s,r,rn(e,s)),s.styleClasses&&(s.styleClasses.bgClass&&(r.bgClass=vo(s.styleClasses.bgClass,r.bgClass||"")),s.styleClasses.textClass&&(r.textClass=vo(s.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(To(e.display.measure))),0==n?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return Js(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=vo(r.pre.className,r.textClass||"")),r}function an(e){var t=uo("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t}function ln(e,t,i,r,n,o){if(t){var s=e.cm.options.specialChars,a=!1;if(s.test(t))for(var l=document.createDocumentFragment(),u=0;;){s.lastIndex=u;var p=s.exec(t),c=p?p.index-u:t.length-u;if(c){var d=document.createTextNode(t.slice(u,u+c));l.appendChild(Vo?uo("span",[d]):d),e.map.push(e.pos,e.pos+c,d),e.col+=c,e.pos+=c}if(!p)break;if(u+=c+1," "==p[0]){var E=e.cm.options.tabSize,h=E-e.col%E,d=l.appendChild(uo("span",Jn(h),"cm-tab"));e.col+=h}else{var d=e.cm.options.specialCharPlaceholder(p[0]);l.appendChild(Vo?uo("span",[d]):d),e.col+=1}e.map.push(e.pos,e.pos+1,d),e.pos++}else{e.col+=t.length;var l=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,l),Vo&&(a=!0),e.pos+=t.length}if(i||r||n||a){var f=i||"";r&&(f+=r),n&&(f+=n);var m=uo("span",[l],f);return o&&(m.title=o),e.content.appendChild(m)}e.content.appendChild(l)}}function un(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";return t+=" "}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function pn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a),o=null,r=r.slice(c.to-l),l=c.to}}}function cn(e,t,i,r){var n=!r&&i.widgetNode;n&&(e.map.push(e.pos,e.pos+t,n),e.content.appendChild(n)),e.pos+=t}function dn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d=n.length,E=0,h=1,f="",m=0;;){if(m==E){a=l=u=p="",c=null,m=1/0;for(var g=[],v=0;v<r.length;++v){var x=r[v],N=x.marker;x.from<=E&&(null==x.to||x.to>E)?(null!=x.to&&m>x.to&&(m=x.to,l=""),N.className&&(a+=" "+N.className),N.startStyle&&x.from==E&&(u+=" "+N.startStyle),N.endStyle&&x.to==m&&(l+=" "+N.endStyle),N.title&&!p&&(p=N.title),N.collapsed&&(!c||wr(c.marker,N)<0)&&(c=x)):x.from>E&&m>x.from&&(m=x.from),"bookmark"==N.type&&x.from==E&&N.widgetNode&&g.push(N)}if(c&&(c.from||0)==E&&(cn(t,(null==c.to?d+1:c.to)-E,c.marker,null==c.from),null==c.to))return;if(!c&&g.length)for(var v=0;v<g.length;++v)cn(t,0,g[v])}if(E>=d)break;for(var L=Math.min(d,m);;){if(f){var I=E+f.length;if(!c){var T=I>L?f.slice(0,L-E):f;t.addToken(t,T,s?s+a:a,u,E+T.length==m?l:"",p)}if(I>=L){f=f.slice(L-E),E=L;break}E=I,u=""}f=n.slice(o,o=i[h++]),s=on(i[h++],t.cm.options)}}else for(var h=1;h<i.length;h+=2)t.addToken(t,n.slice(o,o=i[h]),on(i[h+1],t.cm.options))}function En(e,t){return 0==t.from.ch&&0==t.to.ch&&""==eo(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function hn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){Kr(e,i,n,r),qn(e,"change",e,t)}var s=t.from,a=t.to,l=t.text,u=xn(e,s.line),p=xn(e,a.line),c=eo(l),d=n(l.length-1),E=a.line-s.line;if(En(e,t)){for(var h=0,f=[];h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));o(p,p.text,d),E&&e.remove(s.line,E),f.length&&e.insert(s.line,f)}else if(u==p)if(1==l.length)o(u,u.text.slice(0,s.ch)+c+u.text.slice(a.ch),d);else{for(var f=[],h=1;h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));f.push(new Vs(c+u.text.slice(a.ch),d,r)),o(u,u.text.slice(0,s.ch)+l[0],n(0)),e.insert(s.line+1,f)}else if(1==l.length)o(u,u.text.slice(0,s.ch)+l[0]+p.text.slice(a.ch),n(0)),e.remove(s.line+1,E);else{o(u,u.text.slice(0,s.ch)+l[0],n(0)),o(p,c+p.text.slice(a.ch),d);for(var h=1,f=[];h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));E>1&&e.remove(s.line+1,E-1),e.insert(s.line+1,f)}qn(e,"change",e,t)}function fn(e){this.lines=e,this.parent=null;for(var t=0,i=0;t<e.length;++t)e[t].parent=this,i+=e[t].height;this.height=i}function mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize(),i+=n.height,n.parent=this}this.size=t,this.height=i,this.parent=null}function gn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;(!i||l)&&(t(a.doc,l),r(a.doc,e,l))}}}r(e,null,!0)}function vn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,s(e),i(e),e.options.lineWrapping||E(e),e.options.mode=t.modeOption,ii(e)}function xn(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Nn(e,t,i){var r=[],n=t.line;return e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch)),n==t.line&&(o=o.slice(t.ch)),r.push(o),++n}),r}function Ln(e,t,i){var r=[];return e.iter(t,i,function(e){r.push(e.text)}),r}function In(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Tn(e){if(null==e.parent)return null;for(var t=e.parent,i=to(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function yn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o,i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function An(e){e=Vr(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function Sn(e){var t=e.order;return null==t&&(t=e.order=Ta(e.text)),t}function Cn(e){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e||1}function Rn(e,t){var i={from:j(t.from),to:xs(t),text:Nn(e,t.from,t.to)};return wn(e,i,t.from.line,t.to.line+1),gn(e,function(e){wn(e,i,t.from.line,t.to.line+1)},!0),i}function bn(e){for(;e.length;){var t=eo(e);if(!t.ranges)break;e.pop()}}function On(e,t){return t?(bn(e.done),eo(e.done)):e.done.length&&!eo(e.done).ranges?eo(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),eo(e.done)):void 0}function Pn(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=On(n,n.lastOp==r))){var a=eo(o.changes);0==ls(t.from,t.to)&&0==ls(t.from,a.to)?a.to=xs(t):o.changes.push(Rn(e,t))}else{var l=eo(n.done);for(l&&l.ranges||Mn(e.sel,n.done),o={changes:[Rn(e,t)],generation:n.generation},n.done.push(o);n.done.length>n.undoDepth;)n.done.shift(),n.done[0].ranges||n.done.shift()}n.done.push(i),n.generation=++n.maxGeneration,n.lastModTime=n.lastSelTime=s,n.lastOp=r,n.lastOrigin=n.lastSelOrigin=t.origin,a||Js(e,"historyAdded")}function Dn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function _n(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Dn(e,o,eo(n.done),t))?n.done[n.done.length-1]=t:Mn(t,n.done),n.lastSelTime=+new Date,n.lastSelOrigin=o,n.lastOp=i,r&&r.clearRedo!==!1&&bn(n.undone)}function Mn(e,t){var i=eo(t);i&&i.ranges&&i.equals(e)||t.push(e)}function wn(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans),++o})}function Gn(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function kn(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(Gn(i[r]));return n}function Bn(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?z.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];if(a.push({from:p.from,to:p.to,text:p.text}),t)for(var c in p)(u=c.match(/^spans_(\d+)$/))&&to(t,Number(u[1]))>-1&&(eo(a)[c]=p[c],delete p[c])}}}return n}function Un(e,t,i,r){i<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function Vn(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){o.copied||(o=e[n]=o.deepCopy(),o.copied=!0);for(var a=0;a<o.ranges.length;a++)Un(o.ranges[a].anchor,t,i,r),Un(o.ranges[a].head,t,i,r)}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line)l.from=as(l.from.line+r,l.from.ch),l.to=as(l.to.line+r,l.to.ch);else if(t<=l.to.line){s=!1;break}}s||(e.splice(0,n+1),n=0)}}}function Hn(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;Vn(e.done,i,r,n),Vn(e.undone,i,r,n)}function Fn(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function jn(e){return e.target||e.srcElement}function Wn(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),es&&e.ctrlKey&&1==t&&(t=3),t
}function qn(e,t){function i(e){return function(){e.apply(null,n)}}var r=e._handlers&&e._handlers[t];if(r){var n=Array.prototype.slice.call(arguments,2);Xs||(++ea,Xs=[],setTimeout(zn,0));for(var o=0;o<r.length;++o)Xs.push(i(r[o]))}}function zn(){--ea;var e=Xs;Xs=null;for(var t=0;t<e.length;++t)e[t]()}function Xn(e,t,i){return Js(e,i||t.type,e,t),Fn(t)||t.codemirrorIgnore}function Yn(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==to(i,t[r])&&i.push(t[r])}function Kn(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function $n(e){e.prototype.on=function(e,t){Qs(this,e,t)},e.prototype.off=function(e,t){Zs(this,e,t)}}function Qn(){this.id=null}function Zn(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);if(n+=o-r,n+=i-n%i,r=o+1,n>=t)return r}}function Jn(e){for(;aa.length<=e;)aa.push(eo(aa)+" ");return aa[e]}function eo(e){return e[e.length-1]}function to(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function io(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function ro(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e,i=new r}return t&&no(t,i),i}function no(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function oo(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function so(e,t){return t?t.source.indexOf("\\w")>-1&&ca(e)?!0:t.test(e):ca(e)}function ao(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function lo(e){return e.charCodeAt(0)>=768&&da.test(e)}function uo(e,t,i,r){var n=document.createElement(e);if(i&&(n.className=i),r&&(n.style.cssText=r),"string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function po(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function co(e,t){return po(e).appendChild(t)}function Eo(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function ho(){return document.activeElement}function fo(e){return new RegExp("\\b"+e+"\\b\\s*")}function mo(e,t){var i=fo(t);i.test(e.className)&&(e.className=e.className.replace(i,""))}function go(e,t){fo(t).test(e.className)||(e.className+=" "+t)}function vo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!fo(i[r]).test(t)&&(t+=" "+i[r]);return t}function xo(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function No(){ma||(Lo(),ma=!0)}function Lo(){var e;Qs(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,Ea=null,xo(gi)},100))}),Qs(window,"blur",function(){xo(Vi)})}function Io(e){if(null!=Ea)return Ea;var t=uo("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return co(e,t),t.offsetWidth&&(Ea=t.offsetHeight-t.clientHeight),Ea||0}function To(e){if(null==ha){var t=uo("span","");co(e,uo("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(ha=t.offsetWidth<=1&&t.offsetHeight>2&&!Uo)}return ha?uo("span",""):uo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function yo(e){if(null!=fa)return fa;var t=co(e,document.createTextNode("AخA")),i=ua(t,0,1).getBoundingClientRect();if(i.left==i.right)return!1;var r=ua(t,1,2).getBoundingClientRect();return fa=r.right-i.right<3}function Ao(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];(s.from<i&&s.to>t||t==i&&s.to==t)&&(r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr"),n=!0)}n||r(t,i,"ltr")}function So(e){return e.level%2?e.to:e.from}function Co(e){return e.level%2?e.from:e.to}function Ro(e){var t=Sn(e);return t?So(t[0]):0}function bo(e){var t=Sn(e);return t?Co(eo(t)):e.text.length}function Oo(e,t){var i=xn(e.doc,t),r=Vr(i);r!=i&&(t=Tn(r));var n=Sn(r),o=n?n[0].level%2?bo(r):Ro(r):0;return as(t,o)}function Po(e,t){for(var i,r=xn(e.doc,t);i=Br(r);)r=i.find(1,!0).line,t=null;var n=Sn(r),o=n?n[0].level%2?Ro(r):bo(r):r.text.length;return as(null==t?Tn(r):t,o)}function Do(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function _o(e,t){Ia=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i)return Do(e,n.level,e[i].level)?(n.from!=n.to&&(Ia=i),r):(n.from!=n.to&&(Ia=r),i);i=r}}return i}function Mo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&lo(e.text.charAt(t)));return t}function wo(e,t,i,r){var n=Sn(e);if(!n)return Go(e,t,i,r);for(var o=_o(n,t),s=n[o],a=Mo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to)return _o(n,a)==o?a:(s=n[o+=i],i>0==s.level%2?s.to:s.from);if(s=n[o+=i],!s)return null;a=i>0==s.level%2?Mo(e,s.to,-1,r):Mo(e,s.from,1,r)}}function Go(e,t,i,r){var n=t+i;if(r)for(;n>0&&lo(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ko=/gecko\/\d/i.test(navigator.userAgent),Bo=/MSIE \d/.test(navigator.userAgent),Uo=Bo&&(null==document.documentMode||document.documentMode<8),Vo=Bo&&(null==document.documentMode||document.documentMode<9),Ho=Bo&&(null==document.documentMode||document.documentMode<10),Fo=/Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent),jo=Bo||Fo,Wo=/WebKit\//.test(navigator.userAgent),qo=Wo&&/Qt\/\d+\.\d+/.test(navigator.userAgent),zo=/Chrome\//.test(navigator.userAgent),Xo=/Opera\//.test(navigator.userAgent),Yo=/Apple Computer/.test(navigator.vendor),Ko=/KHTML\//.test(navigator.userAgent),$o=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),Qo=/PhantomJS/.test(navigator.userAgent),Zo=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Jo=Zo||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),es=Zo||/Mac/.test(navigator.platform),ts=/win/i.test(navigator.platform),is=Xo&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);is&&(is=Number(is[1])),is&&is>=15&&(Xo=!1,Wo=!0);var rs=es&&(qo||Xo&&(null==is||12.11>is)),ns=ko||jo&&!Vo,os=!1,ss=!1,as=e.Pos=function(e,t){return this instanceof as?(this.line=e,void(this.ch=t)):new as(e,t)},ls=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};z.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ls(i.anchor,r.anchor)||0!=ls(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new X(j(this.ranges[t].anchor),j(this.ranges[t].head));return new z(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ls(t,r.from())>=0&&ls(e,r.to())<=0)return i}return-1}},X.prototype={from:function(){return q(this.anchor,this.head)},to:function(){return W(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var us,ps,cs,ds={left:0,right:0,top:0,bottom:0},Es=0,hs=0,fs=0,ms=null;jo?ms=-.53:ko?ms=15:zo?ms=-.7:Yo&&(ms=-1/3);var gs,vs=null,xs=e.changeEnd=function(e){return e.text?as(e.from.line+e.text.length-1,eo(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus(),Ei(this),pi(this)},setOption:function(e,t){var i=this.options,r=i[e];(i[e]!=t||"mode"==e)&&(i[e]=t,Ls.hasOwnProperty(e)&&Qt(this,Ls[e])(this,t,r))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](e)},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||"string"!=typeof t[i]&&t[i].name==e)return t.splice(i,1),!0},addOverlay:Zt(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque}),this.state.modeGen++,ii(this)}),removeOverlay:Zt(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(i,1),this.state.modeGen++,void ii(this)}}),indentLine:Zt(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),J(this.doc,e)&&lr(this,e,t,i)}),indentSelection:Zt(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty())n.head.line>i&&(lr(this,n.head.line,e,!0),i=n.head.line,r==this.doc.sel.primIndex&&sr(this));else{var o=Math.max(i,n.from().line),s=n.to();i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var a=o;i>a;++a)lr(this,a,e)}}}),getTokenAt:function(e,t){var i=this.doc;e=Q(i,e);for(var r=Lt(this,e.line,t),n=this.doc.mode,o=xn(i,e.line),s=new ws(o.text,this.options.tabSize);s.pos<e.ch&&!s.eol();){s.start=s.pos;var a=Jr(n,s,r)}return{start:s.start,end:s.pos,string:s.current(),type:a||null,state:r}},getTokenTypeAt:function(e){e=Q(this.doc,e);var t,i=rn(this,xn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!Cs.hasOwnProperty(t))return Cs;var r=Cs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==to(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;return e=$(i,null==e?i.first+i.size-1:e),Lt(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();return i=null==e?r.head:"object"==typeof e?Q(this.doc,e):e?r.from():r.to(),Ht(this,i,t||"page")},charCoords:function(e,t){return Vt(this,Q(this.doc,e),t||"page")},coordsChar:function(e,t){return e=Ut(this,e,t||"page"),Wt(this,e.left,e.top)},lineAtHeight:function(e,t){return e=Ut(this,{top:e,left:0},t||"page").top,yn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>r&&(e=r,i=!0);var n=xn(this.doc,e);return Bt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-An(n):0)},defaultTextHeight:function(){return zt(this.display)},defaultCharWidth:function(){return Xt(this.display)},setGutterMarker:Zt(function(e,t,i){return ur(this,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=i,!i&&ao(r)&&(e.gutterMarkers=null),!0})}),clearGutter:Zt(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){i.gutterMarkers&&i.gutterMarkers[e]&&(i.gutterMarkers[e]=null,ri(t,r,"gutter"),ao(i.gutterMarkers)&&(i.gutterMarkers=null)),++r})}),addLineClass:Zt(function(e,t,i){return ur(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass";if(e[r]){if(new RegExp("(?:^|\\s)"+i+"(?:$|\\s)").test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:Zt(function(e,t,i){return ur(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(new RegExp("(?:^|\\s+)"+i+"(?:$|\\s+)"));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),addLineWidget:Zt(function(e,t,i){return Yr(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!J(this.doc,e))return null;var t=e;if(e=xn(this.doc,e),!e)return null}else{var t=Tn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Ht(this,Q(this.doc,e));var s=e.bottom,a=e.left;if(t.style.position="absolute",o.sizer.appendChild(t),"over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom),a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px",t.style.left=t.style.right="","right"==n?(a=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=a+"px"),i&&rr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Zt(wi),triggerOnKeyPress:Zt(Bi),triggerOnKeyUp:Zt(ki),execCommand:function(e){return Os.hasOwnProperty(e)?Os[e](this):void 0},findPosH:function(e,t,i,r){var n=1;0>t&&(n=-1,t=-t);for(var o=0,s=Q(this.doc,e);t>o&&(s=cr(this.doc,s,n,i,r),!s.hitSide);++o);return s},moveH:Zt(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?cr(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},oa)}),deleteH:Zt(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):pr(this,function(i){var n=cr(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;0>t&&(n=-1,t=-t);for(var s=0,a=Q(this.doc,e);t>s;++s){var l=Ht(this,a,"div");if(null==o?o=l.left:l.left=o,a=dr(this,l,n,i),a.hitSide)break}return a},moveV:Zt(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();if(r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Ht(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn),n.push(a.left);var l=dr(i,a,e,t);return"page"==t&&s==r.sel.primary()&&or(i,null,Vt(i,l,"div").top-a.top),l},oa),n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),toggleOverwrite:function(e){(null==e||e!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?go(this.display.cursorDiv,"CodeMirror-overwrite"):mo(this.display.cursorDiv,"CodeMirror-overwrite"),Js(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return ho()==this.display.input},scrollTo:Zt(function(e,t){(null!=e||null!=t)&&ar(this),null!=e&&(this.curOp.scrollLeft=e),null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller,t=ta;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-t,width:e.scrollWidth-t,clientHeight:e.clientHeight-t,clientWidth:e.clientWidth-t}},scrollIntoView:Zt(function(e,t){if(null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:as(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line)ar(this),this.curOp.scrollToPos=e;else{var i=nr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Zt(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}null!=e&&(this.display.wrapper.style.width=i(e)),null!=t&&(this.display.wrapper.style.height=i(t)),this.options.lineWrapping&&Mt(this),this.curOp.forceUpdate=!0,Js(this,"refresh",this)}),operation:function(e){return $t(this,e)},refresh:Zt(function(){var e=this.display.cachedTextHeight;ii(this),this.curOp.forceUpdate=!0,wt(this),this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop),c(this),(null==e||Math.abs(e-zt(this.display))>.5)&&s(this),Js(this,"refresh",this)}),swapDoc:Zt(function(e){var t=this.doc;return t.cm=null,vn(this,e),wt(this),di(this),this.scrollTo(e.scrollLeft,e.scrollTop),qn(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},$n(e);var Ns=e.defaults={},Ls=e.optionHandlers={},Is=e.Init={toString:function(){return"CodeMirror.Init"}};hr("value","",function(e,t){e.setValue(t)},!0),hr("mode",null,function(e,t){e.doc.modeOption=t,i(e)},!0),hr("indentUnit",2,i,!0),hr("indentWithTabs",!1),hr("smartIndent",!0),hr("tabSize",4,function(e){r(e),wt(e),ii(e)},!0),hr("specialChars",/[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),hr("specialCharPlaceholder",an,function(e){e.refresh()},!0),hr("electricChars",!0),hr("rtlMoveVisually",!ts),hr("wholeLineUpdateBefore",!0),hr("theme","default",function(e){l(e),u(e)},!0),hr("keyMap","default",a),hr("extraKeys",null),hr("lineWrapping",!1,n,!0),hr("gutters",[],function(e){h(e.options),u(e)},!0),hr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?L(e.display)+"px":"0",e.refresh()},!0),hr("coverGutterNextToScrollbar",!1,m,!0),hr("lineNumbers",!1,function(e){h(e.options),u(e)},!0),hr("firstLineNumber",1,u,!0),hr("lineNumberFormatter",function(e){return e},u,!0),hr("showCursorWhenSelecting",!1,ht,!0),hr("resetSelectionOnContextMenu",!0),hr("readOnly",!1,function(e,t){"nocursor"==t?(Vi(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||di(e))}),hr("disableInput",!1,function(e,t){t||di(e)},!0),hr("dragDrop",!0),hr("cursorBlinkRate",530),hr("cursorScrollMargin",0),hr("cursorHeight",1),hr("workTime",100),hr("workDelay",100),hr("flattenSpans",!0,r,!0),hr("addModeClass",!1,r,!0),hr("pollInterval",100),hr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),hr("historyEventDelay",1250),hr("viewportMargin",10,function(e){e.refresh()},!0),hr("maxHighlightLength",1e4,r,!0),hr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),hr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),hr("autofocus",null);var Ts=e.modes={},ys=e.mimeModes={};e.defineMode=function(t,i){if(e.defaults.mode||"null"==t||(e.defaults.mode=t),arguments.length>2){i.dependencies=[];for(var r=2;r<arguments.length;++r)i.dependencies.push(arguments[r])}Ts[t]=i},e.defineMIME=function(e,t){ys[e]=t},e.resolveMode=function(t){if("string"==typeof t&&ys.hasOwnProperty(t))t=ys[t];else if(t&&"string"==typeof t.name&&ys.hasOwnProperty(t.name)){var i=ys[t.name];"string"==typeof i&&(i={name:i}),t=ro(i,t),t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}},e.getMode=function(t,i){var i=e.resolveMode(i),r=Ts[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(As.hasOwnProperty(i.name)){var o=As[i.name];for(var s in o)o.hasOwnProperty(s)&&(n.hasOwnProperty(s)&&(n["_"+s]=n[s]),n[s]=o[s])}if(n.name=i.name,i.helperType&&(n.helperType=i.helperType),i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n},e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),e.defineMIME("text/plain","null");var As=e.modeExtensions={};e.extendMode=function(e,t){var i=As.hasOwnProperty(e)?As[e]:As[e]={};no(t,i)},e.defineExtension=function(t,i){e.prototype[t]=i},e.defineDocExtension=function(e,t){Ws.prototype[e]=t},e.defineOption=hr;var Ss=[];e.defineInitHook=function(e){Ss.push(e)};var Cs=e.helpers={};e.registerHelper=function(t,i,r){Cs.hasOwnProperty(t)||(Cs[t]=e[t]={_global:[]}),Cs[t][i]=r},e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n),Cs[t]._global.push({pred:r,val:n})};var Rs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([])),i[r]=n}return i},bs=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state,e=i.mode}return i||{mode:e,state:t}};var Os=e.commands={selectAll:function(e){e.setSelection(as(e.firstLine(),0),as(e.lastLine()),ra)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),ra)},killLine:function(e){pr(e,function(t){if(t.empty()){var i=xn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:as(t.head.line+1,0)}:{from:t.head,to:as(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){pr(e,function(t){return{from:as(t.from().line,0),to:Q(e.doc,as(t.to().line+1,0))}})},delLineLeft:function(e){pr(e,function(e){return{from:as(e.from().line,0),to:e.from()}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(as(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(as(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Oo(e,t.head.line)},oa)},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){var i=Oo(e,t.head.line),r=e.getLineHandle(i.line),n=Sn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.head.line==i.line&&t.head.ch<=o&&t.head.ch;return as(i.line,s?0:o)}return i},oa)},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Po(e,t.head.line)},oa)},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},oa)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},oa)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=sa(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){$t(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=xn(e.doc,n.line).text;if(o)if(n.ch==o.length&&(n=new as(n.line,n.ch-1)),n.ch>0)n=new as(n.line,n.ch+1),e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),as(n.line,n.ch-2),n,"+transpose");else if(n.line>e.doc.first){var s=xn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),as(n.line-1,s.length-1),as(n.line,1),"+transpose")}i.push(new X(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){$t(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input"),e.indentLine(r.from().line+1,null,!0),sr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ps=e.keyMap={};Ps.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ps.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-Up":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Down":"goDocEnd","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ps.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineStart","Cmd-Right":"goLineEnd","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delLineLeft","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection",fallthrough:["basic","emacsy"]},Ps.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},Ps["default"]=es?Ps.macDefault:Ps.pcDefault;var Ds=e.lookupKey=function(e,t,i){function r(t){t=fr(t);var n=t[e];if(n===!1)return"stop";if(null!=n&&i(n))return!0;if(t.nofallthrough)return"stop";var o=t.fallthrough;if(null==o)return!1;if("[object Array]"!=Object.prototype.toString.call(o))return r(o);for(var s=0;s<o.length;++s){var a=r(o[s]);if(a)return a}return!1}for(var n=0;n<t.length;++n){var o=r(t[n]);if(o)return"stop"!=o}},_s=e.isModifierKey=function(e){var t=La[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Ms=e.keyName=function(e,t){if(Xo&&34==e.keyCode&&e["char"])return!1;var i=La[e.keyCode];return null==i||e.altGraphKey?!1:(e.altKey&&(i="Alt-"+i),(rs?e.metaKey:e.ctrlKey)&&(i="Ctrl-"+i),(rs?e.ctrlKey:e.metaKey)&&(i="Cmd-"+i),!t&&e.shiftKey&&(i="Shift-"+i),i)};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}if(i||(i={}),i.value=t.value,!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex),!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder),null==i.autofocus){var n=ho();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form&&(Qs(t.form,"submit",r),!i.leaveSubmitMethodAlone)){var o=t.form,s=o.submit;try{var a=o.submit=function(){r(),o.submit=s,o.submit(),o.submit=a}}catch(l){}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);return u.save=r,u.getTextArea=function(){return t},u.toTextArea=function(){r(),t.parentNode.removeChild(u.getWrapperElement()),t.style.display="",t.form&&(Zs(t.form,"submit",r),"function"==typeof t.form.submit&&(t.form.submit=s))},u};var ws=e.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0};ws.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));return i?(++this.pos,t):void 0},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);return t>-1?(this.pos=t,!0):void 0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=sa(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?sa(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return sa(this.string,null,this.tabSize)-(this.lineStart?sa(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&r.index>0?null:(r&&t!==!1&&(this.pos+=r[0].length),r)}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return n(o)==n(e)?(t!==!1&&(this.pos+=e.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Gs=e.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};$n(Gs),Gs.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Yt(e),Kn(this,"clear")){var i=this.find();i&&qn(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Ir(s.markedSpans,this);e&&!this.collapsed?ri(e,Tn(s),"text"):e&&(null!=a.to&&(n=Tn(s)),null!=a.from&&(r=Tn(s))),s.markedSpans=Tr(s.markedSpans,a),null==a.from&&this.collapsed&&!Wr(this.doc,s)&&e&&In(s,zt(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Vr(this.lines[o]),u=d(l);u>e.display.maxLineLength&&(e.display.maxLine=l,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&ii(e,r,n+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&ct(e.doc)),e&&qn(e,"markerCleared",e,this),t&&Kt(e),this.parent&&this.parent.clear()}},Gs.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Ir(o.markedSpans,this);if(null!=s.from&&(i=as(t?o:Tn(o),s.from),-1==e))return i;if(null!=s.to&&(r=as(t?o:Tn(o),s.to),1==e))return r}return i&&{from:i,to:r}},Gs.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&$t(i,function(){var r=e.line,n=Tn(e.line),o=bt(i,n);if(o&&(_t(o),i.curOp.selectionChanged=i.curOp.forceUpdate=!0),i.curOp.updateMaxLine=!0,!Wr(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=Xr(t)-s;a&&In(r,r.height+a)}})},Gs.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=to(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},Gs.prototype.detachLine=function(e){if(this.lines.splice(to(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ks=0,Bs=e.SharedTextMarker=function(e,t){this.markers=e,this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};$n(Bs),Bs.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();qn(this,"clear")}},Bs.prototype.find=function(e,t){return this.primary.find(e,t)
};var Us=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e,this.node=t};$n(Us),Us.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Tn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=Xr(this);$t(e,function(){zr(e,i,-o),ri(e,r,"widget"),In(i,Math.max(0,i.height-o))})}},Us.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=Xr(this)-e;r&&$t(t,function(){t.curOp.forceUpdate=!0,zr(t,i,r),In(i,i.height+r)})};var Vs=e.Line=function(e,t,i){this.text=e,Dr(this,t),this.height=i?i(this):1};$n(Vs),Vs.prototype.lineNo=function(){return Tn(this)};var Hs={},Fs={};fn.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height,$r(n),qn(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}},mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;if(r.removeInner(e,o),this.height-=s-r.height,n==o&&(this.children.splice(i--,1),r.parent=null),0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof fn))){var a=[];this.collapse(a),this.children=[new fn(a)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length,this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){if(n.insertInner(e,t,i),n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new fn(s);n.height-=a.height,this.children.splice(r+1,0,a),a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new mn(t);if(e.parent){e.size-=i.size,e.height-=i.height;var r=to(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new mn(e.children);n.parent=e,e.children=[n,i],e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var js=0,Ws=e.Doc=function(e,t,i){if(!(this instanceof Ws))return new Ws(e,t,i);null==i&&(i=0),mn.call(this,[new fn([new Vs("",null)])]),this.first=i,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=i;var r=as(i,0);this.sel=K(r),this.history=new Cn(null),this.id=++js,this.modeOption=t,"string"==typeof e&&(e=va(e)),hn(this,{from:r,to:r,text:e}),lt(this,K(r),ra)};Ws.prototype=ro(mn.prototype,{constructor:Ws,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ln(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:Jt(function(e){var t=as(this.first,0),i=this.first+this.size-1;Yi(this,{from:t,to:as(i,xn(this,i).text.length),text:va(e),origin:"setValue"},!0),lt(this,K(t))}),replaceRange:function(e,t,i,r){t=Q(this,t),i=i?Q(this,i):t,er(this,e,t,i,r)},getRange:function(e,t,i){var r=Nn(this,Q(this,e),Q(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return J(this,e)?xn(this,e):void 0},getLineNumber:function(e){return Tn(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=xn(this,e)),Vr(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return Q(this,e)},getCursor:function(e){var t,i=this.sel.primary();return t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:Jt(function(e,t,i){ot(this,Q(this,"number"==typeof e?as(e,t||0):e),null,i)}),setSelection:Jt(function(e,t,i){ot(this,Q(this,e),Q(this,t||e),i)}),extendSelection:Jt(function(e,t,i){it(this,Q(this,e),t&&Q(this,t),i)}),extendSelections:Jt(function(e,t){rt(this,et(this,e,t))}),extendSelectionsBy:Jt(function(e,t){rt(this,io(this.sel.ranges,e),t)}),setSelections:Jt(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new X(Q(this,e[r].anchor),Q(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),lt(this,Y(n,t),i)}}),addSelection:Jt(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new X(Q(this,e),Q(this,t||e))),lt(this,Y(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Nn(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Nn(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n")),t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:Jt(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:va(e[o]),origin:i}}for(var a=t&&"end"!=t&&zi(this,r,t),o=r.length-1;o>=0;o--)Yi(this,r[o]);a?at(this,a):this.cm&&sr(this.cm)}),undo:Jt(function(){$i(this,"undo")}),redo:Jt(function(){$i(this,"redo")}),undoSelection:Jt(function(){$i(this,"undo",!0)}),redoSelection:Jt(function(){$i(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new Cn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Bn(this.history.done),undone:Bn(this.history.undone)}},setHistory:function(e){var t=this.history=new Cn(this.history.maxGeneration);t.done=Bn(e.done.slice(0),null,!0),t.undone=Bn(e.undone.slice(0),null,!0)},markText:function(e,t,i){return mr(this,Q(this,e),Q(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};return e=Q(this,e),mr(this,e,e,i,"bookmark")},findMarksAt:function(e){e=Q(this,e);var t=[],i=xn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=Q(this,e),t=Q(this,t);var r=[],n=e.line;return this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)}),e},posFromIndex:function(e){var t,i=this.first;return this.iter(function(r){var n=r.text.length+1;return n>e?(t=e,!0):(e-=n,void++i)}),Q(this,as(i,t))},indexFromPos:function(e){e=Q(this,e);var t=e.ch;return e.line<this.first||e.ch<0?0:(this.iter(this.first,e.line,function(e){t+=e.text.length+1}),t)},copy:function(e){var t=new Ws(Ln(this,this.first,this.first+this.size),this.modeOption,this.first);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<i&&(i=e.to);var r=new Ws(Ln(this,t,i),e.mode||this.modeOption,t);return e.sharedHist&&(r.history=this.history),(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist}),r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],xr(r,vr(this)),r},unlinkDoc:function(t){if(t instanceof e&&(t=t.doc),this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1),t.unlinkDoc(this),Nr(vr(this));break}}if(t.history==this.history){var n=[t.id];gn(t,function(e){n.push(e.id)},!0),t.history=new Cn(null),t.history.done=Bn(this.history.done,n),t.history.undone=Bn(this.history.undone,n)}},iterLinkedDocs:function(e){gn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),Ws.prototype.eachLine=Ws.prototype.iter;var qs="iter insert remove copy getEditor".split(" ");for(var zs in Ws.prototype)Ws.prototype.hasOwnProperty(zs)&&to(qs,zs)<0&&(e.prototype[zs]=function(e){return function(){return e.apply(this.doc,arguments)}}(Ws.prototype[zs]));$n(Ws);var Xs,Ys=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},Ks=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},$s=e.e_stop=function(e){Ys(e),Ks(e)},Qs=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},Zs=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},Js=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},ea=0,ta=30,ia=e.Pass={toString:function(){return"CodeMirror.Pass"}},ra={scroll:!1},na={origin:"*mouse"},oa={origin:"+move"};Qn.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var sa=e.countColumn=function(e,t,i,r,n){null==t&&(t=e.search(/[^\s\u00a0]/),-1==t&&(t=e.length));for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o,s+=i-s%i,o=a+1}},aa=[""],la=function(e){e.select()};Zo?la=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:jo&&(la=function(e){try{e.select()}catch(t){}}),[].indexOf&&(to=function(e,t){return e.indexOf(t)}),[].map&&(io=function(e,t){return e.map(t)});var ua,pa=/[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ca=e.isWordChar=function(e){return/\w/.test(e)||e>""&&(e.toUpperCase()!=e.toLowerCase()||pa.test(e))},da=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ua=document.createRange?function(e,t,i){var r=document.createRange();return r.setEnd(e,i),r.setStart(e,t),r}:function(e,t,i){var r=document.body.createTextRange();return r.moveToElementText(e.parentNode),r.collapse(!0),r.moveEnd("character",i),r.moveStart("character",t),r},Bo&&(ho=function(){try{return document.activeElement}catch(e){return document.body}});var Ea,ha,fa,ma=!1,ga=function(){if(Vo)return!1;var e=uo("div");return"draggable"in e||"dragDrop"in e}(),va=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");-1!=s?(i.push(o.slice(0,s)),t+=s+1):(i.push(o),t=n+1)}return i}:function(e){return e.split(/\r\n?|\n/)},xa=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Na=function(){var e=uo("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),La={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=La,function(){for(var e=0;10>e;e++)La[e+48]=La[e+96]=String(e);for(var e=65;90>=e;e++)La[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)La[e+111]=La[e+63235]="F"+e}();var Ia,Ta=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e,this.from=t,this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,E=u;p>d;++d){var r=c[d];"m"==r?c[d]=E:E=r}for(var d=0,h=u;p>d;++d){var r=c[d];"1"==r&&"r"==h?c[d]="n":s.test(r)&&(h=r,"r"==r&&(c[d]="R"))}for(var d=1,E=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==E&&"1"==c[d+1]?c[d]="1":","!=r||E!=c[d+1]||"1"!=E&&"n"!=E||(c[d]=E),E=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var f=d+1;p>f&&"%"==c[f];++f);for(var m=d&&"!"==c[d-1]||p>f&&"1"==c[f]?"1":"N",g=d;f>g;++g)c[g]=m;d=f-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var f=d+1;p>f&&o.test(c[f]);++f);for(var v="L"==(d?c[d-1]:u),x="L"==(p>f?c[f]:u),m=v||x?"L":"R",g=d;f>g;++g)c[g]=m;d=f-1}for(var N,L=[],d=0;p>d;)if(a.test(c[d])){var I=d;for(++d;p>d&&a.test(c[d]);++d);L.push(new t(0,I,d))}else{var T=d,y=L.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=T;d>g;)if(l.test(c[g])){g>T&&L.splice(y,0,new t(1,T,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);L.splice(y,0,new t(2,A,g)),T=g}else++g;d>T&&L.splice(y,0,new t(1,T,d))}return 1==L[0].level&&(N=i.match(/^\s+/))&&(L[0].from=N[0].length,L.unshift(new t(0,0,N[0].length))),1==eo(L).level&&(N=i.match(/\s+$/))&&(eo(L).to-=N[0].length,L.push(new t(0,p-N[0].length,p))),L[0].level!=eo(L).level&&L.push(new t(L[0].level,p,p)),L}}();return e.version="4.2.0",e})},{}],9:[function(t,i){!function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(Et.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Lt[e]={};return ot.each(e.match(Nt)||[],function(e,i){t[i]=!0}),t}function a(){ft.addEventListener?(ft.removeEventListener("DOMContentLoaded",l,!1),t.removeEventListener("load",l,!1)):(ft.detachEvent("onreadystatechange",l),t.detachEvent("onload",l))}function l(){(ft.addEventListener||"load"===event.type||"complete"===ft.readyState)&&(a(),ot.ready())}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();if(i=e.getAttribute(r),"string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t)return u||(u=a?e[s]=K.pop()||ot.guid++:s),l[u]||(l[u]=a?{}:{toJSON:ot.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==i&&(o[ot.camelCase(t)]=i),"string"==typeof t?(n=o[t],null==n&&(n=o[ot.camelCase(t)])):n=o,n}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t&&(r=i?s[a]:s[a].data)){ot.isArray(t)?t=t.concat(ot.map(t,ot.camelCase)):t in r?t=[t]:(t=ot.camelCase(t),t=t in r?[t]:t.split(" ")),n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}(i||(delete s[a].data,p(s[a])))&&(o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null)}}}function E(){return!0}function h(){return!1}function f(){try{return ft.activeElement}catch(e){}}function m(e){var t=kt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){return e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type,e}function L(e){var t=Yt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function I(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle,s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){if(i=t.nodeName.toLowerCase(),!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}"script"===i&&t.text!==e.text?(N(t).text=e.text,L(t)):"object"===i?(t.parentNode&&(t.outerHTML=e.outerHTML),rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===i&&Pt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");return n.detach(),o}function S(e){var t=ft,i=ei[e];return i||(i=A(e,t),"none"!==i&&i||(Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Jt[0].contentWindow||Jt[0].contentDocument).document,t.write(),t.close(),i=A(e,t),Jt.detach()),ei[e]=i),i}function C(e,t){return{get:function(){var i=e();if(null!=i)return i?void delete this.get:(this.get=t).apply(this,arguments)}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=Ei.length;n--;)if(t=Ei[n]+i,t in e)return t;return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++)r=e[s],r.style&&(o[s]=ot._data(r,"olddisplay"),i=r.style.display,t?(o[s]||"none"!==i||(r.style.display=""),""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))):(n=bt(r),(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2)"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n)),r?("content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n)),"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))):(s+=ot.css(e,"padding"+Rt[o],!0,n),"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n)));return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){if(n=ii(e,t,o),(0>n||null==n)&&(n=e.style[t]),ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]),n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function _(e,t,i,r,n){return new _.prototype.init(e,t,i,r,n)}function M(){return setTimeout(function(){hi=void 0}),hi=ot.now()}function w(e,t){var i,r={height:e},n=0;for(t=t?1:0;4>n;n+=2-t)i=Rt[n],r["margin"+i]=r["padding"+i]=e;return t&&(r.opacity=r.width=e),r}function G(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function k(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},E=e.style,h=e.nodeType&&bt(e),f=ot._data(e,"fxshow");i.queue||(a=ot._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,l=a.empty.fire,a.empty.fire=function(){a.unqueued||l()}),a.unqueued++,c.always(function(){c.always(function(){a.unqueued--,ot.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(i.overflow=[E.overflow,E.overflowX,E.overflowY],u=ot.css(e,"display"),p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u,"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?E.zoom=1:E.display="inline-block")),i.overflow&&(E.overflow="hidden",rt.shrinkWrapBlocks()||c.always(function(){E.overflow=i.overflow[0],E.overflowX=i.overflow[1],E.overflowY=i.overflow[2]}));for(r in t)if(n=t[r],mi.exec(n)){if(delete t[r],o=o||"toggle"===n,n===(h?"hide":"show")){if("show"!==n||!f||void 0===f[r])continue;h=!0}d[r]=f&&f[r]||ot.style(e,r)}else u=void 0;if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(E.display=u);else{f?"hidden"in f&&(h=f.hidden):f=ot._data(e,"fxshow",{}),o&&(f.hidden=!h),h?ot(e).show():c.done(function(){ot(e).hide()}),c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d)s=G(h?f[r]:0,r,c),r in f||(f[r]=s.start,h&&(s.end=s.start,s.start="width"===r||"height"===r?1:0))}}function B(e,t){var i,r,n,o,s;for(i in e)if(r=ot.camelCase(i),n=t[r],o=e[i],ot.isArray(o)&&(n=o[1],o=e[i]=o[0]),i!==r&&(e[r]=o,delete e[i]),s=ot.cssHooks[r],s&&"expand"in s){o=s.expand(o),delete e[r];for(i in o)i in e||(e[i]=o[i],t[i]=n)}else t[r]=n}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||M(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);return a.notifyWith(e,[u,o,i]),1>o&&l?i:(a.resolveWith(e,[u]),!1)},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||M(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;for(n=!0;r>i;i++)u.tweens[i].run(1);return t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]),this}}),p=u.props;for(B(p,u.opts.specialEasing);s>o;o++)if(r=xi[o].call(u,e,p,u.opts))return r;return ot.map(p,G,u),ot.isFunction(u.opts.start)&&u.opts.start.call(e,u),ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){"string"!=typeof t&&(i=t,t="*");var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(i)):(e[r]=e[r]||[]).push(i)}}function H(e,t,i,r){function n(a){var l;return o[a]=!0,ot.each(e[a]||[],function(e,a){var u=a(t,i,r);return"string"!=typeof u||s||o[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),n(u),!1)}),l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function F(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);return i&&ot.extend(!0,e,i),e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"));if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}return o?(o!==l[0]&&l.unshift(o),i[o]):void 0}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];for(o=p.shift();o;)if(e.responseFields[o]&&(i[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=p.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(s=u[l+" "+o]||u["* "+o],!s)for(n in u)if(a=n.split(" "),a[1]===o&&(s=u[l+" "+a[0]]||u["* "+a[0]])){s===!0?s=u[n]:u[n]!==!0&&(o=a[0],p.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.1",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice},ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[a]||{},a++),"object"==typeof s||ot.isFunction(s)||(s={}),a===l&&(s=this,a--);l>a;a++)if(null!=(n=arguments[a]))for(r in n)e=s[r],i=n[r],s!==i&&(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))?(t?(t=!1,o=e&&ot.isArray(e)?e:[]):o=e&&ot.isPlainObject(e)?e:{},s[r]=ot.extend(u,o,i)):void 0!==i&&(s[r]=i));return s},ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i){if(a)for(;s>o&&(n=t.apply(e[o],i),n!==!1);o++);else for(o in e)if(n=t.apply(e[o],i),n===!1)break}else if(a)for(;s>o&&(n=t.call(e[o],o,e[o]),n!==!1);o++);else for(o in e)if(n=t.call(e[o],o,e[o]),n===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];return null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e)),i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);for(r=t.length,i=i?0>i?Math.max(0,r+i):i:0;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];
if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];return e.length=n,e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++)r=!t(e[o],o),r!==a&&n.push(e[o]);return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++)n=t(e[o],o,i),null!=n&&l.push(n);else for(o in e)n=t(e[o],o,i),null!=n&&l.push(n);return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;return"string"==typeof t&&(n=e[t],t=e,e=n),ot.isFunction(e)?(i=$.call(arguments,2),r=function(){return e.apply(t||this,i.concat($.call(arguments)))},r.guid=e.guid=e.guid||ot.guid++,r):void 0},now:function(){return+new Date},support:rt}),ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,E,h,f;if((t?t.ownerDocument||t:V)!==D&&P(t),t=t||D,i=i||[],!e||"string"!=typeof e)return i;if(1!==(a=t.nodeType)&&9!==a)return[];if(M&&!r){if(n=vt.exec(e))if(s=n[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return i;if(o.id===s)return i.push(o),i}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s)return i.push(o),i}else{if(n[2])return J.apply(i,t.getElementsByTagName(e)),i;if((s=n[3])&&L.getElementsByClassName&&t.getElementsByClassName)return J.apply(i,t.getElementsByClassName(s)),i}if(L.qsa&&(!w||!w.test(e))){if(E=c=U,h=t,f=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){for(u=A(e),(c=t.getAttribute("id"))?E=c.replace(Nt,"\\$&"):t.setAttribute("id",E),E="[id='"+E+"'] ",l=u.length;l--;)u[l]=E+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t,f=u.join(",")}if(f)try{return J.apply(i,h.querySelectorAll(f)),i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){return t.push(i+" ")>I.cacheLength&&delete e[t.shift()],e[i+" "]=r}var t=[];return e}function r(e){return e[U]=!0,e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)I.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&typeof e.getElementsByTagName!==X&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function E(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=F++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[H,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){if(l=t[U]||(t[U]={}),(a=l[r])&&a[0]===H&&a[1]===o)return u[2]=a[2];if(l[r]=u,u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function f(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)(o=e[a])&&(!i||i(o,r,n))&&(s.push(o),u&&t.push(a));return s}function g(e,t,i,n,o,s){return n&&!n[U]&&(n=g(n)),o&&!o[U]&&(o=g(o,s)),r(function(r,s,a,l){var u,p,c,d=[],E=[],h=s.length,g=r||f(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;if(i&&i(v,x,a,l),n)for(u=m(x,E),n(u,[],a,l),p=u.length;p--;)(c=u[p])&&(x[E[p]]=!(v[E[p]]=c));if(r){if(o||e){if(o){for(u=[],p=x.length;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}for(p=x.length;p--;)(c=x[p])&&(u=o?tt.call(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else x=m(x===s?x.splice(h,x.length):x),o?o(null,s,x,l):J.apply(s,x)})}function v(e){for(var t,i,r,n=e.length,o=I.relative[e[0].type],s=o||I.relative[" "],a=o?1:0,l=E(function(e){return e===t},s,!0),u=E(function(e){return tt.call(t,e)>-1},s,!0),p=[function(e,i,r){return!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r))}];n>a;a++)if(i=I.relative[e[a].type])p=[E(h(p),i)];else{if(i=I.filter[e[a].type].apply(null,e[a].matches),i[U]){for(r=++a;n>r&&!I.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,E=0,h="0",f=r&&[],g=[],v=R,x=r||o&&I.find.TAG("*",u),N=H+=null==v?1:Math.random()||.1,L=x.length;for(u&&(R=s!==D&&s);h!==L&&null!=(p=x[h]);h++){if(o&&p){for(c=0;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(H=N)}n&&((p=!d&&p)&&E--,r&&f.push(p))}if(E+=h,n&&h!==E){for(c=0;d=i[c++];)d(f,g,s,a);if(r){if(E>0)for(;h--;)f[h]||g[h]||(g[h]=Q.call(l));g=m(g)}J.apply(l,g),u&&!r&&g.length>0&&E+i.length>1&&t.uniqueSort(l)}return u&&(H=N,R=v),f};return n?r(s):s}var N,L,I,T,y,A,S,C,R,b,O,P,D,_,M,w,G,k,B,U="sizzle"+-new Date,V=e.document,H=0,F=0,j=i(),W=i(),q=i(),z=function(e,t){return e===t&&(O=!0),0},X="undefined",Y=1<<31,K={}.hasOwnProperty,$=[],Q=$.pop,Z=$.push,J=$.push,et=$.slice,tt=$.indexOf||function(e){for(var t=0,i=this.length;i>t;t++)if(this[t]===e)return t;return-1},it="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",nt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=nt.replace("w","w#"),st="\\["+rt+"*("+nt+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",at=":("+nt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+st+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),pt=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),ct=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),dt=new RegExp(at),Et=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+nt+")"),CLASS:new RegExp("^\\.("+nt+")"),TAG:new RegExp("^("+nt.replace("w","w*")+")"),ATTR:new RegExp("^"+st),PSEUDO:new RegExp("^"+at),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+it+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},ft=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Lt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),It=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{J.apply($=et.call(V.childNodes),V.childNodes),$[V.childNodes.length].nodeType}catch(Tt){J={apply:$.length?function(e,t){Z.apply(e,et.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}L=t.support={},y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},P=t.setDocument=function(e){var t,i=e?e.ownerDocument||e:V,r=i.defaultView;return i!==D&&9===i.nodeType&&i.documentElement?(D=i,_=i.documentElement,M=!y(i),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){P()},!1):r.attachEvent&&r.attachEvent("onunload",function(){P()})),L.attributes=n(function(e){return e.className="i",!e.getAttribute("className")}),L.getElementsByTagName=n(function(e){return e.appendChild(i.createComment("")),!e.getElementsByTagName("*").length}),L.getElementsByClassName=gt.test(i.getElementsByClassName)&&n(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),L.getById=n(function(e){return _.appendChild(e).id=U,!i.getElementsByName||!i.getElementsByName(U).length}),L.getById?(I.find.ID=function(e,t){if(typeof t.getElementById!==X&&M){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}},I.filter.ID=function(e){var t=e.replace(Lt,It);return function(e){return e.getAttribute("id")===t}}):(delete I.find.ID,I.filter.ID=function(e){var t=e.replace(Lt,It);return function(e){var i=typeof e.getAttributeNode!==X&&e.getAttributeNode("id");return i&&i.value===t}}),I.find.TAG=L.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==X?t.getElementsByTagName(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o},I.find.CLASS=L.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==X&&M?t.getElementsByClassName(e):void 0},G=[],w=[],(L.qsa=gt.test(i.querySelectorAll))&&(n(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&w.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||w.push("\\["+rt+"*(?:value|"+it+")"),e.querySelectorAll(":checked").length||w.push(":checked")}),n(function(e){var t=i.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&w.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||w.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),w.push(",.*:")})),(L.matchesSelector=gt.test(k=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&n(function(e){L.disconnectedMatch=k.call(e,"div"),k.call(e,"[s!='']:x"),G.push("!=",at)}),w=w.length&&new RegExp(w.join("|")),G=G.length&&new RegExp(G.join("|")),t=gt.test(_.compareDocumentPosition),B=t||gt.test(_.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},z=t?function(e,t){if(e===t)return O=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!L.sortDetached&&t.compareDocumentPosition(e)===r?e===i||e.ownerDocument===V&&B(V,e)?-1:t===i||t.ownerDocument===V&&B(V,t)?1:b?tt.call(b,e)-tt.call(b,t):0:4&r?-1:1)}:function(e,t){if(e===t)return O=!0,0;var r,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===i?-1:t===i?1:o?-1:a?1:b?tt.call(b,e)-tt.call(b,t):0;if(o===a)return s(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0},i):D},t.matches=function(e,i){return t(e,null,null,i)},t.matchesSelector=function(e,i){if((e.ownerDocument||e)!==D&&P(e),i=i.replace(ct,"='$1']"),!(!L.matchesSelector||!M||G&&G.test(i)||w&&w.test(i)))try{var r=k.call(e,i);if(r||L.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==D&&P(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=I.attrHandle[t.toLowerCase()],r=i&&K.call(I.attrHandle,t.toLowerCase())?i(e,t,!M):void 0;return void 0!==r?r:L.attributes||!M?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,i=[],r=0,n=0;if(O=!L.detectDuplicates,b=!L.sortStable&&e.slice(0),e.sort(z),O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}return b=null,e},T=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=T(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=T(t);return i},I=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Lt,It),e[3]=(e[3]||e[4]||e[5]||"").replace(Lt,It),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,i=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)&&(e[0]=e[0].slice(0,t),e[2]=i.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Lt,It).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==X&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);return null==o?"!="===i:i?(o+="","="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,E,h,f=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;f;){for(c=t;c=c[f];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=f="only"===e&&!h&&"nextSibling"}return!0}if(h=[s?m.firstChild:m.lastChild],s&&v){for(p=m[U]||(m[U]={}),u=p[e]||[],E=u[0]===H&&u[1],d=u[0]===H&&u[2],c=E&&m.childNodes[E];c=++E&&c&&c[f]||(d=E=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[H,E,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===H)d=u[1];else for(;(c=++E&&c&&c[f]||(d=E=0)||h.pop())&&((a?c.nodeName.toLowerCase()!==g:1!==c.nodeType)||!++d||(v&&((c[U]||(c[U]={}))[e]=[H,d]),c!==t)););return d-=n,d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=I.pseudos[e]||I.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[U]?o(i):o.length>1?(n=[e,e,"",i],I.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;)r=tt.call(e,n[s]),e[r]=!(t[r]=n[s])}):function(e){return o(e,0,n)}):o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){return t[0]=e,n(t,null,o,i),!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||T(t)).indexOf(e)>-1}}),lang:r(function(e){return Et.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(Lt,It).toLowerCase(),function(t){var i;do if(i=M?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return i=i.toLowerCase(),i===e||0===i.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!I.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return ft.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}},I.pseudos.nth=I.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})I.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})I.pseudos[N]=l(N);return c.prototype=I.filters=I.pseudos,I.setFilters=new c,A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);for(a=e,l=[],u=I.preFilter;a;){(!r||(n=ut.exec(a)))&&(n&&(a=a.slice(n[0].length)||a),l.push(o=[])),r=!1,(n=pt.exec(a))&&(r=n.shift(),o.push({value:r,type:n[0].replace(lt," ")}),a=a.slice(r.length));for(s in I.filter)!(n=ht[s].exec(a))||u[s]&&!(n=u[s](n))||(r=n.shift(),o.push({value:r,type:s,matches:n}),a=a.slice(r.length));if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)},S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){for(t||(t=A(e)),i=t.length;i--;)o=v(t[i]),o[U]?r.push(o):n.push(o);o=q(e,x(n,r)),o.selector=e}return o},C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);if(i=i||[],1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(s=o[0]).type&&L.getById&&9===t.nodeType&&M&&I.relative[o[1].type]){if(t=(I.find.ID(s.matches[0].replace(Lt,It),t)||[])[0],!t)return i;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(n=ht.needsContext.test(e)?0:o.length;n--&&(s=o[n],!I.relative[a=s.type]);)if((l=I.find[a])&&(r=l(s.matches[0].replace(Lt,It),xt.test(o[0].type)&&p(t.parentNode)||t))){if(o.splice(n,1),e=r.length&&d(o),!e)return J.apply(i,r),i;break}}return(u||S(e,c))(r,t,!M,i,xt.test(e)&&p(t.parentNode)||t),i},L.sortStable=U.split("").sort(z).join("")===U,L.detectDuplicates=!!O,P(),L.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))}),n(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),L.attributes&&n(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),n(function(e){return null==e.getAttribute("disabled")})||o(it,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(t);ot.find=pt,ot.expr=pt.selectors,ot.expr[":"]=ot.expr.pseudos,ot.unique=pt.uniqueSort,ot.text=pt.getText,ot.isXMLDoc=pt.isXML,ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,Et=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];return i&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))},ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);return i=this.pushStack(n>1?ot.unique(i):i),i.selector=this.selector?this.selector+" "+e:e,i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,ft=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof ot?t[0]:t,ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:ft,!0)),dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}if(r=ft.getElementById(i[2]),r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1,this[0]=r}return this.context=ft,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ot.isFunction(e)?"undefined"!=typeof ht.ready?ht.ready(e):e(ot):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ot.makeArray(e,this))};gt.prototype=ot.fn,ht=ot(ft);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));)1===n.nodeType&&r.push(n),n=n[t];return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}}),ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);return"Until"!==e.slice(-5)&&(r=i),r&&"string"==typeof r&&(n=ot.filter(r,n)),this.length>1&&(xt[e]||(n=ot.unique(n)),vt.test(e)&&(n=n.reverse())),this.pushStack(n)}});var Nt=/\S+/g,Lt={};ot.Callbacks=function(e){e="string"==typeof e?Lt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){for(i=e.memory&&s,r=!0,o=a||0,a=0,n=l.length,t=!0;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1,l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;!function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})}(arguments),t?n=l.length:i&&(a=r,p(i))}return this},remove:function(){return l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;)l.splice(r,1),t&&(n>=r&&n--,o>=r&&o--)}),this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],n=0,this},disable:function(){return l=u=i=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,i||c.disable(),this},locked:function(){return!u},fireWith:function(e,i){return!l||r&&!u||(i=i||[],i=[e,i.slice?i.slice():i],t?u.push(i):p(i)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){return n.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};return r.pipe=r.then,ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock),n[o[0]]=function(){return n[o[0]+"With"](this===n?r:this,arguments),this},n[o[0]+"With"]=s.fireWith}),r.promise(n),e&&e.call(n,n),n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this,r[e]=arguments.length>1?$.call(arguments):n,r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1)for(t=new Array(s),i=new Array(s),r=new Array(s);s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a;return a||l.resolveWith(r,o),l.promise()}});var It;ot.fn.ready=function(e){return ot.ready.promise().done(e),this},ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!ft.body)return setTimeout(ot.ready);ot.isReady=!0,e!==!0&&--ot.readyWait>0||(It.resolveWith(ft,[ot]),ot.fn.triggerHandler&&(ot(ft).triggerHandler("ready"),ot(ft).off("ready")))}}}),ot.ready.promise=function(e){if(!It)if(It=ot.Deferred(),"complete"===ft.readyState)setTimeout(ot.ready);else if(ft.addEventListener)ft.addEventListener("DOMContentLoaded",l,!1),t.addEventListener("load",l,!1);else{ft.attachEvent("onreadystatechange",l),t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&ft.documentElement}catch(r){}i&&i.doScroll&&!function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a(),ot.ready()}}()}return It.promise(e)};var Tt,yt="undefined";for(Tt in ot(rt))break;rt.ownLast="0"!==Tt,rt.inlineBlockNeedsLayout=!1,ot(function(){var e,t,i,r;i=ft.getElementsByTagName("body")[0],i&&i.style&&(t=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(t),typeof t.style.zoom!==yt&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",rt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(i.style.zoom=1)),i.removeChild(r))}),function(){var e=ft.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null}(),ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando],!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length&&(n=ot.data(o),1===o.nodeType&&!ot._data(o,"parsedAttrs"))){for(i=s.length;i--;)s[i]&&(r=s[i].name,0===r.indexOf("data-")&&(r=ot.camelCase(r.slice(5)),u(o,r,n[r])));ot._data(o,"parsedAttrs",!0)}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}}),ot.extend({queue:function(e,t,i){var r;return e?(t=(t||"fx")+"queue",r=ot._data(e,t),i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};"inprogress"===n&&(n=i.shift(),r--),n&&("fx"===t&&i.unshift("inprogress"),delete o.stop,n.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue"),ot._removeData(e,i)})})}}),ot.fn.extend({queue:function(e,t){var i=2;return"string"!=typeof e&&(t=e,e="fx",i--),arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e),"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)i=ot._data(o[s],e+"queueHooks"),i&&i.empty&&(r++,i.empty.add(a));return a(),n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){return e=t||e,"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r&&(n=!0,ot.isFunction(r)||(s=!0),u&&(s?(t.call(e,r),t=null):(u=t,t=function(e,t,i){return u.call(ot(e),i)})),t))for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)));return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;!function(){var e=ft.createElement("input"),t=ft.createElement("div"),i=ft.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",rt.leadingWhitespace=3===t.firstChild.nodeType,rt.tbody=!t.getElementsByTagName("tbody").length,rt.htmlSerialize=!!t.getElementsByTagName("link").length,rt.html5Clone="<:nav></:nav>"!==ft.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,i.appendChild(e),rt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,i.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,rt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){rt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}}(),function(){var e,i,r=ft.createElement("div");for(e in{submit:!0,change:!0,focusin:!0})i="on"+e,(rt[e+"Bubbles"]=i in t)||(r.setAttribute(i,"t"),rt[e+"Bubbles"]=r.attributes[i].expando===!1);r=null}();var Dt=/^(?:input|select|textarea)$/i,_t=/^key/,Mt=/^(?:mouse|pointer|contextmenu)|click/,wt=/^(?:focusinfocus|focusoutblur)$/,Gt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,E,h,f,m=ot._data(e);if(m){for(i.handler&&(l=i,i=l.handler,n=l.selector),i.guid||(i.guid=ot.guid++),(s=m.events)||(s=m.events={}),(p=m.handle)||(p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)},p.elem=e),t=(t||"").match(Nt)||[""],a=t.length;a--;)o=Gt.exec(t[a])||[],E=f=o[1],h=(o[2]||"").split(".").sort(),E&&(u=ot.event.special[E]||{},E=(n?u.delegateType:u.bindType)||E,u=ot.event.special[E]||{},c=ot.extend({type:E,origType:f,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l),(d=s[E])||(d=s[E]=[],d.delegateCount=0,u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(E,p,!1):e.attachEvent&&e.attachEvent("on"+E,p))),u.add&&(u.add.call(e,c),c.handler.guid||(c.handler.guid=i.guid)),n?d.splice(d.delegateCount++,0,c):d.push(c),ot.event.global[E]=!0);
e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,E,h,f,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){for(t=(t||"").match(Nt)||[""],u=t.length;u--;)if(a=Gt.exec(t[u])||[],E=f=a[1],h=(a[2]||"").split(".").sort(),E){for(c=ot.event.special[E]||{},E=(r?c.delegateType:c.bindType)||E,d=p[E]||[],a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;o--;)s=d[o],!n&&f!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector)||(d.splice(o,1),s.selector&&d.delegateCount--,c.remove&&c.remove.call(e,s));l&&!d.length&&(c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,E,m.handle),delete p[E])}else for(E in p)ot.event.remove(e,E+t[u],i,r,!0);ot.isEmptyObject(p)&&(delete m.handle,ot._removeData(e,"events"))}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||ft],E=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];if(a=p=r=r||ft,3!==r.nodeType&&8!==r.nodeType&&!wt.test(E+ot.event.triggered)&&(E.indexOf(".")>=0&&(h=E.split("."),E=h.shift(),h.sort()),s=E.indexOf(":")<0&&"on"+E,e=e[ot.expando]?e:new ot.Event(E,"object"==typeof e&&e),e.isTrigger=n?2:3,e.namespace=h.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),i=null==i?[e]:ot.makeArray(i,[e]),u=ot.event.special[E]||{},n||!u.trigger||u.trigger.apply(r,i)!==!1)){if(!n&&!u.noBubble&&!ot.isWindow(r)){for(l=u.delegateType||E,wt.test(l+E)||(a=a.parentNode);a;a=a.parentNode)d.push(a),p=a;p===(r.ownerDocument||ft)&&d.push(p.defaultView||p.parentWindow||t)}for(c=0;(a=d[c++])&&!e.isPropagationStopped();)e.type=c>1?l:u.bindType||E,o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle"),o&&o.apply(a,i),o=s&&a[s],o&&o.apply&&ot.acceptData(a)&&(e.result=o.apply(a,i),e.result===!1&&e.preventDefault());if(e.type=E,!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[E]&&!ot.isWindow(r)){p=r[s],p&&(r[s]=null),ot.event.triggered=E;try{r[E]()}catch(f){}ot.event.triggered=void 0,p&&(r[s]=p)}return e.result}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=ot.event.handlers.call(this,e,l),t=0;(n=s[t++])&&!e.isPropagationStopped();)for(e.currentTarget=n.elem,o=0;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a),void 0!==i&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(n=[],o=0;a>o;o++)r=t[o],i=r.selector+" ",void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length),n[i]&&n.push(r);n.length&&s.push({elem:l,handlers:n})}return a<t.length&&s.push({elem:this,handlers:t.slice(a)}),s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];for(s||(this.fixHooks[n]=s=Mt.test(n)?this.mouseHooks:_t.test(n)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new ot.Event(o),t=r.length;t--;)i=r[t],e[i]=o[i];return e.target||(e.target=o.srcElement||ft),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ft,n=r.documentElement,i=r.body,e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==f()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===f()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n),n.isDefaultPrevented()&&i.preventDefault()}},ot.removeEvent=ft.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;e.detachEvent&&(typeof e[r]===yt&&(e[r]=null),e.detachEvent(r,i))},ot.Event=function(e,t){return this instanceof ot.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?E:h):this.type=e,t&&ot.extend(this,t),this.timeStamp=e&&e.timeStamp||ot.now(),void(this[ot.expando]=!0)):new ot.Event(e,t)},ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=E,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=E,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=E,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;return(!n||n!==r&&!ot.contains(r,n))&&(e.type=o.origType,i=o.handler.apply(this,arguments),e.type=t),i}}}),rt.submitBubbles||(ot.event.special.submit={setup:function(){return ot.nodeName(this,"form")?!1:void ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;i&&!ot._data(i,"submitBubbles")&&(ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0}),ot._data(i,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ot.nodeName(this,"form")?!1:void ot.event.remove(this,"._submit")}}),rt.changeBubbles||(ot.event.special.change={setup:function(){return Dt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ot.event.simulate("change",this,e,!0)})),!1):void ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")&&(ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)}),ot._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ot.event.remove(this,"._change"),!Dt.test(this.nodeName)}}),rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0),ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;n?ot._data(r,t,n):(r.removeEventListener(e,i,!0),ot._removeData(r,t))}}}),ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){"string"!=typeof t&&(i=i||t,t=void 0);for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r?(r=t,i=t=void 0):null==r&&("string"==typeof t?(r=i,i=void 0):(r=i,i=t,t=void 0)),r===!1)r=h;else if(!r)return this;return 1===n&&(s=r,r=function(e){return ot().off(e),s.apply(this,arguments)},r.guid=s.guid||(s.guid=ot.guid++)),this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}return(t===!1||"function"==typeof t)&&(i=t,t=void 0),i===!1&&(i=h),this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var kt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+kt+")[\\s/>]","i"),Vt=/^\s+/,Ht=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ft=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(ft),Zt=Qt.appendChild(ft.createElement("div"));$t.optgroup=$t.option,$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead,$t.th=$t.td,ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Zt.innerHTML=e.outerHTML,Zt.removeChild(o=Zt.firstChild)),!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e)))for(r=g(o),a=g(e),s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s]);if(t)if(i)for(a=a||g(e),r=r||g(o),s=0;null!=(n=a[s]);s++)T(n,r[s]);else T(e,o);return r=g(o,"script"),r.length>0&&I(r,!l&&g(e,"script")),r=a=n=null,o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),E=[],h=0;c>h;h++)if(o=e[h],o||0===o)if("object"===ot.type(o))ot.merge(E,o.nodeType?[o]:o);else if(Wt.test(o)){for(a=a||d.appendChild(t.createElement("div")),l=(Ft.exec(o)||["",""])[1].toLowerCase(),p=$t[l]||$t._default,a.innerHTML=p[1]+o.replace(Ht,"<$1></$2>")+p[2],n=p[0];n--;)a=a.lastChild;if(!rt.leadingWhitespace&&Vt.test(o)&&E.push(t.createTextNode(Vt.exec(o)[0])),!rt.tbody)for(o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild,n=o&&o.childNodes.length;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(ot.merge(E,a.childNodes),a.textContent="";a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else E.push(t.createTextNode(o));for(a&&d.removeChild(a),rt.appendChecked||ot.grep(g(E,"input"),v),h=0;o=E[h++];)if((!r||-1===ot.inArray(o,r))&&(s=ot.contains(o.ownerDocument,o),a=g(d.appendChild(o),"script"),s&&I(a),i))for(n=0;o=a[n++];)Xt.test(o.type||"")&&i.push(o);return a=null,d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if((t||ot.acceptData(i))&&(n=i[a],o=n&&l[n])){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);l[n]&&(delete l[n],u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null,K.push(n))}}}),ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ft).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++)t||1!==i.nodeType||ot.cleanData(g(i)),i.parentNode&&(t&&ot.contains(i.ownerDocument,i)&&I(g(i,"script")),i.parentNode.removeChild(i));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ot.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ft.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ht,"<$1></$2>");try{for(;r>i;i++)t=this[i]||{},1===t.nodeType&&(ot.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ot.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],E=ot.isFunction(d);if(E||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);E&&(e[0]=d.call(this,i,r.html())),r.domManip(e,t)});if(u&&(a=ot.buildFragment(e,this[0].ownerDocument,!1,this),i=a.firstChild,1===a.childNodes.length&&(a=i),i)){for(o=ot.map(g(a,"script"),N),n=o.length;u>l;l++)r=a,l!==c&&(r=ot.clone(r,!0,!0),n&&ot.merge(o,g(r,"script"))),t.call(this[l],r,l);if(n)for(s=o[o.length-1].ownerDocument,ot.map(o,L),l=0;n>l;l++)r=o[l],Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")));a=i=null}return this}}),ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++)i=r===s?this:this.clone(!0),ot(o[r])[t](i),Z.apply(n,i.get());return this.pushStack(n)}});var Jt,ei={};!function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;return i=ft.getElementsByTagName("body")[0],i&&i.style?(t=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(t),typeof t.style.zoom!==yt&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ft.createElement("div")).style.width="5px",e=3!==t.offsetWidth),i.removeChild(r),e):void 0}}();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;t.getComputedStyle?(ti=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},ii=function(e,t,i){var r,n,o,s,a=e.style;return i=i||ti(e),s=i?i.getPropertyValue(t)||i[t]:void 0,i&&(""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t)),ni.test(s)&&ri.test(t)&&(r=a.width,n=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=s,s=i.width,a.width=r,a.minWidth=n,a.maxWidth=o)),void 0===s?s:s+""}):ft.documentElement.currentStyle&&(ti=function(e){return e.currentStyle},ii=function(e,t,i){var r,n,o,s,a=e.style;return i=i||ti(e),s=i?i[t]:void 0,null==s&&a&&a[t]&&(s=a[t]),ni.test(s)&&!oi.test(t)&&(r=a.left,n=e.runtimeStyle,o=n&&n.left,o&&(n.left=e.currentStyle.left),a.left="fontSize"===t?"1em":s,s=a.pixelLeft+"px",a.left=r,o&&(n.left=o)),void 0===s?s:s+""||"auto"}),function(){function e(){var e,i,r,n;i=ft.getElementsByTagName("body")[0],i&&i.style&&(e=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(e),e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=s=!1,l=!0,t.getComputedStyle&&(o="1%"!==(t.getComputedStyle(e,null)||{}).top,s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width,n=e.appendChild(ft.createElement("div")),n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",n.style.marginRight=n.style.width="0",e.style.width="1px",l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight)),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",n=e.getElementsByTagName("td"),n[0].style.cssText="margin:0;border:0;padding:0;display:none",a=0===n[0].offsetHeight,a&&(n[0].style.display="",n[1].style.display="none",a=0===n[0].offsetHeight),i.removeChild(r))}var i,r,n,o,s,a,l;i=ft.createElement("div"),i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=i.getElementsByTagName("a")[0],r=n&&n.style,r&&(r.cssText="float:left;opacity:.5",rt.opacity="0.5"===r.opacity,rt.cssFloat=!!r.cssFloat,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",rt.clearCloneStyle="content-box"===i.style.backgroundClip,rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ot.extend(rt,{reliableHiddenOffsets:function(){return null==a&&e(),a},boxSizingReliable:function(){return null==s&&e(),s},pixelPosition:function(){return null==o&&e(),o},reliableMarginRight:function(){return null==l&&e(),l}}))}(),ot.swap=function(e,t,i,r){var n,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},Ei=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;if(t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a)),s=ot.cssHooks[t]||ot.cssHooks[a],void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];if(o=typeof i,"string"===o&&(n=pi.exec(i))&&(i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t)),o="number"),null!=i&&i===i&&("number"!==o||ot.cssNumber[a]||(i+="px"),rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit"),!(s&&"set"in s&&void 0===(i=s.set(e,i,r)))))try{l[t]=i}catch(u){}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);return t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a)),s=ot.cssHooks[t]||ot.cssHooks[a],s&&"get"in s&&(o=s.get(e,!0,i)),void 0===o&&(o=ii(e,t,r)),"normal"===o&&t in di&&(o=di[t]),""===i||i?(n=parseFloat(o),i===!0||ot.isNumeric(n)?n||0:o):o}}),ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}}),rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1,(t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute&&(i.removeAttribute("filter"),""===t||r&&!r.filter)||(i.filter=si.test(o)?o.replace(si,n):o+" "+n)}}),ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0}),ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}},ri.test(e)||(ot.cssHooks[e+t].set=O)}),ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){for(r=ti(e),n=t.length;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}}),ot.Tween=_,_.prototype={constructor:_,init:function(e,t,i,r,n,o){this.elem=e,this.prop=i,this.easing=n||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=_.propHooks[this.prop];return e&&e.get?e.get(this):_.propHooks._default.get(this)},run:function(e){var t,i=_.propHooks[this.prop];return this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),i&&i.set?i.set(this):_.propHooks._default.set(this),this}},_.prototype.init.prototype=_.prototype,_.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ot.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},_.propHooks.scrollTop=_.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ot.fx=_.prototype.init,ot.fx.step={};var hi,fi,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[k],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3],n=n||[],s=+r||1;do a=a||".5",s/=a,ot.style(i.elem,e,s+o);while(a!==(a=i.cur()/r)&&1!==a&&--l)}return n&&(s=i.start=+s||+r||0,i.unit=o,i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]),i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){ot.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++)i=e[r],Ni[i]=Ni[i]||[],Ni[i].unshift(t)},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}}),ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};return r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ot.isFunction(r.old)&&r.old.call(this),r.queue&&ot.dequeue(this,r.queue)},r},ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};return s.finish=s,n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop,t(i)};return"string"!=typeof e&&(i=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(i),t=!1,o.splice(n,1));(t||!i)&&ot.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;for(i.finish=!0,ot.queue(this,e,[]),n&&n.stop&&n.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}}),ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(w(t,!0),e,r,n)}}),ot.each({slideDown:w("show"),slideUp:w("hide"),slideToggle:w("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}}),ot.timers=[],ot.fx.tick=function(){var e,t=ot.timers,i=0;for(hi=ot.now();i<t.length;i++)e=t[i],e()||t[i]!==e||t.splice(i--,1);t.length||ot.fx.stop(),hi=void 0},ot.fx.timer=function(e){ot.timers.push(e),e()?ot.fx.start():ot.timers.pop()},ot.fx.interval=13,ot.fx.start=function(){fi||(fi=setInterval(ot.fx.tick,ot.fx.interval))},ot.fx.stop=function(){clearInterval(fi),fi=null},ot.fx.speeds={slow:600,fast:200,_default:400},ot.fn.delay=function(e,t){return e=ot.fx?ot.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})},function(){var e,t,i,r,n;t=ft.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],i=ft.createElement("select"),n=i.appendChild(ft.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",rt.getSetAttribute="t"!==t.className,rt.style=/top/.test(r.getAttribute("style")),rt.hrefNormalized="/a"===r.getAttribute("href"),rt.checkOn=!!e.value,rt.optSelected=n.selected,rt.enctype=!!ft.createElement("form").enctype,i.disabled=!0,rt.optDisabled=!n.disabled,e=ft.createElement("input"),e.setAttribute("value",""),rt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),rt.radioValue="t"===e.value}();var Li=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];{if(arguments.length)return r=ot.isFunction(e),this.each(function(i){var n;1===this.nodeType&&(n=r?e.call(this,i,ot(this).val()):e,null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""})),t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n))});if(n)return t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(i=t.get(n,"value"))?i:(i=n.value,"string"==typeof i?i.replace(Li,""):null==i?"":i)}}}),ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++)if(i=r[l],!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){if(t=ot(i).val(),o)return t;s.push(t)}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;)if(r=n[s],ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1;return i||(e.selectedIndex=-1),n}}}}),ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}},rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Ii,Ti,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}}),ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===yt?ot.prop(e,t,i):(1===o&&ot.isXMLDoc(e)||(t=t.toLowerCase(),r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ti:Ii)),void 0===i?r&&"get"in r&&null!==(n=r.get(e,t))?n:(n=ot.find.attr(e,t),null==n?void 0:n):null!==i?r&&"set"in r&&void 0!==(n=r.set(e,i,t))?n:(e.setAttribute(t,i+""),i):void ot.removeAttr(e,t))},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];)r=ot.propFix[i]||i,ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,""),e.removeAttribute(Si?i:r)},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;return e.setAttribute("type",t),i&&(e.value=i),t}}}}}),Ti={set:function(e,t,i){return t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0,i}},ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;return r||(o=yi[t],yi[t]=n,n=null!=i(e,t,r)?t.toLowerCase():null,yi[t]=o),n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}}),Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){return ot.nodeName(e,"input")?void(e.defaultValue=t):Ii&&Ii.set(e,t,i)}}),Si||(Ii={set:function(e,t,i){var r=e.getAttributeNode(i);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i)),r.value=t+="","value"===i||t===e.getAttribute(i)?t:void 0}},yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Ii.set},ot.attrHooks.contenteditable={set:function(e,t,i){Ii.set(e,""===t?!1:t,i)}},ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){return""===i?(e.setAttribute(t,"auto"),i):void 0}}})),rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ot.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]
}catch(t){}})}}),ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!ot.isXMLDoc(e),o&&(t=ot.propFix[t]||t,n=ot.propHooks[t]),void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}}),rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this}),rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(Nt)||[];l>a;a++)if(i=this[a],r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ")){for(o=0;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r),i.className!==s&&(i.className=s)}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(Nt)||[];l>a;a++)if(i=this[a],r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"")){for(o=0;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"",i.className!==s&&(i.className=s)}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else(i===yt||"boolean"===i)&&(this.className&&ot._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ot._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}}),ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}}),ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,_i=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(_i,function(e,t,n,o){return i&&t&&(r=0),0===r?e:(i=n||t,r+=!o-!n,"")}))?Function("return "+n)():ot.error("Invalid JSON: "+e)},ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{t.DOMParser?(r=new DOMParser,i=r.parseFromString(e,"text/xml")):(i=new ActiveXObject("Microsoft.XMLDOM"),i.async="false",i.loadXML(e))}catch(n){i=void 0}return i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e),i};var Mi,wi,Gi=/#.*$/,ki=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Hi=/^\/\//,Fi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{wi=location.href}catch(zi){wi=ft.createElement("a"),wi.href="",wi=wi.href}Mi=Fi.exec(wi.toLowerCase())||[],ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:wi,type:"GET",isLocal:Ui.test(Mi[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?F(F(e,ot.ajaxSettings),t):F(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,I=t;2!==x&&(x=2,a&&clearTimeout(a),u=void 0,s=r||"",L.readyState=e>0?4:0,n=e>=200&&300>e||304===e,i&&(v=j(c,L,i)),v=W(c,v,L,n),n?(c.ifModified&&(N=L.getResponseHeader("Last-Modified"),N&&(ot.lastModified[o]=N),N=L.getResponseHeader("etag"),N&&(ot.etag[o]=N)),204===e||"HEAD"===c.type?I="nocontent":304===e?I="notmodified":(I=v.state,p=v.data,g=v.error,n=!g)):(g=I,(e||!I)&&(I="error",0>e&&(e=0))),L.status=e,L.statusText=(t||I)+"",n?h.resolveWith(d,[p,I,L]):h.rejectWith(d,[L,I,g]),L.statusCode(m),m=void 0,l&&E.trigger(n?"ajaxSuccess":"ajaxError",[L,c,n?p:g]),f.fireWith(d,[L,I]),l&&(E.trigger("ajaxComplete",[L,c]),--ot.active||ot.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,E=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),f=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",L={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p)for(p={};t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2];t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();return x||(e=v[i]=v[i]||e,g[e]=t),this},overrideMimeType:function(e){return x||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else L.always(e[L.status]);return this},abort:function(e){var t=e||N;return u&&u.abort(t),i(0,t),this}};if(h.promise(L).complete=f.add,L.success=L.done,L.error=L.fail,c.url=((e||c.url||wi)+"").replace(Gi,"").replace(Hi,Mi[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""],null==c.crossDomain&&(r=Fi.exec(c.url.toLowerCase()),c.crossDomain=!(!r||r[1]===Mi[1]&&r[2]===Mi[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Mi[3]||("http:"===Mi[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional)),H(ji,c,t,L),2===x)return L;l=c.global,l&&0===ot.active++&&ot.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Vi.test(c.type),o=c.url,c.hasContent||(c.data&&(o=c.url+=(Di.test(o)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=ki.test(o)?o.replace(ki,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)),c.ifModified&&(ot.lastModified[o]&&L.setRequestHeader("If-Modified-Since",ot.lastModified[o]),ot.etag[o]&&L.setRequestHeader("If-None-Match",ot.etag[o])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&L.setRequestHeader("Content-Type",c.contentType),L.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)L.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,L,c)===!1||2===x))return L.abort();N="abort";for(n in{success:1,error:1,complete:1})L[n](c[n]);if(u=H(Wi,c,t,L)){L.readyState=1,l&&E.trigger("ajaxSend",[L,c]),c.async&&c.timeout>0&&(a=setTimeout(function(){L.abort("timeout")},c.timeout));try{x=1,u.send(g,i)}catch(I){if(!(2>x))throw I;i(-1,I)}}else i(-1,"No Transport");return L},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}}),ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){return ot.isFunction(i)&&(n=n||r,r=i,i=void 0),ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}}),ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}}),ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}}),ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))},ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional),ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")},ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}}),ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.ActiveXObject&&ot(t).on("unload",function(){for(var e in Ji)Ji[e](void 0,!0)}),rt.cors=!!er&&"withCredentials"in er,er=rt.ajax=!!er,er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null),t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState))if(delete Ji[s],t=void 0,o.onreadystatechange=ot.noop,n)4!==o.readyState&&o.abort();else{u={},a=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}u&&r(a,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ot.globalEval(e),e}}}),ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=ft.head||ot("head")[0]||ft.documentElement;return{send:function(r,n){t=ft.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,i){(i||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,i||n(200,"success"))},i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;return this[e]=!0,e}}),ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");return a||"jsonp"===e.dataTypes[0]?(n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n),e.converters["script json"]=function(){return s||ot.error(n+" was not called"),s[0]},e.dataTypes[0]="json",o=t[n],t[n]=function(){s=arguments},r.always(function(){t[n]=o,e[n]&&(e.jsonpCallback=i.jsonpCallback,tr.push(n)),s&&ot.isFunction(o)&&o(s[0]),s=o=void 0}),"script"):void 0}),ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(i=t,t=!1),t=t||ft;var r=dt.exec(e),n=!i&&[];return r?[t.createElement(r[1])]:(r=ot.buildFragment([e],t,n),n&&n.length&&ot(n).remove(),ot.merge([],r.childNodes))};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");return a>=0&&(r=ot.trim(e.slice(a,e.length)),e=e.slice(0,a)),ot.isFunction(t)?(i=t,t=void 0):t&&"object"==typeof t&&(o="POST"),s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments,s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])}),this},ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative"),a=c.offset(),o=ot.css(e,"top"),l=ot.css(e,"left"),u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1,u?(r=c.position(),s=r.top,n=r.left):(s=parseFloat(o)||0,n=parseFloat(l)||0),ot.isFunction(t)&&(t=t.call(e,i,a)),null!=t.top&&(d.top=t.top-a.top+s),null!=t.left&&(d.left=t.left-a.left+n),"using"in t?t.using.call(e,d):c.css(d)}},ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o)return t=o.documentElement,ot.contains(t,n)?(typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect()),i=Y(o),{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];return"fixed"===ot.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ot.nodeName(e[0],"html")||(i=e.offset()),i.top+=ot.css(e[0],"borderTopWidth",!0),i.left+=ot.css(e[0],"borderLeftWidth",!0)),{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}}),ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);return void 0===n?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n)},e,r,arguments.length,null)}}),ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){return i?(i=ii(e,t),ni.test(i)?ot(e).position()[t]+"px":i):void 0})}),ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;return ot.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(n=t.documentElement,Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])):void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})}),ot.fn.size=function(){return this.length},ot.fn.andSelf=ot.fn.addBack,"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;return ot.noConflict=function(e){return t.$===ot&&(t.$=sr),e&&t.jQuery===ot&&(t.jQuery=or),ot},typeof i===yt&&(t.jQuery=t.$=ot),ot})},{}],10:[function(e,t){t.exports=e(9)},{}],11:[function(t,i){!function(t){function r(){try{return u in t&&t[u]}catch(e){return!1}}function n(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(s),c.appendChild(s),s.addBehavior("#default#userData"),s.load(u);var i=e.apply(a,t);return c.removeChild(s),i}}function o(e){return e.replace(/^d/,"___$&").replace(h,"___")}var s,a={},l=t.document,u="localStorage",p="script";if(a.disabled=!1,a.set=function(){},a.get=function(){},a.remove=function(){},a.clear=function(){},a.transact=function(e,t,i){var r=a.get(e);null==i&&(i=t,t=null),"undefined"==typeof r&&(r=t||{}),i(r),a.set(e,r)},a.getAll=function(){},a.forEach=function(){},a.serialize=function(e){return JSON.stringify(e)},a.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},r())s=t[u],a.set=function(e,t){return void 0===t?a.remove(e):(s.setItem(e,a.serialize(t)),t)},a.get=function(e){return a.deserialize(s.getItem(e))},a.remove=function(e){s.removeItem(e)},a.clear=function(){s.clear()},a.getAll=function(){var e={};return a.forEach(function(t,i){e[t]=i}),e},a.forEach=function(e){for(var t=0;t<s.length;t++){var i=s.key(t);e(i,a.get(i))}};else if(l.documentElement.addBehavior){var c,d;try{d=new ActiveXObject("htmlfile"),d.open(),d.write("<"+p+">document.w=window</"+p+'><iframe src="/favicon.ico"></iframe>'),d.close(),c=d.w.frames[0].document,s=c.createElement("div")}catch(E){s=l.createElement("div"),c=l.body}var h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=n(function(e,t,i){return t=o(t),void 0===i?a.remove(t):(e.setAttribute(t,a.serialize(i)),e.save(u),i)}),a.get=n(function(e,t){return t=o(t),a.deserialize(e.getAttribute(t))}),a.remove=n(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),a.clear=n(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(u)}),a.getAll=function(){var e={};return a.forEach(function(t,i){e[t]=i}),e},a.forEach=n(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,a.deserialize(e.getAttribute(i.name)))})}try{var f="__storejs__";a.set(f,f),a.get(f)!=f&&(a.disabled=!0),a.remove(f)}catch(E){a.disabled=!0}a.enabled=!a.disabled,"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=a:"function"==typeof e&&e.amd?e(a):t.store=a}(Function("return this")())},{}],12:[function(e,t){t.exports=function(t){return e("jquery")(t).closest("[id]").attr("id")}},{jquery:10}],13:[function(e,t){var i=e("jquery"),r=t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g id="Layer_1"></g><g id="Layer_2"> <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" ><g id="Layer_1" transform="translate(-2.995,-2.411)" /><g id="Layer_2" transform="translate(-2.995,-2.411)"><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" id="path6" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g3"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 88.184,81.468 c 1.167,1.167 1.167,3.075 0,4.242 l -2.475,2.475 c -1.167,1.167 -3.076,1.167 -4.242,0 l -69.65,-69.65 c -1.167,-1.167 -1.167,-3.076 0,-4.242 l 2.476,-2.476 c 1.167,-1.167 3.076,-1.167 4.242,0 l 69.649,69.651 z" id="path5" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g7"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 18.532,88.184 c -1.167,1.166 -3.076,1.166 -4.242,0 l -2.475,-2.475 c -1.167,-1.166 -1.167,-3.076 0,-4.242 l 69.65,-69.651 c 1.167,-1.167 3.075,-1.167 4.242,0 l 2.476,2.476 c 1.166,1.167 1.166,3.076 0,4.242 l -69.651,69.65 z" id="path9" /></g></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Icons" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path id="ShareThis" d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',draw:function(e,t){if(e){var n=r.getElement(t);
n&&i(e).append(n)}},getElement:function(e){var t=e.id?r[e.id]:e.value;if(t&&0==t.indexOf("<svg")){var n=new DOMParser,o=n.parseFromString(t,"text/xml"),s=o.documentElement,a=i("<div></div>").css("display","inline-block");return e.width||(e.width="100%"),e.height||(e.height="100%"),a.width(e.width).height(e.height),a.append(s)}return!1}}},{jquery:10}],14:[function(e,t){window.console=window.console||{log:function(){}},t.exports={storage:e("./storage.js"),determineId:e("./determineId.js"),imgs:e("./imgs.js")}},{"./determineId.js":12,"./imgs.js":13,"./storage.js":15}],15:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){"string"==typeof n&&(n=r[n]()),i.set(e,{val:t,exp:n,time:(new Date).getTime()})},get:function(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:11}],16:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"1.2.1",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],devDependencies:{gulp:"~3.6.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-uglify":"^0.2.1","gulp-concat":"^2.2.0","gulp-minify-css":"^0.3.0","gulp-browserify":"^0.5.0","vinyl-buffer":"0.0.0",browserify:"^3.38.1",express:"^3.5.1","connect-livereload":"^0.3.2","gulp-livereload":"^1.3.1","gulp-util":"^2.2.14","gulp-connect":"^2.0.5","gulp-notify":"^1.2.5","gulp-embedlr":"^0.5.2","gulp-changed":"^0.3.0","gulp-imagemin":"^0.2.0","gulp-open":"^0.2.8",connect:"^2.14.4","gulp-debug":"^0.3.0",amplify:"0.0.11","twitter-bootstrap-3.0.0":"^3.0.0","gulp-yuidoc":"^0.1.2","gulp-jsvalidate":"^0.2.0"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],homepage:"http://yasgui.github.io/YASQE",maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},readme:"README.md",dependencies:{jquery:"~ 1.11.0",codemirror:"~4.2.0",amplify:"0.0.11",store:"^1.3.14","twitter-bootstrap-3.0.0":"^3.0.0","browserify-shim":"~3.2.0","yasgui-utils":"^1.0.0"},"browserify-shim":{"twitter-bootstrap-3.0.0":"bootstrap"},browserify:{transform:["browserify-shim"]}}},{}],17:[function(e,t){"use strict";function i(e,t,r){var n=e.getTokenAt({line:t,ch:r.start});return null!=n&&"ws"==n.type&&(n=i(e,t,n)),n}var r=e("jquery"),n=e("codemirror");e("codemirror/addon/hint/show-hint.js"),e("codemirror/addon/search/searchcursor.js"),e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/addon/runmode/runmode.js"),window.console=window.console||{log:function(){}},e("../lib/flint.js");var o=e("../lib/trie.js"),s=t.exports=function(e,t){t=a(t);var i=l(n(e,t));return u(i),i},a=function(e){var t=r.extend(!0,{},s.defaults,e);return t},l=function(t){return t.query=function(e){s.executeQuery(t,e)},t.getPrefixesFromQuery=function(){return h(t)},t.storeBulkCompletions=function(i,r){p[i]=new o;for(var n=0;n<r.length;n++)p[i].insert(r[n]);var s=R(t,t.options.autocompletions[i].persistent);s&&e("yasgui-utils").storage.set(s,r,"month")},t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e,x(t)},t},u=function(t){var i=R(t,t.options.persistent);if(i){var r=e("yasgui-utils").storage.get(i);r&&t.setValue(r)}if(s.drawButtons(t),t.on("blur",function(e){s.storeQuery(e)}),t.on("change",function(e){x(e),s.appendPrefixIfNeeded(e),s.updateQueryButton(e),s.positionAbsoluteItems(e)}),t.on("cursorActivity",function(e){s.autoComplete(e,!0)}),t.prevQueryValid=!1,x(t),s.positionAbsoluteItems(t),t.options.autocompletions)for(var n in t.options.autocompletions)t.options.autocompletions[n].bulk&&E(t,n);t.options.consumeShareLink&&t.options.consumeShareLink(t)},p={},c={"string-2":"prefixed",atom:"var"},d=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},E=function(t,i){var r=null;if(d(t.options.autocompletions[i],"get")&&(r=t.options.autocompletions[i].get),r instanceof Array)t.storeBulkCompletions(i,r);else{var n=null;if(R(t,t.options.autocompletions[i].persistent)&&(n=e("yasgui-utils").storage.get(R(t,t.options.autocompletions[i].persistent))),n&&n instanceof Array&&n.length>0)t.storeBulkCompletions(i,n);else if(r instanceof Function){var o=r(t);o&&o instanceof Array&&o.length>0&&t.storeBulkCompletions(i,o)}}},h=function(e){for(var t={},i=e.lineCount(),r=0;i>r;r++){var n=g(e,r);if(null!=n&&"PREFIX"==n.string.toUpperCase()){var o=g(e,r,n.end+1);if(o){var s=g(e,r,o.end+1);if(null!=o&&o.string.length>0&&null!=s&&s.string.length>0){var a=s.string;0==a.indexOf("<")&&(a=a.substring(1)),">"==a.slice(-1)&&(a=a.substring(0,a.length-1)),t[o.string]=a}}}}return t},f=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var s=g(e,o);null==s||"PREFIX"!=s.string&&"BASE"!=s.string||(i=s,r=o)}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var a=m(e,r);e.replaceRange("\n"+a+"PREFIX "+t,{line:r})}},m=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+m(e,t,r.end+1)},g=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?g(e,t,r.end+1):r},v=null,x=function(e,t){e.queryValid=!0,v&&(v(),v=null),e.clearGutter("gutterErrorBar");for(var i=null,n=0;n<e.lineCount();++n){var o=!1;if(e.prevQueryValid||(o=!0),i=e.getTokenAt({line:n,ch:e.getLine(n).length},o).state,0==i.OK){if(!e.options.syntaxErrorCheck)return void r(e.getWrapperElement).find(".sp-error").css("color","black");var s=document.createElement("span");s.innerHTML="→",s.className="gutterError",e.setGutterMarker(n,"gutterErrorBar",s),v=function(){e.markText({line:n,ch:i.errorStartPos},{line:n,ch:i.errorEndPos},"sp-error")},e.queryValid=!1;break}}if(e.prevQueryValid=e.queryValid,t&&null!=i&&void 0!=i.stack){var a=i.stack,l=i.stack.length;l>1?e.queryValid=!1:1==l&&"solutionModifier"!=a[0]&&"?limitOffsetClauses"!=a[0]&&"?offsetClause"!=a[0]&&(e.queryValid=!1)}};r.extend(s,n),s.positionAbsoluteItems=function(e){var t=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),i=0;t.is(":visible")&&(i=t.outerWidth());var n=r(e.getWrapperElement()).find(".completionNotification");n.is(":visible")&&n.css("right",i);var o=r(e.getWrapperElement()).find(".yasqe_buttons");o.is(":visible")&&o.css("right",i)},s.createShareLink=function(e){return{query:e.getValue()}},s.consumeShareLink=function(t){e("../lib/deparam.js");var i=r.deparam(window.location.search.substring(1));i.query&&t.setValue(i.query)},s.drawButtons=function(t){var i=r("<div class='yasqe_buttons'></div>").appendTo(r(t.getWrapperElement()));if(t.options.createShareLink){var n=e("yasgui-utils").imgs.getElement({id:"share",width:"30px",height:"30px"});n.click(function(e){e.stopPropagation();var o=r("<div class='yasqe_sharePopup'></div>").appendTo(i);r("html").click(function(){o&&o.remove()}),o.click(function(e){e.stopPropagation()});var s=r("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+r.param(t.options.createShareLink(t)));s.focus(function(){var e=r(this);e.select(),e.mouseup(function(){return e.unbind("mouseup"),!1})}),o.empty().append(s);var a=n.position();o.css("top",a.top+n.outerHeight()+"px").css("left",a.left+n.outerWidth()-o.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(i)}if(t.options.sparql.showQueryButton){var o=40,a=40;r("<div class='yasqe_queryButton'></div>").click(function(){r(this).hasClass("query_busy")?(t.xhr&&t.xhr.abort(),s.updateQueryButton(t)):t.query()}).height(o).width(a).appendTo(i),s.updateQueryButton(t)}};var N={busy:"loader",valid:"query",error:"queryInvalid"};s.updateQueryButton=function(t,i){var n=r(t.getWrapperElement()).find(".yasqe_queryButton");0!=n.length&&(i||(i="valid",t.queryValid===!1&&(i="error")),i==t.queryStatus||"busy"!=i&&"valid"!=i&&"error"!=i||(n.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+i).append(e("yasgui-utils").imgs.getElement({id:N[i],width:"100%",height:"100%"})),t.queryStatus=i))},s.fromTextArea=function(e,t){t=a(t);var i=l(n.fromTextArea(e,t));return u(i),i},s.fetchFromPrefixCc=function(e){r.get("http://prefix.cc/popular/all.file.json",function(t){var i=[];for(var r in t)if("bif"!=r){var n=r+": <"+t[r]+">";i.push(n)}e.storeBulkCompletions("prefixes",i)})},s.determineId=function(e){return r(e.getWrapperElement()).closest("[id]").attr("id")},s.storeQuery=function(t){var i=R(t,t.options.persistent);i&&e("yasgui-utils").storage.set(i,t.getValue(),"month")},s.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})},s.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}},s.copyLineDown=function(e){s.copyLineUp(e);var t=e.getCursor();t.line++,e.setCursor(t)},s.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};b(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;b(e,{line:0,ch:0},{line:i,ch:r})}},s.executeQuery=function(e,t){var i="function"==typeof t?t:null,n="object"==typeof t?t:{};if(e.options.sparql&&(n=r.extend({},e.options.sparql,n)),n.endpoint&&0!=n.endpoint.length){var o={url:n.endpoint,type:n.requestMethod,data:[{name:"query",value:e.getValue()}],headers:{Accept:n.acceptHeader}},a=!1;if(n.handlers)for(var l in n.handlers)n.handlers[l]&&(a=!0,o[l]=n.handlers[l]);if(a||i){if(i&&(o.complete=i),n.namedGraphs&&n.namedGraphs.length>0)for(var u=0;u<n.namedGraphs.length;u++)o.data.push({name:"named-graph-uri",value:n.namedGraphs[u]});if(n.defaultGraphs&&n.defaultGraphs.length>0)for(var u=0;u<n.defaultGraphs.length;u++)o.data.push({name:"default-graph-uri",value:n.defaultGraphs[u]});n.headers&&!r.isEmptyObject(n.headers)&&r.extend(o.headers,n.headers),n.args&&n.args.length>0&&r.merge(o.data,n.args),s.updateQueryButton(e,"busy");var p=function(){s.updateQueryButton(e)};if(o.complete){var c=o.complete;o.complete=function(e,t){c(e,t),p()}}else o.complete=p();e.xhr=r.ajax(o)}}};var L={};s.showCompletionNotification=function(e,t){e.options.autocompletions[t].autoshow||(L[t]||(L[t]=r("<div class='completionNotification'></div>")),L[t].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(r(e.getWrapperElement())))},s.hideCompletionNotification=function(e,t){L[t]&&L[t].hide()};var I={properties:function(e){var t=T(e);if(0==t.string.indexOf("?"))return!1;if(r.inArray("a",t.state.possibleCurrent)>=0)return!0;var n=e.getCursor(),o=i(e,n.line,t);return"rdfs:subPropertyOf"==o.string?!0:!1},classes:function(e){var t=T(e);if(0==t.string.indexOf("?"))return!1;var r=e.getCursor(),n=i(e,r.line,t);return"a"==n.string?!0:"rdf:type"==n.string?!0:"rdfs:domain"==n.string?!0:"rdfs:range"==n.string?!0:!1},prefixes:function(e){var t=e.getCursor(),i=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;if("ws"!=i.type&&(i=T(e)),0==!i.string.indexOf("a")&&-1==r.inArray("PNAME_NS",i.state.possibleCurrent))return!1;var n=g(e,t.line);return null==n||"PREFIX"!=n.string.toUpperCase()?!1:!0}};s.autoComplete=function(e,t){if(!e.somethingSelected()&&e.options.autocompletions){var i=function(i){if(t&&(!e.options.autocompletions[i].autoShow||e.options.autocompletions[i].async))return!1;var r={closeCharacters:/(?=a)b/,type:i,completeSingle:!1};e.options.autocompletions[i].async&&(r.async=!0);s.showHint(e,C[i],r);return!0};for(var r in e.options.autocompletions)if(I[r](e)){if(!e.options.autocompletions[r].handlers||!e.options.autocompletions[r].handlers.validPosition||e.options.autocompletions[r].handlers.validPosition(e,r)!==!1){var n=i(r);if(n)break}}else e.options.autocompletions[r].handlers&&e.options.autocompletions[r].handlers.invalidPosition&&e.options.autocompletions[r].handlers.invalidPosition(e,r)}},s.appendPrefixIfNeeded=function(e){if(p.prefixes){var t=e.getCursor(),i=e.getTokenAt(t);if("prefixed"==c[i.type]){var r=i.string.indexOf(":");if(-1!==r){var n=g(e,t.line).string.toUpperCase(),o=e.getTokenAt({line:t.line,ch:i.start});if("PREFIX"!=n&&("ws"==o.type||null==o.type)){var s=i.string.substring(0,r+1),a=h(e);if(null==a[s]){var l=p.prefixes.autoComplete(s);l.length>0&&f(e,l[0])}}}}}};var T=function(e,t,i){i||(i=e.getCursor()),t||(t=e.getTokenAt(i));var r=e.getTokenAt({line:i.line,ch:t.start});return null!=r.type&&"ws"!=r.type?(t.start=r.start,t.string=r.string+t.string,T(e,t,{line:i.line,ch:r.start})):t},y=function(e,t){var i=null;if(t.string.indexOf(":")>-1||0==t.string.indexOf("<")){i={},t=T(e,t);var r=h(e);if(0==!t.string.indexOf("<")&&(i.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1),null!=r[i.tokenPrefix]&&(i.tokenPrefixUri=r[i.tokenPrefix])),i.uri=t.string,0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var n in r)if(r.hasOwnProperty(n)&&0==t.string.indexOf(n)){i.uri=r[n],i.uri+=t.string.substring(n.length);break}0==i.uri.indexOf("<")&&(i.uri=i.uri.substring(1)),-1!==i.uri.indexOf(">",i.length-1)&&(i.uri=i.uri.substring(0,i.uri.length-1))}return i},A=function(e,t,i){var r=[];if(p[t])r=p[t].autoComplete(i);else if("function"==typeof e.options.autocompletions[t].get&&0==e.options.autocompletions[t].async)r=e.options.autocompletions[t].get(e,i,t);else if("object"==typeof e.options.autocompletions[t].get)for(var n=i.length,o=0;o<e.options.autocompletions[t].get.length;o++){var s=e.options.autocompletions[t].get[o];s.slice(0,n)==i&&r.push(s)}return r};s.fetchFromLov=function(t,i,n,o){var s=50,a={q:i,page:1};a.type="classes"==n?"class":"property";var l=[],u="",p=function(){u="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+r.param(a)};p();var c=function(){a.page++,p()},d=function(){r.get(u,function(e){for(var t=0;t<e.results.length;t++)l.push(e.results[t].uri);l.length<e.total_results&&l.length<s?(c(),d()):(L[n]&&(l.length>0?L[n].hide():L[n].text("0 matches found...")),o(l))}).fail(function(e,t,i){console.log(i)})};L[n]&&L[n].empty().append(r("<span>Fetchting autocompletions </span>")).append(e("yasgui-utils").imgs.getElement({id:"loader",width:"18px",height:"18px"}).css("vertical-align","middle")),d()};var S=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)},C={};C.resourceHints=function(e,t,i){var r=function(i){for(var r=[],l=0;l<i.length;l++){var u=i[l];null!=a.tokenPrefix&&null!=a.uri?(u=u.substring(a.tokenPrefixUri.length),u=a.tokenPrefix+u):u="<"+u+">",r.push({text:u,displayText:u,hint:S,className:t+"Hint"})}var p={completionToken:a.uri,list:r,from:{line:o.line,ch:n.start},to:{line:o.line,ch:n.end}};if(e.options.autocompletions[t].handlers)for(var c in e.options.autocompletions[t].handlers)e.options.autocompletions[t].handlers[c]&&s.on(p,c,e.options.autocompletions[t].handlers[c]);return p},n=T(e),o=e.getCursor(),a=y(e,n);if(a){if(!e.options.autocompletions[t].async)return r(A(e,t,a.uri));var l=function(e){i(r(e))};e.options.autocompletions[t].get(e,a.uri,t,l)}},C.properties=function(e,t){return C.resourceHints(e,"properties",t)},C.classes=function(e,t){return C.resourceHints(e,"classes",t)},C.prefixes=function(e,t){var i="prefixes",r=T(e),n=e.getCursor(),o=function(){r=/\s*/.test(r.string)&&"PREFIX"==e.getTokenAt({line:n.line,ch:r.start}).string.toUpperCase()?{start:n.ch,end:n.ch,string:"",state:r.state}:T(e,r,n)},a=function(t){var o={completionToken:r.uri,list:t,from:{line:n.line,ch:r.start},to:{line:n.line,ch:r.end}};if(e.options.autocompletions[i].handlers)for(var a in e.options.autocompletions[i].handlers)e.options.autocompletions[i].handlers[a]&&s.on(o,a,e.options.autocompletions[i].handlers[a]);return o};if(o(),r){if(!e.options.autocompletions[i].async)return a(A(e,i,r.string));var l=function(e){t(a(e))};e.options.autocompletions[i].get(e,r.uri,i,l)}};var R=function(e,t){var i=null;return t&&(i="string"==typeof t?t:t(e)),i},b=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=O(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},O=function(e,t,i){e=e.substring(t,i);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=r.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];return n.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);0!=i?(1==i?(u+=e+"\n",p=""):(u+="\n"+e,p=e),c=[]):(p+=e,u+=e),1==c.length&&"sp-ws"==c[0]&&(c=[])}),r.trim(u.replace(/\n\s*\n/g,"\n"))};s.defaults=r.extend(s.defaults,{mode:"sparql11",value:"SELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,gutters:["gutterErrorBar","CodeMirror-linenumbers"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":s.autoComplete,"Cmd-Space":s.autoComplete,"Ctrl-D":s.deleteLine,"Ctrl-K":s.deleteLine,"Cmd-D":s.deleteLine,"Cmd-K":s.deleteLine,"Ctrl-/":s.commentLines,"Cmd-/":s.commentLines,"Ctrl-Alt-Down":s.copyLineDown,"Ctrl-Alt-Up":s.copyLineUp,"Cmd-Alt-Down":s.copyLineDown,"Cmd-Alt-Up":s.copyLineUp,"Shift-Ctrl-F":s.doAutoFormat,"Shift-Cmd-F":s.doAutoFormat,"Ctrl-]":s.indentMore,"Cmd-]":s.indentMore,"Ctrl-[":s.indentLess,"Cmd-[":s.indentLess,"Ctrl-S":s.storeQuery,"Cmd-S":s.storeQuery,"Ctrl-Enter":s.executeQuery,"Cmd-Enter":s.executeQuery},cursorHeight:.9,createShareLink:s.createShareLink,consumeShareLink:s.consumeShareLink,persistent:function(e){return"queryVal_"+s.determineId(e)},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"GET",acceptHeader:"application/sparql-results+json",namedGraphs:[],defaultGraphs:[],args:[],headers:{},handlers:{beforeSend:null,complete:null,error:null,success:null}},autocompletions:{prefixes:{get:s.fetchFromPrefixCc,async:!1,bulk:!0,autoShow:!0,autoAddDeclaration:!0,persistent:"prefixes",handlers:{validPosition:null,invalidPosition:null,shown:null,select:null,pick:null,close:null}},properties:{get:s.fetchFromLov,async:!0,bulk:!1,autoShow:!1,persistent:"properties",handlers:{validPosition:s.showCompletionNotification,invalidPosition:s.hideCompletionNotification,shown:function(){console.log("shown")},select:null,pick:null,close:null}},classes:{get:s.fetchFromLov,async:!0,bulk:!1,autoShow:!1,persistent:"classes",handlers:{validPosition:s.showCompletionNotification,invalidPosition:s.hideCompletionNotification,shown:null,select:null,pick:null,close:null}}}}),s.version={CodeMirror:n.version,YASQE:e("../package.json").version}},{"../lib/deparam.js":1,"../lib/flint.js":2,"../lib/trie.js":3,"../package.json":16,codemirror:8,"codemirror/addon/edit/matchbrackets.js":4,"codemirror/addon/hint/show-hint.js":5,"codemirror/addon/runmode/runmode.js":6,"codemirror/addon/search/searchcursor.js":7,jquery:9,"yasgui-utils":14}]},{},[17])(17)});
|
src/app/components/propertiesOil.js
|
benigeri/soapee-ui
|
import _ from 'lodash';
import React from 'react';
import oilsStore from 'stores/oils';
import calculatorStore from 'stores/calculator';
export default React.createClass( {
shouldComponentUpdate( nextProps ) {
return !( _.isEqual( this.props, nextProps ) );
},
render() {
let oil = this.props.oil;
return (
<div className="properties-oil">
{ oil &&
<div className="properties-container">
<table className="table table-striped table-condensed table-super-condensed">
<tbody>
<tr>
<td>Sap KOH<br />NaOH</td>
<td>{oil.sap}<br />{calculatorStore.sapForNaOh(oil)}</td>
</tr>
<tr>
<td>Iodine</td>
<td>{oil.iodine}</td>
</tr>
<tr>
<td>INS</td>
<td>{oil.ins}</td>
</tr>
{this.gap()}
{this.renderFats()}
{this.gap()}
{this.renderProperties()}
{this.gap()}
{this.renderSaturation()}
</tbody>
</table>
</div>
}
</div>
);
},
gap() {
return (
<tr>
<td colSpan="2"></td>
</tr>
);
},
renderFats() {
let oil = this.props.oil;
return _.transform( oilsStore.getAllFats(), ( output, fat ) => {
let breakdown = oil.breakdown[ fat ];
if ( breakdown ) {
output.push(
<tr>
<td>{_.capitalize(fat)}</td>
<td>{breakdown}%</td>
</tr>
);
}
}, [] );
},
renderProperties() {
let oil = this.props.oil;
function render( property ) {
return (
<tr>
<td>{_.capitalize( property )}</td>
<td>{oil.properties[ property ]}%</td>
</tr>
);
}
return _( oil.properties )
.keys()
.sort()
.map( render, this )
.value();
},
renderSaturation() {
let oil = this.props.oil;
return _.map( oil.saturations, ( satType, saturation ) => {
return (
<tr>
<td>{_.capitalize(saturation)}:</td>
<td>{satType}%</td>
</tr>
);
} );
}
} );
|
src/js/components/icons/base/PlatformOracle.js
|
linde12/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-platform-oracle`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-oracle');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M10.3609792,12.0298215 L11.9468503,12.0298215 L11.1082982,10.6807167 L9.56926613,13.1199573 L8.86882586,13.1199573 L10.7408019,10.1899094 C10.822194,10.0715231 10.9578407,10 11.1082982,10 C11.2538045,10 11.3894535,10.069058 11.4683805,10.1849768 L13.3477542,13.1199573 L12.647312,13.1199573 L12.3168148,12.5748896 L10.7111996,12.5748896 L10.3609792,12.0298215 L10.3609792,12.0298215 Z M17.636774,12.5748896 L17.636774,10.0295965 L17.0423792,10.0295965 L17.0423792,12.8239938 C17.0423792,12.9004515 17.0719808,12.9744417 17.1287027,13.0311675 C17.1854208,13.0878954 17.2618823,13.1199573 17.3457403,13.1199573 L20.056286,13.1199573 L20.4065071,12.5748896 L17.636774,12.5748896 L17.636774,12.5748896 Z M7.80335434,12.1186113 C8.38049377,12.1186113 8.84910424,11.6524682 8.84910424,11.0753366 C8.84910424,10.4982069 8.38049377,10.0295965 7.80335434,10.0295965 L5.20305143,10.0295965 L5.20305143,13.1199573 L5.79721057,13.1199573 L5.79721057,10.5746646 L7.76389083,10.5746646 C8.04013463,10.5746646 8.26210362,10.7991026 8.26210362,11.0753366 C8.26210362,11.3515703 8.04013463,11.5760106 7.76389083,11.5760106 L6.08824577,11.5735432 L7.86253946,13.1199573 L8.7257835,13.1199573 L7.53206103,12.1186113 L7.80335434,12.1186113 L7.80335434,12.1186113 Z M1.5454416,13.1199573 C0.692314677,13.1199573 0,12.4293739 0,11.5760106 C0,10.7226453 0.692314677,10.0295965 1.5454416,10.0295965 L3.34168561,10.0295965 C4.19504894,10.0295965 4.88687091,10.7226453 4.88687091,11.5760106 C4.88687091,12.4293739 4.19504894,13.1199573 3.34168561,13.1199573 L1.5454416,13.1199573 L1.5454416,13.1199573 Z M3.30172939,12.5748896 C3.85445301,12.5748896 4.30209898,12.128476 4.30209898,11.5760106 C4.30209898,11.0235429 3.85445301,10.5746646 3.30172939,10.5746646 L1.58514152,10.5746646 C1.0326742,10.5746646 0.584771536,11.0235429 0.584771536,11.5760106 C0.584771536,12.128476 1.0326742,12.5748896 1.58514152,12.5748896 L3.30172939,12.5748896 L3.30172939,12.5748896 Z M14.5883347,13.1199573 C13.7349694,13.1199573 13.0419276,12.4293739 13.0419276,11.5760106 C13.0419276,10.7226453 13.7349694,10.0295965 14.5883347,10.0295965 L16.721744,10.0295965 L16.3739884,10.5746646 L14.6277982,10.5746646 C14.0753286,10.5746646 13.6264604,11.0235429 13.6264604,11.5760106 C13.6264604,12.128476 14.0753286,12.5748896 14.6277982,12.5748896 L16.7710656,12.5748896 L16.4208484,13.1199573 L14.5883347,13.1199573 L14.5883347,13.1199573 Z M21.8567326,12.5748896 C21.4004484,12.5748896 21.0132293,12.2690591 20.8948388,11.8473098 L23.4352068,11.8473098 L23.7854279,11.3022421 L20.8948388,11.3022421 C21.0132293,10.8829598 21.4004484,10.5746646 21.8567326,10.5746646 L23.6004573,10.5746646 L23.9531439,10.0295965 L21.8172691,10.0295965 C20.9639038,10.0295965 20.270862,10.7226453 20.270862,11.5760106 C20.270862,12.4293739 20.9639038,13.1199573 21.8172691,13.1199573 L23.6497828,13.1199573 L24,12.5748896 L21.8567326,12.5748896 L21.8567326,12.5748896 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'PlatformOracle';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
ajax/libs/analytics.js/2.3.7/analytics.js
|
sashberd/cdnjs
|
(function outer(modules, cache, entries){
/**
* Global
*/
var global = (function(){ return this; })();
/**
* Require `name`.
*
* @param {String} name
* @param {Boolean} jumped
* @api public
*/
function require(name, jumped){
if (cache[name]) return cache[name].exports;
if (modules[name]) return call(name, require);
throw new Error('cannot find module "' + name + '"');
}
/**
* Call module `id` and cache it.
*
* @param {Number} id
* @param {Function} require
* @return {Function}
* @api private
*/
function call(id, require){
var m = cache[id] = { exports: {} };
var mod = modules[id];
var name = mod[2];
var fn = mod[0];
fn.call(m.exports, function(req){
var dep = modules[id][1][req];
return require(dep ? dep : req);
}, m, m.exports, outer, modules, cache, entries);
// expose as `name`.
if (name) cache[name] = cache[id];
return cache[id].exports;
}
/**
* Require all entries exposing them on global if needed.
*/
for (var id in entries) {
if (entries[id]) {
global[entries[id]] = require(id);
} else {
require(id);
}
}
/**
* Duo flag.
*/
require.duo = true;
/**
* Expose cache.
*/
require.cache = cache;
/**
* Expose modules
*/
require.modules = modules;
/**
* Return newest require.
*/
return require;
})({
1: [function(require, module, exports) {
/**
* Analytics.js
*
* (C) 2013 Segment.io Inc.
*/
var Integrations = require('analytics.js-integrations');
var Analytics = require('./analytics');
var each = require('each');
/**
* Expose the `analytics` singleton.
*/
var analytics = module.exports = exports = new Analytics();
/**
* Expose require
*/
analytics.require = require;
/**
* Expose `VERSION`.
*/
exports.VERSION = require('./version');
/**
* Add integrations.
*/
each(Integrations, function (name, Integration) {
analytics.use(Integration);
});
}, {"./analytics":2,"./version":3,"analytics.js-integrations":4,"each":5}],
2: [function(require, module, exports) {
var after = require('after');
var bind = require('bind');
var callback = require('callback');
var canonical = require('canonical');
var clone = require('clone');
var cookie = require('./cookie');
var debug = require('debug');
var defaults = require('defaults');
var each = require('each');
var Emitter = require('emitter');
var group = require('./group');
var is = require('is');
var isEmail = require('is-email');
var isMeta = require('is-meta');
var newDate = require('new-date');
var on = require('event').bind;
var prevent = require('prevent');
var querystring = require('querystring');
var size = require('object').length;
var store = require('./store');
var url = require('url');
var user = require('./user');
var Facade = require('facade');
var Identify = Facade.Identify;
var Group = Facade.Group;
var Alias = Facade.Alias;
var Track = Facade.Track;
var Page = Facade.Page;
/**
* Expose `Analytics`.
*/
exports = module.exports = Analytics;
/**
* Expose `cookie`
*/
exports.cookie = cookie;
exports.store = store;
/**
* Initialize a new `Analytics` instance.
*/
function Analytics () {
this.Integrations = {};
this._integrations = {};
this._readied = false;
this._timeout = 300;
this._user = user; // BACKWARDS COMPATIBILITY
bind.all(this);
var self = this;
this.on('initialize', function (settings, options) {
if (options.initialPageview) self.page();
});
this.on('initialize', function () {
self._parseQuery();
});
}
/**
* Event Emitter.
*/
Emitter(Analytics.prototype);
/**
* Use a `plugin`.
*
* @param {Function} plugin
* @return {Analytics}
*/
Analytics.prototype.use = function (plugin) {
plugin(this);
return this;
};
/**
* Define a new `Integration`.
*
* @param {Function} Integration
* @return {Analytics}
*/
Analytics.prototype.addIntegration = function (Integration) {
var name = Integration.prototype.name;
if (!name) throw new TypeError('attempted to add an invalid integration');
this.Integrations[name] = Integration;
return this;
};
/**
* Initialize with the given integration `settings` and `options`. Aliased to
* `init` for convenience.
*
* @param {Object} settings
* @param {Object} options (optional)
* @return {Analytics}
*/
Analytics.prototype.init =
Analytics.prototype.initialize = function (settings, options) {
settings = settings || {};
options = options || {};
this._options(options);
this._readied = false;
// clean unknown integrations from settings
var self = this;
each(settings, function (name) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
});
// add integrations
each(settings, function (name, opts) {
var Integration = self.Integrations[name];
var integration = new Integration(clone(opts));
self.add(integration);
});
var integrations = this._integrations;
// load user now that options are set
user.load();
group.load();
// make ready callback
var ready = after(size(integrations), function () {
self._readied = true;
self.emit('ready');
});
// initialize integrations, passing ready
each(integrations, function (name, integration) {
if (options.initialPageview && integration.options.initialPageview === false) {
integration.page = after(2, integration.page);
}
integration.analytics = self;
integration.once('ready', ready);
integration.initialize();
});
// backwards compat with angular plugin.
// TODO: remove
this.initialized = true;
this.emit('initialize', settings, options);
return this;
};
/**
* Add an integration.
*
* @param {Integration} integration
*/
Analytics.prototype.add = function(integration){
this._integrations[integration.name] = integration;
return this;
};
/**
* Identify a user by optional `id` and `traits`.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.identify = function (id, traits, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = user.id();
// clone traits before we manipulate so we don't do anything uncouth, and take
// from `user` so that we carryover anonymous traits
user.identify(id, traits);
id = user.id();
traits = user.traits();
this._invoke('identify', message(Identify, {
options: options,
traits: traits,
userId: id
}));
// emit
this.emit('identify', id, traits, options);
this._callback(fn);
return this;
};
/**
* Return the current user.
*
* @return {Object}
*/
Analytics.prototype.user = function () {
return user;
};
/**
* Identify a group by optional `id` and `traits`. Or, if no arguments are
* supplied, return the current group.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics or Object}
*/
Analytics.prototype.group = function (id, traits, options, fn) {
if (0 === arguments.length) return group;
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = group.id();
// grab from group again to make sure we're taking from the source
group.identify(id, traits);
id = group.id();
traits = group.traits();
this._invoke('group', message(Group, {
options: options,
traits: traits,
groupId: id
}));
this.emit('group', id, traits, options);
this._callback(fn);
return this;
};
/**
* Track an `event` that a user has triggered with optional `properties`.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.track = function (event, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = null, properties = null;
this._invoke('track', message(Track, {
properties: properties,
options: options,
event: event
}));
this.emit('track', event, properties, options);
this._callback(fn);
return this;
};
/**
* Helper method to track an outbound link that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackClick`.
*
* @param {Element or Array} links
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackClick =
Analytics.prototype.trackLink = function (links, event, properties) {
if (!links) return this;
if (is.element(links)) links = [links]; // always arrays, handles jquery
var self = this;
each(links, function (el) {
if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.');
on(el, 'click', function (e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
if (el.href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function () {
window.location.href = el.href;
});
}
});
});
return this;
};
/**
* Helper method to track an outbound form that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackSubmit`.
*
* @param {Element or Array} forms
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackSubmit =
Analytics.prototype.trackForm = function (forms, event, properties) {
if (!forms) return this;
if (is.element(forms)) forms = [forms]; // always arrays, handles jquery
var self = this;
each(forms, function (el) {
if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.');
function handler (e) {
prevent(e);
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
self._callback(function () {
el.submit();
});
}
// support the events happening through jQuery or Zepto instead of through
// the normal DOM API, since `el.submit` doesn't bubble up events...
var $ = window.jQuery || window.Zepto;
if ($) {
$(el).submit(handler);
} else {
on(el, 'submit', handler);
}
});
return this;
};
/**
* Trigger a pageview, labeling the current page with an optional `category`,
* `name` and `properties`.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object or String} properties (or path) (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.page = function (category, name, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = properties = null;
if (is.fn(name)) fn = name, options = properties = name = null;
if (is.object(category)) options = name, properties = category, name = category = null;
if (is.object(name)) options = properties, properties = name, name = null;
if (is.string(category) && !is.string(name)) name = category, category = null;
var defs = {
path: canonicalPath(),
referrer: document.referrer,
title: document.title,
search: location.search
};
if (name) defs.name = name;
if (category) defs.category = category;
properties = clone(properties) || {};
defaults(properties, defs);
properties.url = properties.url || canonicalUrl(properties.search);
this._invoke('page', message(Page, {
properties: properties,
category: category,
options: options,
name: name
}));
this.emit('page', category, name, properties, options);
this._callback(fn);
return this;
};
/**
* BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call.
*
* @param {String} url (optional)
* @param {Object} options (optional)
* @return {Analytics}
* @api private
*/
Analytics.prototype.pageview = function (url, options) {
var properties = {};
if (url) properties.path = url;
this.page(properties);
return this;
};
/**
* Merge two previously unassociated user identities.
*
* @param {String} to
* @param {String} from (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.alias = function (to, from, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(from)) fn = from, options = null, from = null;
if (is.object(from)) options = from, from = null;
this._invoke('alias', message(Alias, {
options: options,
from: from,
to: to
}));
this.emit('alias', to, from, options);
this._callback(fn);
return this;
};
/**
* Register a `fn` to be fired when all the analytics services are ready.
*
* @param {Function} fn
* @return {Analytics}
*/
Analytics.prototype.ready = function (fn) {
if (!is.fn(fn)) return this;
this._readied
? callback.async(fn)
: this.once('ready', fn);
return this;
};
/**
* Set the `timeout` (in milliseconds) used for callbacks.
*
* @param {Number} timeout
*/
Analytics.prototype.timeout = function (timeout) {
this._timeout = timeout;
};
/**
* Enable or disable debug.
*
* @param {String or Boolean} str
*/
Analytics.prototype.debug = function(str){
if (0 == arguments.length || str) {
debug.enable('analytics:' + (str || '*'));
} else {
debug.disable();
}
};
/**
* Apply options.
*
* @param {Object} options
* @return {Analytics}
* @api private
*/
Analytics.prototype._options = function (options) {
options = options || {};
cookie.options(options.cookie);
store.options(options.localStorage);
user.options(options.user);
group.options(options.group);
return this;
};
/**
* Callback a `fn` after our defined timeout period.
*
* @param {Function} fn
* @return {Analytics}
* @api private
*/
Analytics.prototype._callback = function (fn) {
callback.async(fn, this._timeout);
return this;
};
/**
* Call `method` with `facade` on all enabled integrations.
*
* @param {String} method
* @param {Facade} facade
* @return {Analytics}
* @api private
*/
Analytics.prototype._invoke = function (method, facade) {
var options = facade.options();
this.emit('invoke', facade);
each(this._integrations, function (name, integration) {
if (!facade.enabled(name)) return;
integration.invoke.call(integration, method, facade);
});
return this;
};
/**
* Push `args`.
*
* @param {Array} args
* @api private
*/
Analytics.prototype.push = function(args){
var method = args.shift();
if (!this[method]) return;
this[method].apply(this, args);
};
/**
* Parse the query string for callable methods.
*
* @return {Analytics}
* @api private
*/
Analytics.prototype._parseQuery = function () {
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var q = querystring.parse(window.location.search);
if (q.ajs_uid) this.identify(q.ajs_uid);
if (q.ajs_event) this.track(q.ajs_event);
return this;
};
/**
* Return the canonical path for the page.
*
* @return {String}
*/
function canonicalPath () {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
/**
* Return the canonical URL for the page concat the given `search`
* and strip the hash.
*
* @param {String} search
* @return {String}
*/
function canonicalUrl (search) {
var canon = canonical();
if (canon) return ~canon.indexOf('?') ? canon : canon + search;
var url = window.location.href;
var i = url.indexOf('#');
return -1 == i ? url : url.slice(0, i);
}
/**
* Create a new message with `Type` and `msg`
*
* the function will make sure that the `msg.options`
* is merged to `msg` and deletes `msg.options` if it
* has `.context / .timestamp / .integrations`.
*
* Example:
*
* message(Identify, {
* options: { timestamp: Date, context: Object, integrations: Object },
* traits: { trait: true },
* userId: 123
* });
*
* // =>
*
* {
* userId: 123,
* context: Object,
* timestamp: Date,
* integrations: Object
* traits: { trait: true }
* }
*
* @param {Function} Type
* @param {Object} msg
* @return {Facade}
*/
function message(Type, msg){
var ctx = msg.options || {};
if (ctx.timestamp || ctx.integrations || ctx.context) {
msg = defaults(ctx, msg);
delete msg.options;
}
return new Type(msg);
}
}, {"./cookie":6,"./group":7,"./store":8,"./user":9,"after":10,"bind":11,"callback":12,"canonical":13,"clone":14,"debug":15,"defaults":16,"each":5,"emitter":17,"is":18,"is-email":19,"is-meta":20,"new-date":21,"event":22,"prevent":23,"querystring":24,"object":25,"url":26,"facade":27}],
6: [function(require, module, exports) {
var debug = require('debug')('analytics.js:cookie');
var bind = require('bind');
var cookie = require('cookie');
var clone = require('clone');
var defaults = require('defaults');
var json = require('json');
var topDomain = require('top-domain');
/**
* Initialize a new `Cookie` with `options`.
*
* @param {Object} options
*/
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options.
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
var domain = '.' + topDomain(window.location.href);
this._options = defaults(options, {
maxage: 31536000000, // default to a year
path: '/',
domain: domain
});
// http://curl.haxx.se/rfc/cookie_spec.html
// https://publicsuffix.org/list/effective_tld_names.dat
//
// try setting a dummy cookie with the options
// if the cookie isn't set, it probably means
// that the domain is on the public suffix list
// like myapp.herokuapp.com or localhost / ip.
this.set('ajs:test', true);
if (!this.get('ajs:test')) {
debug('fallback to domain=null');
this._options.domain = null;
}
this.remove('ajs:test');
};
/**
* Set a `key` and `value` in our cookie.
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie by `key`.
*
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from our cookie by `key`.
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Expose the cookie singleton.
*/
module.exports = bind.all(new Cookie());
/**
* Expose the `Cookie` constructor.
*/
module.exports.Cookie = Cookie;
}, {"debug":15,"bind":11,"cookie":28,"clone":14,"defaults":16,"json":29,"top-domain":30}],
15: [function(require, module, exports) {
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
}, {"./lib/debug":31,"./debug":32}],
31: [function(require, module, exports) {
/**
* Module dependencies.
*/
var tty = require('tty');
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Enabled debuggers.
*/
var names = []
, skips = [];
(process.env.DEBUG || '')
.split(/[\s,]+/)
.forEach(function(name){
name = name.replace('*', '.*?');
if (name[0] === '-') {
skips.push(new RegExp('^' + name.substr(1) + '$'));
} else {
names.push(new RegExp('^' + name + '$'));
}
});
/**
* Colors.
*/
var colors = [6, 2, 3, 4, 5, 1];
/**
* Previous debug() call.
*/
var prev = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Is stdout a TTY? Colored output is disabled when `true`.
*/
var isatty = tty.isatty(2);
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function color() {
return colors[prevColor++ % colors.length];
}
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
function humanize(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
}
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
function disabled(){}
disabled.enabled = false;
var match = skips.some(function(re){
return re.test(name);
});
if (match) return disabled;
match = names.some(function(re){
return re.test(name);
});
if (!match) return disabled;
var c = color();
function colored(fmt) {
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (prev[name] || curr);
prev[name] = curr;
fmt = ' \u001b[9' + c + 'm' + name + ' '
+ '\u001b[3' + c + 'm\u001b[90m'
+ fmt + '\u001b[3' + c + 'm'
+ ' +' + humanize(ms) + '\u001b[0m';
console.error.apply(this, arguments);
}
function plain(fmt) {
fmt = coerce(fmt);
fmt = new Date().toUTCString()
+ ' ' + name + ' ' + fmt;
console.error.apply(this, arguments);
}
colored.enabled = plain.enabled = true;
return isatty || process.env.DEBUG_COLORS
? colored
: plain;
}
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
}, {}],
32: [function(require, module, exports) {
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
}, {}],
11: [function(require, module, exports) {
try {
var bind = require('bind');
} catch (e) {
var bind = require('bind-component');
}
var bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
}, {"bind":33,"bind-all":34}],
33: [function(require, module, exports) {
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
}, {}],
34: [function(require, module, exports) {
try {
var bind = require('bind');
var type = require('type');
} catch (e) {
var bind = require('bind-component');
var type = require('type-component');
}
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
}, {"bind":33,"type":35}],
35: [function(require, module, exports) {
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Function]': return 'function';
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object String]': return 'string';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val && val.nodeType === 1) return 'element';
if (val === Object(val)) return 'object';
return typeof val;
};
}, {}],
28: [function(require, module, exports) {
/**
* Encode.
*/
var encode = encodeURIComponent;
/**
* Decode.
*/
var decode = decodeURIComponent;
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toGMTString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
}, {}],
14: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
}, {"type":35}],
16: [function(require, module, exports) {
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
}, {}],
29: [function(require, module, exports) {
var json = window.JSON || {};
var stringify = json.stringify;
var parse = json.parse;
module.exports = parse && stringify
? JSON
: require('json-fallback');
}, {"json-fallback":36}],
36: [function(require, module, exports) {
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
(function () {
'use strict';
var JSON = module.exports = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
}, {}],
30: [function(require, module, exports) {
/**
* Module dependencies.
*/
var parse = require('url').parse;
/**
* Expose `domain`
*/
module.exports = domain;
/**
* RegExp
*/
var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;
/**
* Get the top domain.
*
* Official Grammar: http://tools.ietf.org/html/rfc883#page-56
* Look for tlds with up to 2-6 characters.
*
* Example:
*
* domain('http://localhost:3000/baz');
* // => ''
* domain('http://dev:3000/baz');
* // => ''
* domain('http://127.0.0.1:3000/baz');
* // => ''
* domain('http://segment.io/baz');
* // => 'segment.io'
*
* @param {String} url
* @return {String}
* @api public
*/
function domain(url){
var host = parse(url).hostname;
var match = host.match(regexp);
return match ? match[0] : '';
};
}, {"url":26}],
26: [function(require, module, exports) {
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
port: a.port,
hash: a.hash,
hostname: a.hostname,
pathname: a.pathname,
protocol: a.protocol,
search: a.search,
query: a.search.slice(1)
}
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
if (0 == url.indexOf('//')) return true;
if (~url.indexOf('://')) return true;
return false;
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return ! exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname != location.hostname
|| url.port != location.port
|| url.protocol != location.protocol;
};
}, {}],
7: [function(require, module, exports) {
var debug = require('debug')('analytics:group');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
/**
* Group defaults
*/
Group.defaults = {
persist: true,
cookie: {
key: 'ajs_group_id'
},
localStorage: {
key: 'ajs_group_properties'
}
};
/**
* Initialize a new `Group` with `options`.
*
* @param {Object} options
*/
function Group (options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(Group, Entity);
/**
* Expose the group singleton.
*/
module.exports = bind.all(new Group());
/**
* Expose the `Group` constructor.
*/
module.exports.Group = Group;
}, {"./entity":37,"debug":15,"inherit":38,"bind":11}],
37: [function(require, module, exports) {
var traverse = require('isodate-traverse');
var defaults = require('defaults');
var cookie = require('./cookie');
var store = require('./store');
var extend = require('extend');
var clone = require('clone');
/**
* Expose `Entity`
*/
module.exports = Entity;
/**
* Initialize new `Entity` with `options`.
*
* @param {Object} options
*/
function Entity(options){
this.options(options);
}
/**
* Get or set storage `options`.
*
* @param {Object} options
* @property {Object} cookie
* @property {Object} localStorage
* @property {Boolean} persist (default: `true`)
*/
Entity.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, this.defaults || {});
this._options = options;
};
/**
* Get or set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype.id = function (id) {
switch (arguments.length) {
case 0: return this._getId();
case 1: return this._setId(id);
}
};
/**
* Get the entity's id.
*
* @return {String}
*/
Entity.prototype._getId = function () {
var ret = this._options.persist
? cookie.get(this._options.cookie.key)
: this._id;
return ret === undefined ? null : ret;
};
/**
* Set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype._setId = function (id) {
if (this._options.persist) {
cookie.set(this._options.cookie.key, id);
} else {
this._id = id;
}
};
/**
* Get or set the entity's `traits`.
*
* BACKWARDS COMPATIBILITY: aliased to `properties`
*
* @param {Object} traits
*/
Entity.prototype.properties =
Entity.prototype.traits = function (traits) {
switch (arguments.length) {
case 0: return this._getTraits();
case 1: return this._setTraits(traits);
}
};
/**
* Get the entity's traits. Always convert ISO date strings into real dates,
* since they aren't parsed back from local storage.
*
* @return {Object}
*/
Entity.prototype._getTraits = function () {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? traverse(clone(ret)) : {};
};
/**
* Set the entity's `traits`.
*
* @param {Object} traits
*/
Entity.prototype._setTraits = function (traits) {
traits || (traits = {});
if (this._options.persist) {
store.set(this._options.localStorage.key, traits);
} else {
this._traits = traits;
}
};
/**
* Identify the entity with an `id` and `traits`. If we it's the same entity,
* extend the existing `traits` instead of overwriting.
*
* @param {String} id
* @param {Object} traits
*/
Entity.prototype.identify = function (id, traits) {
traits || (traits = {});
var current = this.id();
if (current === null || current === id) traits = extend(this.traits(), traits);
if (id) this.id(id);
this.debug('identify %o, %o', id, traits);
this.traits(traits);
this.save();
};
/**
* Save the entity to local storage and the cookie.
*
* @return {Boolean}
*/
Entity.prototype.save = function () {
if (!this._options.persist) return false;
cookie.set(this._options.cookie.key, this.id());
store.set(this._options.localStorage.key, this.traits());
return true;
};
/**
* Log the entity out, reseting `id` and `traits` to defaults.
*/
Entity.prototype.logout = function () {
this.id(null);
this.traits({});
cookie.remove(this._options.cookie.key);
store.remove(this._options.localStorage.key);
};
/**
* Reset all entity state, logging out and returning options to defaults.
*/
Entity.prototype.reset = function () {
this.logout();
this.options({});
};
/**
* Load saved entity `id` or `traits` from storage.
*/
Entity.prototype.load = function () {
this.id(cookie.get(this._options.cookie.key));
this.traits(store.get(this._options.localStorage.key));
};
}, {"./cookie":6,"./store":8,"isodate-traverse":39,"defaults":16,"extend":40,"clone":14}],
8: [function(require, module, exports) {
var bind = require('bind');
var defaults = require('defaults');
var store = require('store.js');
/**
* Initialize a new `Store` with `options`.
*
* @param {Object} options
*/
function Store (options) {
this.options(options);
}
/**
* Set the `options` for the store.
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Set a `key` and `value` in local storage.
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Get a value from local storage by `key`.
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Remove a value from local storage by `key`.
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Expose the store singleton.
*/
module.exports = bind.all(new Store());
/**
* Expose the `Store` constructor.
*/
module.exports.Store = Store;
}, {"bind":11,"defaults":16,"store.js":41}],
41: [function(require, module, exports) {
var json = require('json')
, store = {}
, win = window
, doc = win.document
, localStorageName = 'localStorage'
, namespace = '__storejs__'
, storage;
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return json.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return json.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
module.exports = store;
}, {"json":29}],
39: [function(require, module, exports) {
var is = require('is');
var isodate = require('isodate');
var each;
try {
each = require('each');
} catch (err) {
each = require('each-component');
}
/**
* Expose `traverse`.
*/
module.exports = traverse;
/**
* Traverse an object or array, and return a clone with all ISO strings parsed
* into Date objects.
*
* @param {Object} obj
* @return {Object}
*/
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) return object(input, strict);
if (is.array(input)) return array(input, strict);
return input;
}
/**
* Object traverser.
*
* @param {Object} obj
* @param {Boolean} strict
* @return {Object}
*/
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
/**
* Array traverser.
*
* @param {Array} arr
* @param {Boolean} strict
* @return {Array}
*/
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
}, {"is":42,"isodate":43,"each":5}],
42: [function(require, module, exports) {
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":44,"type":35,"component-type":35}],
44: [function(require, module, exports) {
/**
* Expose `isEmpty`.
*/
module.exports = isEmpty;
/**
* Has.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Test whether a value is "empty".
*
* @param {Mixed} val
* @return {Boolean}
*/
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
}, {}],
43: [function(require, module, exports) {
/**
* Matcher, slightly modified from:
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*/
var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
/**
* Convert an ISO date string to a date. Fallback to native `Date.parse`.
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*
* @param {String} iso
* @return {Date}
*/
exports.parse = function (iso) {
var numericKeys = [1, 5, 6, 7, 11, 12];
var arr = matcher.exec(iso);
var offset = 0;
// fallback to native parsing
if (!arr) return new Date(iso);
// remove undefined values
for (var i = 0, val; val = numericKeys[i]; i++) {
arr[val] = parseInt(arr[val], 10) || 0;
}
// allow undefined days and months
arr[2] = parseInt(arr[2], 10) || 1;
arr[3] = parseInt(arr[3], 10) || 1;
// month is 0-11
arr[2]--;
// allow abitrary sub-second precision
arr[8] = arr[8]
? (arr[8] + '00').substring(0, 3)
: 0;
// apply timezone if one exists
if (arr[4] == ' ') {
offset = new Date().getTimezoneOffset();
} else if (arr[9] !== 'Z' && arr[10]) {
offset = arr[11] * 60 + arr[12];
if ('+' == arr[10]) offset = 0 - offset;
}
var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);
return new Date(millis);
};
/**
* Checks whether a `string` is an ISO date string. `strict` mode requires that
* the date string at least have a year, month and date.
*
* @param {String} string
* @param {Boolean} strict
* @return {Boolean}
*/
exports.is = function (string, strict) {
if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false;
return matcher.test(string);
};
}, {}],
5: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
}, {"type":35}],
40: [function(require, module, exports) {
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
}, {}],
38: [function(require, module, exports) {
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
}, {}],
9: [function(require, module, exports) {
var debug = require('debug')('analytics:user');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
var cookie = require('./cookie');
/**
* User defaults
*/
User.defaults = {
persist: true,
cookie: {
key: 'ajs_user_id',
oldKey: 'ajs_user'
},
localStorage: {
key: 'ajs_user_traits'
}
};
/**
* Initialize a new `User` with `options`.
*
* @param {Object} options
*/
function User (options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(User, Entity);
/**
* Load saved user `id` or `traits` from storage.
*/
User.prototype.load = function () {
if (this._loadOldCookie()) return;
Entity.prototype.load.call(this);
};
/**
* BACKWARDS COMPATIBILITY: Load the old user from the cookie.
*
* @return {Boolean}
* @api private
*/
User.prototype._loadOldCookie = function () {
var user = cookie.get(this._options.cookie.oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this._options.cookie.oldKey);
return true;
};
/**
* Expose the user singleton.
*/
module.exports = bind.all(new User());
/**
* Expose the `User` constructor.
*/
module.exports.User = User;
}, {"./entity":37,"./cookie":6,"debug":15,"inherit":38,"bind":11}],
10: [function(require, module, exports) {
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
}, {}],
12: [function(require, module, exports) {
var next = require('next-tick');
/**
* Expose `callback`.
*/
module.exports = callback;
/**
* Call an `fn` back synchronously if it exists.
*
* @param {Function} fn
*/
function callback (fn) {
if ('function' === typeof fn) fn();
}
/**
* Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the
* `fn` will be called on next tick.
*
* @param {Function} fn
* @param {Number} wait (optional)
*/
callback.async = function (fn, wait) {
if ('function' !== typeof fn) return;
if (!wait) return next(fn);
setTimeout(fn, wait);
};
/**
* Symmetry.
*/
callback.sync = callback;
}, {"next-tick":45}],
45: [function(require, module, exports) {
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
}, {}],
13: [function(require, module, exports) {
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
}, {}],
17: [function(require, module, exports) {
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
}, {"indexof":46}],
46: [function(require, module, exports) {
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
}, {}],
18: [function(require, module, exports) {
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":44,"type":35,"component-type":35}],
19: [function(require, module, exports) {
/**
* Expose `isEmail`.
*/
module.exports = isEmail;
/**
* Email address matcher.
*/
var matcher = /.+\@.+\..+/;
/**
* Loosely validate an email address.
*
* @param {String} string
* @return {Boolean}
*/
function isEmail (string) {
return matcher.test(string);
}
}, {}],
20: [function(require, module, exports) {
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
}, {}],
21: [function(require, module, exports) {
var is = require('is');
var isodate = require('isodate');
var milliseconds = require('./milliseconds');
var seconds = require('./seconds');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native Date constructor.
*
* @param {Date|String|Number} val
*/
module.exports = function newDate (val) {
if (is.date(val)) return val;
if (is.number(val)) return new Date(toMs(val));
// date strings
if (isodate.is(val)) return isodate.parse(val);
if (milliseconds.is(val)) return milliseconds.parse(val);
if (seconds.is(val)) return seconds.parse(val);
// fallback to Date.parse
return new Date(val);
};
/**
* If the number passed val is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param {Number} num
*/
function toMs (num) {
if (num < 31557600000) return num * 1000;
return num;
}
}, {"./milliseconds":47,"./seconds":48,"is":49,"isodate":43}],
47: [function(require, module, exports) {
/**
* Matcher.
*/
var matcher = /\d{13}/;
/**
* Check whether a string is a millisecond date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a millisecond string to a date.
*
* @param {String} millis
* @return {Date}
*/
exports.parse = function (millis) {
millis = parseInt(millis, 10);
return new Date(millis);
};
}, {}],
48: [function(require, module, exports) {
/**
* Matcher.
*/
var matcher = /\d{10}/;
/**
* Check whether a string is a second date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a second string to a date.
*
* @param {String} seconds
* @return {Date}
*/
exports.parse = function (seconds) {
var millis = parseInt(seconds, 10) * 1000;
return new Date(millis);
};
}, {}],
49: [function(require, module, exports) {
var isEmpty = require('is-empty')
, typeOf = require('type');
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
}, {"is-empty":44,"type":35}],
22: [function(require, module, exports) {
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
}, {}],
23: [function(require, module, exports) {
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
}, {}],
24: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
}, {"trim":50,"type":35}],
50: [function(require, module, exports) {
exports = module.exports = trim;
function trim(str){
if (str.trim) return str.trim();
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
if (str.trimLeft) return str.trimLeft();
return str.replace(/^\s*/, '');
};
exports.right = function(str){
if (str.trimRight) return str.trimRight();
return str.replace(/\s*$/, '');
};
}, {}],
25: [function(require, module, exports) {
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
}, {}],
27: [function(require, module, exports) {
var Facade = require('./facade');
/**
* Expose `Facade` facade.
*/
module.exports = Facade;
/**
* Expose specific-method facades.
*/
Facade.Alias = require('./alias');
Facade.Group = require('./group');
Facade.Identify = require('./identify');
Facade.Track = require('./track');
Facade.Page = require('./page');
Facade.Screen = require('./screen');
}, {"./facade":51,"./alias":52,"./group":53,"./identify":54,"./track":55,"./page":56,"./screen":57}],
51: [function(require, module, exports) {
var clone = require('./utils').clone;
var isEnabled = require('./is-enabled');
var objCase = require('obj-case');
var traverse = require('isodate-traverse');
var newDate = require('new-date');
/**
* Expose `Facade`.
*/
module.exports = Facade;
/**
* Initialize a new `Facade` with an `obj` of arguments.
*
* @param {Object} obj
*/
function Facade (obj) {
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = newDate(obj.timestamp);
this.obj = obj;
}
/**
* Return a proxy function for a `field` that will attempt to first use methods,
* and fallback to accessing the underlying object directly. You can specify
* deeply nested fields too like:
*
* this.proxy('options.Librato');
*
* @param {String} field
*/
Facade.prototype.proxy = function (field) {
var fields = field.split('.');
field = fields.shift();
// Call a function at the beginning to take advantage of facaded fields
var obj = this[field] || this.field(field);
if (!obj) return obj;
if (typeof obj === 'function') obj = obj.call(this) || {};
if (fields.length === 0) return transform(obj);
obj = objCase(obj, fields.join('.'));
return transform(obj);
};
/**
* Directly access a specific `field` from the underlying object, returning a
* clone so outsiders don't mess with stuff.
*
* @param {String} field
* @return {Mixed}
*/
Facade.prototype.field = function (field) {
var obj = this.obj[field];
return transform(obj);
};
/**
* Utility method to always proxy a particular `field`. You can specify deeply
* nested fields too like:
*
* Facade.proxy('options.Librato');
*
* @param {String} field
* @return {Function}
*/
Facade.proxy = function (field) {
return function () {
return this.proxy(field);
};
};
/**
* Utility method to directly access a `field`.
*
* @param {String} field
* @return {Function}
*/
Facade.field = function (field) {
return function () {
return this.field(field);
};
};
/**
* Get the basic json object of this facade.
*
* @return {Object}
*/
Facade.prototype.json = function () {
var ret = clone(this.obj);
if (this.type) ret.type = this.type();
return ret;
};
/**
* Get the options of a call (formerly called "context"). If you pass an
* integration name, it will get the options for that specific integration, or
* undefined if the integration is not enabled.
*
* @param {String} integration (optional)
* @return {Object or Null}
*/
Facade.prototype.context =
Facade.prototype.options = function (integration) {
var options = clone(this.obj.options || this.obj.context) || {};
if (!integration) return clone(options);
if (!this.enabled(integration)) return;
var integrations = this.integrations();
var value = integrations[integration] || objCase(integrations, integration);
if ('boolean' == typeof value) value = {};
return value || {};
};
/**
* Check whether an integration is enabled.
*
* @param {String} integration
* @return {Boolean}
*/
Facade.prototype.enabled = function (integration) {
var allEnabled = this.proxy('options.providers.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all');
if (typeof allEnabled !== 'boolean') allEnabled = true;
var enabled = allEnabled && isEnabled(integration);
var options = this.integrations();
// If the integration is explicitly enabled or disabled, use that
// First, check options.providers for backwards compatibility
if (options.providers && options.providers.hasOwnProperty(integration)) {
enabled = options.providers[integration];
}
// Next, check for the integration's existence in 'options' to enable it.
// If the settings are a boolean, use that, otherwise it should be enabled.
if (options.hasOwnProperty(integration)) {
var settings = options[integration];
if (typeof settings === 'boolean') {
enabled = settings;
} else {
enabled = true;
}
}
return enabled ? true : false;
};
/**
* Get all `integration` options.
*
* @param {String} integration
* @return {Object}
* @api private
*/
Facade.prototype.integrations = function(){
return this.obj.integrations
|| this.proxy('options.providers')
|| this.options();
};
/**
* Check whether the user is active.
*
* @return {Boolean}
*/
Facade.prototype.active = function () {
var active = this.proxy('options.active');
if (active === null || active === undefined) active = true;
return active;
};
/**
* Get `sessionId / anonymousId`.
*
* @return {Mixed}
* @api public
*/
Facade.prototype.sessionId =
Facade.prototype.anonymousId = function(){
return this.field('anonymousId')
|| this.field('sessionId');
};
/**
* Get `groupId` from `context.groupId`.
*
* @return {String}
* @api public
*/
Facade.prototype.groupId = Facade.proxy('options.groupId');
/**
* Get the call's "super properties" which are just traits that have been
* passed in as if from an identify call.
*
* @param {Object} aliases
* @return {Object}
*/
Facade.prototype.traits = function (aliases) {
var ret = this.proxy('options.traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('options.traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Add a convenient way to get the library name and version
*/
Facade.prototype.library = function(){
var library = this.proxy('options.library');
if (!library) return { name: 'unknown', version: null };
if (typeof library === 'string') return { name: library, version: null };
return library;
};
/**
* Setup some basic proxies.
*/
Facade.prototype.userId = Facade.field('userId');
Facade.prototype.channel = Facade.field('channel');
Facade.prototype.timestamp = Facade.field('timestamp');
Facade.prototype.userAgent = Facade.proxy('options.userAgent');
Facade.prototype.ip = Facade.proxy('options.ip');
/**
* Return the cloned and traversed object
*
* @param {Mixed} obj
* @return {Mixed}
*/
function transform(obj){
var cloned = clone(obj);
traverse(cloned);
return cloned;
}
}, {"./utils":58,"./is-enabled":59,"obj-case":60,"isodate-traverse":39,"new-date":21}],
58: [function(require, module, exports) {
/**
* TODO: use component symlink, everywhere ?
*/
try {
exports.inherit = require('inherit');
exports.clone = require('clone');
} catch (e) {
exports.inherit = require('inherit-component');
exports.clone = require('clone-component');
}
}, {"inherit":61,"clone":62}],
61: [function(require, module, exports) {
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
}, {}],
62: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type;
try {
type = require('component-type');
} catch (_) {
type = require('type');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
}, {"component-type":35,"type":35}],
59: [function(require, module, exports) {
/**
* A few integrations are disabled by default. They must be explicitly
* enabled by setting options[Provider] = true.
*/
var disabled = {
Salesforce: true,
Marketo: true
};
/**
* Check whether an integration should be enabled by default.
*
* @param {String} integration
* @return {Boolean}
*/
module.exports = function (integration) {
return ! disabled[integration];
};
}, {}],
60: [function(require, module, exports) {
var Case = require('case');
var identity = function(_){ return _; };
/**
* Cases
*/
var cases = [
identity,
Case.upper,
Case.lower,
Case.snake,
Case.pascal,
Case.camel,
Case.constant,
Case.title,
Case.capital,
Case.sentence
];
/**
* Module exports, export
*/
module.exports = module.exports.find = multiple(find);
/**
* Export the replacement function, return the modified object
*/
module.exports.replace = function (obj, key, val) {
multiple(replace).apply(this, arguments);
return obj;
};
/**
* Export the delete function, return the modified object
*/
module.exports.del = function (obj, key) {
multiple(del).apply(this, arguments);
return obj;
};
/**
* Compose applying the function to a nested key
*/
function multiple (fn) {
return function (obj, key, val) {
var keys = key.split('.');
if (keys.length === 0) return;
while (keys.length > 1) {
key = keys.shift();
obj = find(obj, key);
if (obj === null || obj === undefined) return;
}
key = keys.shift();
return fn(obj, key, val);
};
}
/**
* Find an object by its key
*
* find({ first_name : 'Calvin' }, 'firstName')
*/
function find (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) return obj[cased];
}
}
/**
* Delete a value for a given key
*
* del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }
*/
function del (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) delete obj[cased];
}
return obj;
}
/**
* Replace an objects existing value with a new one
*
* replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
*/
function replace (obj, key, val) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) obj[cased] = val;
}
return obj;
}
}, {"case":63}],
63: [function(require, module, exports) {
var cases = require('./cases');
/**
* Expose `determineCase`.
*/
module.exports = exports = determineCase;
/**
* Determine the case of a `string`.
*
* @param {String} string
* @return {String|Null}
*/
function determineCase (string) {
for (var key in cases) {
if (key == 'none') continue;
var convert = cases[key];
if (convert(string) == string) return key;
}
return null;
}
/**
* Define a case by `name` with a `convert` function.
*
* @param {String} name
* @param {Object} convert
*/
exports.add = function (name, convert) {
exports[name] = cases[name] = convert;
};
/**
* Add all the `cases`.
*/
for (var key in cases) {
exports.add(key, cases[key]);
}
}, {"./cases":64}],
64: [function(require, module, exports) {
var camel = require('to-camel-case')
, capital = require('to-capital-case')
, constant = require('to-constant-case')
, dot = require('to-dot-case')
, none = require('to-no-case')
, pascal = require('to-pascal-case')
, sentence = require('to-sentence-case')
, slug = require('to-slug-case')
, snake = require('to-snake-case')
, space = require('to-space-case')
, title = require('to-title-case');
/**
* Camel.
*/
exports.camel = camel;
/**
* Pascal.
*/
exports.pascal = pascal;
/**
* Dot. Should precede lowercase.
*/
exports.dot = dot;
/**
* Slug. Should precede lowercase.
*/
exports.slug = slug;
/**
* Snake. Should precede lowercase.
*/
exports.snake = snake;
/**
* Space. Should precede lowercase.
*/
exports.space = space;
/**
* Constant. Should precede uppercase.
*/
exports.constant = constant;
/**
* Capital. Should precede sentence and title.
*/
exports.capital = capital;
/**
* Title.
*/
exports.title = title;
/**
* Sentence.
*/
exports.sentence = sentence;
/**
* Convert a `string` to lower case from camel, slug, etc. Different that the
* usual `toLowerCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.lower = function (string) {
return none(string).toLowerCase();
};
/**
* Convert a `string` to upper case from camel, slug, etc. Different that the
* usual `toUpperCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.upper = function (string) {
return none(string).toUpperCase();
};
/**
* Invert each character in a `string` from upper to lower and vice versa.
*
* @param {String} string
* @return {String}
*/
exports.inverse = function (string) {
for (var i = 0, char; char = string[i]; i++) {
if (!/[a-z]/i.test(char)) continue;
var upper = char.toUpperCase();
var lower = char.toLowerCase();
string[i] = char == upper ? lower : upper;
}
return string;
};
/**
* None.
*/
exports.none = none;
}, {"to-camel-case":65,"to-capital-case":66,"to-constant-case":67,"to-dot-case":68,"to-no-case":69,"to-pascal-case":70,"to-sentence-case":71,"to-slug-case":72,"to-snake-case":73,"to-space-case":74,"to-title-case":75}],
65: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toCamelCase`.
*/
module.exports = toCamelCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
}, {"to-space-case":74}],
74: [function(require, module, exports) {
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
}, {"to-no-case":69}],
69: [function(require, module, exports) {
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasCamel = /[a-z][A-Z]/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) string = unseparate(string);
if (hasCamel.test(string)) string = uncamelize(string);
return string.toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
}, {}],
66: [function(require, module, exports) {
var clean = require('to-no-case');
/**
* Expose `toCapitalCase`.
*/
module.exports = toCapitalCase;
/**
* Convert a `string` to capital case.
*
* @param {String} string
* @return {String}
*/
function toCapitalCase (string) {
return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) {
return previous + letter.toUpperCase();
});
}
}, {"to-no-case":69}],
67: [function(require, module, exports) {
var snake = require('to-snake-case');
/**
* Expose `toConstantCase`.
*/
module.exports = toConstantCase;
/**
* Convert a `string` to constant case.
*
* @param {String} string
* @return {String}
*/
function toConstantCase (string) {
return snake(string).toUpperCase();
}
}, {"to-snake-case":73}],
73: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
}, {"to-space-case":74}],
68: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toDotCase`.
*/
module.exports = toDotCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toDotCase (string) {
return toSpace(string).replace(/\s/g, '.');
}
}, {"to-space-case":74}],
70: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toPascalCase`.
*/
module.exports = toPascalCase;
/**
* Convert a `string` to pascal case.
*
* @param {String} string
* @return {String}
*/
function toPascalCase (string) {
return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
}, {"to-space-case":74}],
71: [function(require, module, exports) {
var clean = require('to-no-case');
/**
* Expose `toSentenceCase`.
*/
module.exports = toSentenceCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toSentenceCase (string) {
return clean(string).replace(/[a-z]/i, function (letter) {
return letter.toUpperCase();
});
}
}, {"to-no-case":69}],
72: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toSlugCase`.
*/
module.exports = toSlugCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toSlugCase (string) {
return toSpace(string).replace(/\s/g, '-');
}
}, {"to-space-case":74}],
75: [function(require, module, exports) {
var capital = require('to-capital-case')
, escape = require('escape-regexp')
, map = require('map')
, minors = require('title-case-minors');
/**
* Expose `toTitleCase`.
*/
module.exports = toTitleCase;
/**
* Minors.
*/
var escaped = map(minors, escape);
var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig');
var colonMatcher = /:\s*(\w)/g;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toTitleCase (string) {
return capital(string)
.replace(minorMatcher, function (minor) {
return minor.toLowerCase();
})
.replace(colonMatcher, function (letter) {
return letter.toUpperCase();
});
}
}, {"to-capital-case":66,"escape-regexp":76,"map":77,"title-case-minors":78}],
76: [function(require, module, exports) {
/**
* Escape regexp special characters in `str`.
*
* @param {String} str
* @return {String}
* @api public
*/
module.exports = function(str){
return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
};
}, {}],
77: [function(require, module, exports) {
var each = require('each');
/**
* Map an array or object.
*
* @param {Array|Object} obj
* @param {Function} iterator
* @return {Mixed}
*/
module.exports = function map (obj, iterator) {
var arr = [];
each(obj, function (o) {
arr.push(iterator.apply(null, arguments));
});
return arr;
};
}, {"each":79}],
79: [function(require, module, exports) {
/**
* Module dependencies.
*/
try {
var type = require('type');
} catch (err) {
var type = require('component-type');
}
var toFunction = require('to-function');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`
* in optional context `ctx`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @param {Object} [ctx]
* @api public
*/
module.exports = function(obj, fn, ctx){
fn = toFunction(fn);
ctx = ctx || this;
switch (type(obj)) {
case 'array':
return array(obj, fn, ctx);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn, ctx);
return object(obj, fn, ctx);
case 'string':
return string(obj, fn, ctx);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function string(obj, fn, ctx) {
for (var i = 0; i < obj.length; ++i) {
fn.call(ctx, obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function object(obj, fn, ctx) {
for (var key in obj) {
if (has.call(obj, key)) {
fn.call(ctx, key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @param {Object} ctx
* @api private
*/
function array(obj, fn, ctx) {
for (var i = 0; i < obj.length; ++i) {
fn.call(ctx, obj[i], i);
}
}
}, {"type":35,"component-type":35,"to-function":80}],
80: [function(require, module, exports) {
/**
* Module Dependencies
*/
var expr;
try {
expr = require('props');
} catch(e) {
expr = require('component-props');
}
/**
* Expose `toFunction()`.
*/
module.exports = toFunction;
/**
* Convert `obj` to a `Function`.
*
* @param {Mixed} obj
* @return {Function}
* @api private
*/
function toFunction(obj) {
switch ({}.toString.call(obj)) {
case '[object Object]':
return objectToFunction(obj);
case '[object Function]':
return obj;
case '[object String]':
return stringToFunction(obj);
case '[object RegExp]':
return regexpToFunction(obj);
default:
return defaultToFunction(obj);
}
}
/**
* Default to strict equality.
*
* @param {Mixed} val
* @return {Function}
* @api private
*/
function defaultToFunction(val) {
return function(obj){
return val === obj;
};
}
/**
* Convert `re` to a function.
*
* @param {RegExp} re
* @return {Function}
* @api private
*/
function regexpToFunction(re) {
return function(obj){
return re.test(obj);
};
}
/**
* Convert property `str` to a function.
*
* @param {String} str
* @return {Function}
* @api private
*/
function stringToFunction(str) {
// immediate such as "> 20"
if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str);
// properties such as "name.first" or "age > 18" or "age > 18 && age < 36"
return new Function('_', 'return ' + get(str));
}
/**
* Convert `object` to a function.
*
* @param {Object} object
* @return {Function}
* @api private
*/
function objectToFunction(obj) {
var match = {};
for (var key in obj) {
match[key] = typeof obj[key] === 'string'
? defaultToFunction(obj[key])
: toFunction(obj[key]);
}
return function(val){
if (typeof val !== 'object') return false;
for (var key in match) {
if (!(key in val)) return false;
if (!match[key](val[key])) return false;
}
return true;
};
}
/**
* Built the getter function. Supports getter style functions
*
* @param {String} str
* @return {String}
* @api private
*/
function get(str) {
var props = expr(str);
if (!props.length) return '_.' + str;
var val, i, prop;
for (i = 0; i < props.length; i++) {
prop = props[i];
val = '_.' + prop;
val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")";
// mimic negative lookbehind to avoid problems with nested properties
str = stripNested(prop, str, val);
}
return str;
}
/**
* Mimic negative lookbehind to avoid problems with nested properties.
*
* See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
*
* @param {String} prop
* @param {String} str
* @param {String} val
* @return {String}
* @api private
*/
function stripNested (prop, str, val) {
return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) {
return $1 ? $0 : val;
});
}
}, {"props":81,"component-props":81}],
81: [function(require, module, exports) {
/**
* Global Names
*/
var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g;
/**
* Return immediate identifiers parsed from `str`.
*
* @param {String} str
* @param {String|Function} map function or prefix
* @return {Array}
* @api public
*/
module.exports = function(str, fn){
var p = unique(props(str));
if (fn && 'string' == typeof fn) fn = prefixed(fn);
if (fn) return map(str, p, fn);
return p;
};
/**
* Return immediate identifiers in `str`.
*
* @param {String} str
* @return {Array}
* @api private
*/
function props(str) {
return str
.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '')
.replace(globals, '')
.match(/[$a-zA-Z_]\w*/g)
|| [];
}
/**
* Return `str` with `props` mapped with `fn`.
*
* @param {String} str
* @param {Array} props
* @param {Function} fn
* @return {String}
* @api private
*/
function map(str, props, fn) {
var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;
return str.replace(re, function(_){
if ('(' == _[_.length - 1]) return fn(_);
if (!~props.indexOf(_)) return _;
return fn(_);
});
}
/**
* Return unique array.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function unique(arr) {
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (~ret.indexOf(arr[i])) continue;
ret.push(arr[i]);
}
return ret;
}
/**
* Map with prefix `str`.
*/
function prefixed(str) {
return function(_){
return str + _;
};
}
}, {}],
78: [function(require, module, exports) {
module.exports = [
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'en',
'for',
'from',
'how',
'if',
'in',
'neither',
'nor',
'of',
'on',
'only',
'onto',
'out',
'or',
'per',
'so',
'than',
'that',
'the',
'to',
'until',
'up',
'upon',
'v',
'v.',
'versus',
'vs',
'vs.',
'via',
'when',
'with',
'without',
'yet'
];
}, {}],
52: [function(require, module, exports) {
/**
* Module dependencies.
*/
var inherit = require('./utils').inherit;
var Facade = require('./facade');
/**
* Expose `Alias` facade.
*/
module.exports = Alias;
/**
* Initialize a new `Alias` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @property {String} from
* @property {String} to
* @property {Object} options
*/
function Alias (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Alias, Facade);
/**
* Return type of facade.
*
* @return {String}
*/
Alias.prototype.type =
Alias.prototype.action = function () {
return 'alias';
};
/**
* Get `previousId`.
*
* @return {Mixed}
* @api public
*/
Alias.prototype.from =
Alias.prototype.previousId = function(){
return this.field('previousId')
|| this.field('from');
};
/**
* Get `userId`.
*
* @return {String}
* @api public
*/
Alias.prototype.to =
Alias.prototype.userId = function(){
return this.field('userId')
|| this.field('to');
};
}, {"./utils":58,"./facade":51}],
53: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var Facade = require('./facade');
var newDate = require('new-date');
/**
* Expose `Group` facade.
*/
module.exports = Group;
/**
* Initialize a new `Group` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} groupId
* @param {Object} properties
* @param {Object} options
*/
function Group (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Group, Facade);
/**
* Get the facade's action.
*/
Group.prototype.type =
Group.prototype.action = function () {
return 'group';
};
/**
* Setup some basic proxies.
*/
Group.prototype.groupId = Facade.field('groupId');
/**
* Get created or createdAt.
*
* @return {Date}
*/
Group.prototype.created = function(){
var created = this.proxy('traits.createdAt')
|| this.proxy('traits.created')
|| this.proxy('properties.createdAt')
|| this.proxy('properties.created');
if (created) return newDate(created);
};
/**
* Get the group's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Group.prototype.traits = function (aliases) {
var ret = this.properties();
var id = this.groupId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get traits or properties.
*
* TODO: remove me
*
* @return {Object}
*/
Group.prototype.properties = function(){
return this.field('traits')
|| this.field('properties')
|| {};
};
}, {"./utils":58,"./facade":51,"new-date":21}],
54: [function(require, module, exports) {
var Facade = require('./facade');
var isEmail = require('is-email');
var newDate = require('new-date');
var utils = require('./utils');
var trim = require('trim');
var inherit = utils.inherit;
var clone = utils.clone;
/**
* Expose `Idenfity` facade.
*/
module.exports = Identify;
/**
* Initialize a new `Identify` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} sessionId
* @param {Object} traits
* @param {Object} options
*/
function Identify (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Identify, Facade);
/**
* Get the facade's action.
*/
Identify.prototype.type =
Identify.prototype.action = function () {
return 'identify';
};
/**
* Get the user's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Identify.prototype.traits = function (aliases) {
var ret = this.field('traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {String}
*/
Identify.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the user's created date, optionally looking for `createdAt` since lots of
* people do that instead.
*
* @return {Date or Undefined}
*/
Identify.prototype.created = function () {
var created = this.proxy('traits.created') || this.proxy('traits.createdAt');
if (created) return newDate(created);
};
/**
* Get the company created date.
*
* @return {Date or undefined}
*/
Identify.prototype.companyCreated = function(){
var created = this.proxy('traits.company.created')
|| this.proxy('traits.company.createdAt');
if (created) return newDate(created);
};
/**
* Get the user's name, optionally combining a first and last name if that's all
* that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.name = function () {
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name);
var firstName = this.firstName();
var lastName = this.lastName();
if (firstName && lastName) return trim(firstName + ' ' + lastName);
};
/**
* Get the user's first name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.firstName = function () {
var firstName = this.proxy('traits.firstName');
if (typeof firstName === 'string') return trim(firstName);
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name).split(' ')[0];
};
/**
* Get the user's last name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.lastName = function () {
var lastName = this.proxy('traits.lastName');
if (typeof lastName === 'string') return trim(lastName);
var name = this.proxy('traits.name');
if (typeof name !== 'string') return;
var space = trim(name).indexOf(' ');
if (space === -1) return;
return trim(name.substr(space + 1));
};
/**
* Get the user's unique id.
*
* @return {String or undefined}
*/
Identify.prototype.uid = function(){
return this.userId()
|| this.username()
|| this.email();
};
/**
* Get description.
*
* @return {String}
*/
Identify.prototype.description = function(){
return this.proxy('traits.description')
|| this.proxy('traits.background');
};
/**
* Setup sme basic "special" trait proxies.
*/
Identify.prototype.username = Facade.proxy('traits.username');
Identify.prototype.website = Facade.proxy('traits.website');
Identify.prototype.phone = Facade.proxy('traits.phone');
Identify.prototype.address = Facade.proxy('traits.address');
Identify.prototype.avatar = Facade.proxy('traits.avatar');
}, {"./facade":51,"./utils":58,"is-email":19,"new-date":21,"trim":50}],
55: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var clone = require('./utils').clone;
var Facade = require('./facade');
var Identify = require('./identify');
var isEmail = require('is-email');
/**
* Expose `Track` facade.
*/
module.exports = Track;
/**
* Initialize a new `Track` facade with a `dictionary` of arguments.
*
* @param {object} dictionary
* @property {String} event
* @property {String} userId
* @property {String} sessionId
* @property {Object} properties
* @property {Object} options
*/
function Track (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Track, Facade);
/**
* Return the facade's action.
*
* @return {String}
*/
Track.prototype.type =
Track.prototype.action = function () {
return 'track';
};
/**
* Setup some basic proxies.
*/
Track.prototype.event = Facade.field('event');
Track.prototype.value = Facade.proxy('properties.value');
/**
* Misc
*/
Track.prototype.category = Facade.proxy('properties.category');
Track.prototype.country = Facade.proxy('properties.country');
Track.prototype.state = Facade.proxy('properties.state');
Track.prototype.city = Facade.proxy('properties.city');
Track.prototype.zip = Facade.proxy('properties.zip');
/**
* Ecommerce
*/
Track.prototype.id = Facade.proxy('properties.id');
Track.prototype.sku = Facade.proxy('properties.sku');
Track.prototype.tax = Facade.proxy('properties.tax');
Track.prototype.name = Facade.proxy('properties.name');
Track.prototype.price = Facade.proxy('properties.price');
Track.prototype.total = Facade.proxy('properties.total');
Track.prototype.coupon = Facade.proxy('properties.coupon');
Track.prototype.shipping = Facade.proxy('properties.shipping');
/**
* Order id.
*
* @return {String}
* @api public
*/
Track.prototype.orderId = function(){
return this.proxy('properties.id')
|| this.proxy('properties.orderId');
};
/**
* Get subtotal.
*
* @return {Number}
*/
Track.prototype.subtotal = function(){
var subtotal = this.obj.properties.subtotal;
var total = this.total();
var n;
if (subtotal) return subtotal;
if (!total) return 0;
if (n = this.tax()) total -= n;
if (n = this.shipping()) total -= n;
return total;
};
/**
* Get products.
*
* @return {Array}
*/
Track.prototype.products = function(){
var props = this.obj.properties || {};
return props.products || [];
};
/**
* Get quantity.
*
* @return {Number}
*/
Track.prototype.quantity = function(){
var props = this.obj.properties || {};
return props.quantity || 1;
};
/**
* Get currency.
*
* @return {String}
*/
Track.prototype.currency = function(){
var props = this.obj.properties || {};
return props.currency || 'USD';
};
/**
* BACKWARDS COMPATIBILITY: should probably re-examine where these come from.
*/
Track.prototype.referrer = Facade.proxy('properties.referrer');
Track.prototype.query = Facade.proxy('options.query');
/**
* Get the call's properties.
*
* @param {Object} aliases
* @return {Object}
*/
Track.prototype.properties = function (aliases) {
var ret = this.field('properties') || {};
aliases = aliases || {};
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('properties.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the call's username.
*
* @return {String or Undefined}
*/
Track.prototype.username = function () {
return this.proxy('traits.username') ||
this.proxy('properties.username') ||
this.userId() ||
this.sessionId();
};
/**
* Get the call's email, using an the user ID if it's a valid email.
*
* @return {String or Undefined}
*/
Track.prototype.email = function () {
var email = this.proxy('traits.email');
email = email || this.proxy('properties.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the call's revenue, parsing it from a string with an optional leading
* dollar sign.
*
* For products/services that don't have shipping and are not directly taxed,
* they only care about tracking `revenue`. These are things like
* SaaS companies, who sell monthly subscriptions. The subscriptions aren't
* taxed directly, and since it's a digital product, it has no shipping.
*
* The only case where there's a difference between `revenue` and `total`
* (in the context of analytics) is on ecommerce platforms, where they want
* the `revenue` function to actually return the `total` (which includes
* tax and shipping, total = subtotal + tax + shipping). This is probably
* because on their backend they assume tax and shipping has been applied to
* the value, and so can get the revenue on their own.
*
* @return {Number}
*/
Track.prototype.revenue = function () {
var revenue = this.proxy('properties.revenue');
var event = this.event();
// it's always revenue, unless it's called during an order completion.
if (!revenue && event && event.match(/completed ?order/i)) {
revenue = this.proxy('properties.total');
}
return currency(revenue);
};
/**
* Get cents.
*
* @return {Number}
*/
Track.prototype.cents = function(){
var revenue = this.revenue();
return 'number' != typeof revenue
? this.value() || 0
: revenue * 100;
};
/**
* A utility to turn the pieces of a track call into an identify. Used for
* integrations with super properties or rate limits.
*
* TODO: remove me.
*
* @return {Facade}
*/
Track.prototype.identify = function () {
var json = this.json();
json.traits = this.traits();
return new Identify(json);
};
/**
* Get float from currency value.
*
* @param {Mixed} val
* @return {Number}
*/
function currency(val) {
if (!val) return;
if (typeof val === 'number') return val;
if (typeof val !== 'string') return;
val = val.replace(/\$/g, '');
val = parseFloat(val);
if (!isNaN(val)) return val;
}
}, {"./utils":58,"./facade":51,"./identify":54,"is-email":19}],
56: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var Facade = require('./facade');
var Track = require('./track');
/**
* Expose `Page` facade
*/
module.exports = Page;
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Page(dictionary){
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {String}
*/
Page.prototype.type =
Page.prototype.action = function(){
return 'page';
};
/**
* Proxies
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Get the page properties mixing `category` and `name`.
*
* @return {Object}
*/
Page.prototype.properties = function(){
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
if (category) props.category = category;
if (name) props.name = name;
return props;
};
/**
* Get the page fullName.
*
* @return {String}
*/
Page.prototype.fullName = function(){
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {String}
*/
Page.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {String} name
* @return {Track}
*/
Page.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
}, {"./utils":58,"./facade":51,"./track":55}],
57: [function(require, module, exports) {
var inherit = require('./utils').inherit;
var Page = require('./page');
var Track = require('./track');
/**
* Expose `Screen` facade
*/
module.exports = Screen;
/**
* Initialize new `Screen` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Screen(dictionary){
Page.call(this, dictionary);
}
/**
* Inherit from `Page`
*/
inherit(Screen, Page);
/**
* Get the facade's action.
*
* @return {String}
* @api public
*/
Screen.prototype.type =
Screen.prototype.action = function(){
return 'screen';
};
/**
* Get event with `name`.
*
* @param {String} name
* @return {String}
* @api public
*/
Screen.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Screen'
: 'Loaded a Screen';
};
/**
* Convert this Screen.
*
* @param {String} name
* @return {Track}
* @api public
*/
Screen.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
}, {"./utils":58,"./page":56,"./track":55}],
3: [function(require, module, exports) {
module.exports = '2.3.7';
}, {}],
4: [function(require, module, exports) {
/**
* Module dependencies.
*/
var each = require('each');
var plugins = require('./integrations.js');
/**
* Expose the integrations, using their own `name` from their `prototype`.
*/
each(plugins, function(plugin){
var name = (plugin.Integration || plugin).prototype.name;
exports[name] = plugin;
});
}, {"./integrations.js":82,"each":5}],
82: [function(require, module, exports) {
/**
* DON'T EDIT THIS FILE. It's automatically generated!
*/
module.exports = [
require('./lib/adroll'),
require('./lib/adwords'),
require('./lib/alexa'),
require('./lib/amplitude'),
require('./lib/appcues'),
require('./lib/awesm'),
require('./lib/awesomatic'),
require('./lib/bing-ads'),
require('./lib/bronto'),
require('./lib/bugherd'),
require('./lib/bugsnag'),
require('./lib/chartbeat'),
require('./lib/churnbee'),
require('./lib/clicktale'),
require('./lib/clicky'),
require('./lib/comscore'),
require('./lib/crazy-egg'),
require('./lib/curebit'),
require('./lib/customerio'),
require('./lib/drip'),
require('./lib/errorception'),
require('./lib/evergage'),
require('./lib/facebook-ads'),
require('./lib/foxmetrics'),
require('./lib/frontleaf'),
require('./lib/gauges'),
require('./lib/get-satisfaction'),
require('./lib/google-analytics'),
require('./lib/google-tag-manager'),
require('./lib/gosquared'),
require('./lib/heap'),
require('./lib/hellobar'),
require('./lib/hittail'),
require('./lib/hublo'),
require('./lib/hubspot'),
require('./lib/improvely'),
require('./lib/insidevault'),
require('./lib/inspectlet'),
require('./lib/intercom'),
require('./lib/keen-io'),
require('./lib/kenshoo'),
require('./lib/kissmetrics'),
require('./lib/klaviyo'),
require('./lib/leadlander'),
require('./lib/livechat'),
require('./lib/lucky-orange'),
require('./lib/lytics'),
require('./lib/mixpanel'),
require('./lib/mojn'),
require('./lib/mouseflow'),
require('./lib/mousestats'),
require('./lib/navilytics'),
require('./lib/olark'),
require('./lib/optimizely'),
require('./lib/perfect-audience'),
require('./lib/pingdom'),
require('./lib/piwik'),
require('./lib/preact'),
require('./lib/qualaroo'),
require('./lib/quantcast'),
require('./lib/rollbar'),
require('./lib/saasquatch'),
require('./lib/sentry'),
require('./lib/snapengage'),
require('./lib/spinnakr'),
require('./lib/tapstream'),
require('./lib/trakio'),
require('./lib/twitter-ads'),
require('./lib/usercycle'),
require('./lib/userfox'),
require('./lib/uservoice'),
require('./lib/vero'),
require('./lib/visual-website-optimizer'),
require('./lib/webengage'),
require('./lib/woopra'),
require('./lib/yandex-metrica')
];
}, {"./lib/adroll":83,"./lib/adwords":84,"./lib/alexa":85,"./lib/amplitude":86,"./lib/appcues":87,"./lib/awesm":88,"./lib/awesomatic":89,"./lib/bing-ads":90,"./lib/bronto":91,"./lib/bugherd":92,"./lib/bugsnag":93,"./lib/chartbeat":94,"./lib/churnbee":95,"./lib/clicktale":96,"./lib/clicky":97,"./lib/comscore":98,"./lib/crazy-egg":99,"./lib/curebit":100,"./lib/customerio":101,"./lib/drip":102,"./lib/errorception":103,"./lib/evergage":104,"./lib/facebook-ads":105,"./lib/foxmetrics":106,"./lib/frontleaf":107,"./lib/gauges":108,"./lib/get-satisfaction":109,"./lib/google-analytics":110,"./lib/google-tag-manager":111,"./lib/gosquared":112,"./lib/heap":113,"./lib/hellobar":114,"./lib/hittail":115,"./lib/hublo":116,"./lib/hubspot":117,"./lib/improvely":118,"./lib/insidevault":119,"./lib/inspectlet":120,"./lib/intercom":121,"./lib/keen-io":122,"./lib/kenshoo":123,"./lib/kissmetrics":124,"./lib/klaviyo":125,"./lib/leadlander":126,"./lib/livechat":127,"./lib/lucky-orange":128,"./lib/lytics":129,"./lib/mixpanel":130,"./lib/mojn":131,"./lib/mouseflow":132,"./lib/mousestats":133,"./lib/navilytics":134,"./lib/olark":135,"./lib/optimizely":136,"./lib/perfect-audience":137,"./lib/pingdom":138,"./lib/piwik":139,"./lib/preact":140,"./lib/qualaroo":141,"./lib/quantcast":142,"./lib/rollbar":143,"./lib/saasquatch":144,"./lib/sentry":145,"./lib/snapengage":146,"./lib/spinnakr":147,"./lib/tapstream":148,"./lib/trakio":149,"./lib/twitter-ads":150,"./lib/usercycle":151,"./lib/userfox":152,"./lib/uservoice":153,"./lib/vero":154,"./lib/visual-website-optimizer":155,"./lib/webengage":156,"./lib/woopra":157,"./lib/yandex-metrica":158}],
83: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var snake = require('to-snake-case');
var useHttps = require('use-https');
var each = require('each');
var is = require('is');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdRoll` integration.
*/
var AdRoll = module.exports = integration('AdRoll')
.assumesPageview()
.global('__adroll_loaded')
.global('adroll_adv_id')
.global('adroll_pix_id')
.global('adroll_custom_data')
.option('advId', '')
.option('pixId', '')
.tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">')
.tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">')
.mapping('events');
/**
* Initialize.
*
* http://support.adroll.com/getting-started-in-4-easy-steps/#step-one
* http://support.adroll.com/enhanced-conversion-tracking/
*
* @param {Object} page
*/
AdRoll.prototype.initialize = function(page){
window.adroll_adv_id = this.options.advId;
window.adroll_pix_id = this.options.pixId;
window.__adroll_loaded = true;
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
AdRoll.prototype.loaded = function(){
return window.__adroll;
};
/**
* Page.
*
* http://support.adroll.com/segmenting-clicks/
*
* @param {Page} page
*/
AdRoll.prototype.page = function(page){
var name = page.fullName();
this.track(page.track(name));
};
/**
* Track.
*
* @param {Track} track
*/
AdRoll.prototype.track = function(track){
var event = track.event();
var user = this.analytics.user();
var events = this.events(event);
var total = track.revenue() || track.total() || 0;
var orderId = track.orderId() || 0;
each(events, function(event){
var data = {};
if (user.id()) data.user_id = user.id();
data.adroll_conversion_value_in_dollars = total;
data.order_id = orderId;
// the adroll interface only allows for
// segment names which are snake cased.
data.adroll_segments = snake(event);
window.__adroll.record_user(data);
});
// no events found
if (!events.length) {
var data = {};
if (user.id()) data.user_id = user.id();
data.adroll_segments = snake(event);
window.__adroll.record_user(data);
}
};
}, {"segmentio/analytics.js-integration":159,"to-snake-case":160,"use-https":161,"each":5,"is":18}],
159: [function(require, module, exports) {
/**
* Module dependencies.
*/
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var debug = require('debug');
var defaults = require('defaults');
var protos = require('./protos');
var slug = require('slug');
var statics = require('./statics');
/**
* Expose `createIntegration`.
*/
module.exports = createIntegration;
/**
* Create a new `Integration` constructor.
*
* @param {String} name
* @return {Function} Integration
*/
function createIntegration(name){
/**
* Initialize a new `Integration`.
*
* @param {Object} options
*/
function Integration(options){
if (options && options.addIntegration) {
// plugin
return options.addIntegration(Integration);
}
this.debug = debug('analytics:integration:' + slug(name));
this.options = defaults(clone(options) || {}, this.defaults);
this._queue = [];
this.once('ready', bind(this, this.flush));
Integration.emit('construct', this);
this.ready = bind(this, this.ready);
this._wrapInitialize();
this._wrapPage();
this._wrapTrack();
}
Integration.prototype.defaults = {};
Integration.prototype.globals = [];
Integration.prototype.templates = {};
Integration.prototype.name = name;
for (var key in statics) Integration[key] = statics[key];
for (var key in protos) Integration.prototype[key] = protos[key];
return Integration;
}
}, {"./protos":162,"./statics":163,"bind":164,"callback":12,"clone":14,"debug":165,"defaults":16,"slug":166}],
162: [function(require, module, exports) {
/**
* Module dependencies.
*/
var loadScript = require('segmentio/load-script');
var normalize = require('to-no-case');
var callback = require('callback');
var Emitter = require('emitter');
var events = require('./events');
var tick = require('next-tick');
var assert = require('assert');
var after = require('after');
var each = require('component/each');
var type = require('type');
var fmt = require('yields/fmt');
/**
* Window defaults.
*/
var setTimeout = window.setTimeout;
var setInterval = window.setInterval;
var onerror = null;
var onload = null;
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Initialize.
*/
exports.initialize = function(){
var ready = this.ready;
tick(ready);
};
/**
* Loaded?
*
* @return {Boolean}
* @api private
*/
exports.loaded = function(){
return false;
};
/**
* Load.
*
* @param {Function} cb
*/
exports.load = function(cb){
callback.async(cb);
};
/**
* Page.
*
* @param {Page} page
*/
exports.page = function(page){};
/**
* Track.
*
* @param {Track} track
*/
exports.track = function(track){};
/**
* Get events that match `str`.
*
* Examples:
*
* events = { my_event: 'a4991b88' }
* .map(events, 'My Event');
* // => ["a4991b88"]
* .map(events, 'whatever');
* // => []
*
* events = [{ key: 'my event', value: '9b5eb1fa' }]
* .map(events, 'my_event');
* // => ["9b5eb1fa"]
* .map(events, 'whatever');
* // => []
*
* @param {String} str
* @return {Array}
* @api public
*/
exports.map = function(obj, str){
var a = normalize(str);
var ret = [];
// noop
if (!obj) return ret;
// object
if ('object' == type(obj)) {
for (var k in obj) {
var item = obj[k];
var b = normalize(k);
if (b == a) ret.push(item);
}
}
// array
if ('array' == type(obj)) {
if (!obj.length) return ret;
if (!obj[0].key) return ret;
for (var i = 0; i < obj.length; ++i) {
var item = obj[i];
var b = normalize(item.key);
if (b == a) ret.push(item.value);
}
}
return ret;
};
/**
* Invoke a `method` that may or may not exist on the prototype with `args`,
* queueing or not depending on whether the integration is "ready". Don't
* trust the method call, since it contains integration party code.
*
* @param {String} method
* @param {Mixed} args...
* @api private
*/
exports.invoke = function(method){
if (!this[method]) return;
var args = [].slice.call(arguments, 1);
if (!this._ready) return this.queue(method, args);
var ret;
try {
this.debug('%s with %o', method, args);
ret = this[method].apply(this, args);
} catch (e) {
this.debug('error %o calling %s with %o', e, method, args);
}
return ret;
};
/**
* Queue a `method` with `args`. If the integration assumes an initial
* pageview, then let the first call to `page` pass through.
*
* @param {String} method
* @param {Array} args
* @api private
*/
exports.queue = function(method, args){
if ('page' == method && this._assumesPageview && !this._initialized) {
return this.page.apply(this, args);
}
this._queue.push({ method: method, args: args });
};
/**
* Flush the internal queue.
*
* @api private
*/
exports.flush = function(){
this._ready = true;
var call;
while (call = this._queue.shift()) this[call.method].apply(this, call.args);
};
/**
* Reset the integration, removing its global variables.
*
* @api private
*/
exports.reset = function(){
for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;
window.setTimeout = setTimeout;
window.setInterval = setInterval;
window.onerror = onerror;
window.onload = onload;
};
/**
* Load a tag by `name`.
*
* @param {String} name
* @param {Function} [fn]
*/
exports.load = function(name, locals, fn){
if ('function' == typeof name) fn = name, locals = null, name = null;
if (name && 'object' == typeof name) fn = locals, locals = name, name = null;
if ('function' == typeof locals) fn = locals, locals = null;
name = name || 'library';
locals = locals || {};
locals = this.locals(locals);
var template = this.templates[name];
assert(template, fmt('Template "%s" not defined.', name));
var attrs = render(template, locals);
var el;
switch (template.type) {
case 'img':
attrs.width = 1;
attrs.height = 1;
el = loadImage(attrs, fn);
break;
case 'script':
el = loadScript(attrs, fn);
// TODO: hack until refactoring load-script
delete attrs.src;
each(attrs, function(key, val){
el.setAttribute(key, val);
});
break;
case 'iframe':
el = loadIframe(attrs, fn);
break;
}
return el;
};
/**
* Locals for tag templates.
*
* By default it includes a cache buster,
* and all of the options.
*
* @param {Object} [locals]
* @return {Object}
*/
exports.locals = function(locals){
locals = locals || {};
var cache = Math.floor(new Date().getTime() / 3600000);
if (!locals.hasOwnProperty('cache')) locals.cache = cache;
each(this.options, function(key, val){
if (!locals.hasOwnProperty(key)) locals[key] = val;
});
return locals;
};
/**
* Simple way to emit ready.
*/
exports.ready = function(){
this.emit('ready');
};
/**
* Wrap the initialize method in an exists check, so we don't have to do it for
* every single integration.
*
* @api private
*/
exports._wrapInitialize = function(){
var initialize = this.initialize;
this.initialize = function(){
this.debug('initialize');
this._initialized = true;
var ret = initialize.apply(this, arguments);
this.emit('initialize');
return ret;
};
if (this._assumesPageview) this.initialize = after(2, this.initialize);
};
/**
* Wrap the page method to call `initialize` instead if the integration assumes
* a pageview.
*
* @api private
*/
exports._wrapPage = function(){
var page = this.page;
this.page = function(){
if (this._assumesPageview && !this._initialized) {
return this.initialize.apply(this, arguments);
}
return page.apply(this, arguments);
};
};
/**
* Wrap the track method to call other ecommerce methods if
* available depending on the `track.event()`.
*
* @api private
*/
exports._wrapTrack = function(){
var t = this.track;
this.track = function(track){
var event = track.event();
var called;
var ret;
for (var method in events) {
var regexp = events[method];
if (!this[method]) continue;
if (!regexp.test(event)) continue;
ret = this[method].apply(this, arguments);
called = true;
break;
}
if (!called) ret = t.apply(this, arguments);
return ret;
};
};
function loadImage(attrs, fn) {
fn = fn || function(){};
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
img.src = attrs.src;
img.width = 1;
img.height = 1;
return img;
}
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
/**
* Render template + locals into an `attrs` object.
*
* @param {Object} template
* @param {Object} locals
* @return {Object}
*/
function render(template, locals) {
var attrs = {};
each(template.attrs, function(key, val){
attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){
return locals[$1];
});
});
return attrs;
}
}, {"./events":167,"segmentio/load-script":168,"to-no-case":169,"callback":12,"emitter":17,"next-tick":45,"assert":170,"after":10,"component/each":79,"type":35,"yields/fmt":171}],
167: [function(require, module, exports) {
/**
* Expose `events`.
*/
module.exports = {
removedProduct: /removed[ _]?product/i,
viewedProduct: /viewed[ _]?product/i,
addedProduct: /added[ _]?product/i,
completedOrder: /completed[ _]?order/i
};
}, {}],
168: [function(require, module, exports) {
/**
* Module dependencies.
*/
var onload = require('script-onload');
var tick = require('next-tick');
var type = require('type');
/**
* Expose `loadScript`.
*
* @param {Object} options
* @param {Function} fn
* @api public
*/
module.exports = function loadScript(options, fn){
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if ('string' == type(options)) options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
// If we have a fn, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if ('function' == type(fn)) {
onload(script, fn);
}
tick(function(){
// Append after event listeners are attached for IE.
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
});
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
}, {"script-onload":172,"next-tick":45,"type":35}],
172: [function(require, module, exports) {
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
/**
* Invoke `fn(err)` when the given `el` script loads.
*
* @param {Element} el
* @param {Function} fn
* @api public
*/
module.exports = function(el, fn){
return el.addEventListener
? add(el, fn)
: attach(el, fn);
};
/**
* Add event listener to `el`, `fn()`.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function add(el, fn){
el.addEventListener('load', function(_, e){ fn(null, e); }, false);
el.addEventListener('error', function(e){
var err = new Error('failed to load the script "' + el.src + '"');
err.event = e;
fn(err);
}, false);
}
/**
* Attach evnet.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function attach(el, fn){
el.attachEvent('onreadystatechange', function(e){
if (!/complete|loaded/.test(el.readyState)) return;
fn(null, e);
});
}
}, {}],
169: [function(require, module, exports) {
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) return unseparate(string).toLowerCase();
return uncamelize(string).toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
}, {}],
170: [function(require, module, exports) {
/**
* Module dependencies.
*/
var equals = require('equals');
var fmt = require('fmt');
var stack = require('stack');
/**
* Assert `expr` with optional failure `msg`.
*
* @param {Mixed} expr
* @param {String} [msg]
* @api public
*/
module.exports = exports = function (expr, msg) {
if (expr) return;
throw new Error(msg || message());
};
/**
* Assert `actual` is weak equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.equal = function (actual, expected, msg) {
if (actual == expected) return;
throw new Error(msg || fmt('Expected %o to equal %o.', actual, expected));
};
/**
* Assert `actual` is not weak equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.notEqual = function (actual, expected, msg) {
if (actual != expected) return;
throw new Error(msg || fmt('Expected %o not to equal %o.', actual, expected));
};
/**
* Assert `actual` is deep equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.deepEqual = function (actual, expected, msg) {
if (equals(actual, expected)) return;
throw new Error(msg || fmt('Expected %o to deeply equal %o.', actual, expected));
};
/**
* Assert `actual` is not deep equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.notDeepEqual = function (actual, expected, msg) {
if (!equals(actual, expected)) return;
throw new Error(msg || fmt('Expected %o not to deeply equal %o.', actual, expected));
};
/**
* Assert `actual` is strict equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.strictEqual = function (actual, expected, msg) {
if (actual === expected) return;
throw new Error(msg || fmt('Expected %o to strictly equal %o.', actual, expected));
};
/**
* Assert `actual` is not strict equal to `expected`.
*
* @param {Mixed} actual
* @param {Mixed} expected
* @param {String} [msg]
* @api public
*/
exports.notStrictEqual = function (actual, expected, msg) {
if (actual !== expected) return;
throw new Error(msg || fmt('Expected %o not to strictly equal %o.', actual, expected));
};
/**
* Assert `block` throws an `error`.
*
* @param {Function} block
* @param {Function} [error]
* @param {String} [msg]
* @api public
*/
exports.throws = function (block, error, msg) {
var err;
try {
block();
} catch (e) {
err = e;
}
if (!err) throw new Error(msg || fmt('Expected %s to throw an error.', block.toString()));
if (error && !(err instanceof error)) {
throw new Error(msg || fmt('Expected %s to throw an %o.', block.toString(), error));
}
};
/**
* Assert `block` doesn't throw an `error`.
*
* @param {Function} block
* @param {Function} [error]
* @param {String} [msg]
* @api public
*/
exports.doesNotThrow = function (block, error, msg) {
var err;
try {
block();
} catch (e) {
err = e;
}
if (err) throw new Error(msg || fmt('Expected %s not to throw an error.', block.toString()));
if (error && (err instanceof error)) {
throw new Error(msg || fmt('Expected %s not to throw an %o.', block.toString(), error));
}
};
/**
* Create a message from the call stack.
*
* @return {String}
* @api private
*/
function message() {
if (!Error.captureStackTrace) return 'assertion failed';
var callsite = stack()[2];
var fn = callsite.getFunctionName();
var file = callsite.getFileName();
var line = callsite.getLineNumber() - 1;
var col = callsite.getColumnNumber() - 1;
var src = get(file);
line = src.split('\n')[line].slice(col);
var m = line.match(/assert\((.*)\)/);
return m && m[1].trim();
}
/**
* Load contents of `script`.
*
* @param {String} script
* @return {String}
* @api private
*/
function get(script) {
var xhr = new XMLHttpRequest;
xhr.open('GET', script, false);
xhr.send(null);
return xhr.responseText;
}
}, {"equals":173,"fmt":171,"stack":174}],
173: [function(require, module, exports) {
var type = require('type')
/**
* expose equals
*/
module.exports = equals
equals.compare = compare
/**
* assert all values are equal
*
* @param {Any} [...]
* @return {Boolean}
*/
function equals(){
var i = arguments.length - 1
while (i > 0) {
if (!compare(arguments[i], arguments[--i])) return false
}
return true
}
// (any, any, [array]) -> boolean
function compare(a, b, memos){
// All identical values are equivalent
if (a === b) return true
var fnA = types[type(a)]
var fnB = types[type(b)]
return fnA && fnA === fnB
? fnA(a, b, memos)
: false
}
var types = {}
// (Number) -> boolean
types.number = function(a){
// NaN check
return a !== a
}
// (function, function, array) -> boolean
types['function'] = function(a, b, memos){
return a.toString() === b.toString()
// Functions can act as objects
&& types.object(a, b, memos)
&& compare(a.prototype, b.prototype)
}
// (date, date) -> boolean
types.date = function(a, b){
return +a === +b
}
// (regexp, regexp) -> boolean
types.regexp = function(a, b){
return a.toString() === b.toString()
}
// (DOMElement, DOMElement) -> boolean
types.element = function(a, b){
return a.outerHTML === b.outerHTML
}
// (textnode, textnode) -> boolean
types.textnode = function(a, b){
return a.textContent === b.textContent
}
// decorate `fn` to prevent it re-checking objects
// (function) -> function
function memoGaurd(fn){
return function(a, b, memos){
if (!memos) return fn(a, b, [])
var i = memos.length, memo
while (memo = memos[--i]) {
if (memo[0] === a && memo[1] === b) return true
}
return fn(a, b, memos)
}
}
types['arguments'] =
types.array = memoGaurd(compareArrays)
// (array, array, array) -> boolean
function compareArrays(a, b, memos){
var i = a.length
if (i !== b.length) return false
memos.push([a, b])
while (i--) {
if (!compare(a[i], b[i], memos)) return false
}
return true
}
types.object = memoGaurd(compareObjects)
// (object, object, array) -> boolean
function compareObjects(a, b, memos) {
var ka = getEnumerableProperties(a)
var kb = getEnumerableProperties(b)
var i = ka.length
// same number of properties
if (i !== kb.length) return false
// although not necessarily the same order
ka.sort()
kb.sort()
// cheap key test
while (i--) if (ka[i] !== kb[i]) return false
// remember
memos.push([a, b])
// iterate again this time doing a thorough check
i = ka.length
while (i--) {
var key = ka[i]
if (!compare(a[key], b[key], memos)) return false
}
return true
}
// (object) -> array
function getEnumerableProperties (object) {
var result = []
for (var k in object) if (k !== 'constructor') {
result.push(k)
}
return result
}
}, {"type":175}],
175: [function(require, module, exports) {
var toString = {}.toString
var DomNode = typeof window != 'undefined'
? window.Node
: Function
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = exports = function(x){
var type = typeof x
if (type != 'object') return type
type = types[toString.call(x)]
if (type) return type
if (x instanceof DomNode) switch (x.nodeType) {
case 1: return 'element'
case 3: return 'text-node'
case 9: return 'document'
case 11: return 'document-fragment'
default: return 'dom-node'
}
}
var types = exports.types = {
'[object Function]': 'function',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Arguments]': 'arguments',
'[object Array]': 'array',
'[object String]': 'string',
'[object Null]': 'null',
'[object Undefined]': 'undefined',
'[object Number]': 'number',
'[object Boolean]': 'boolean',
'[object Object]': 'object',
'[object Text]': 'text-node',
'[object Uint8Array]': 'bit-array',
'[object Uint16Array]': 'bit-array',
'[object Uint32Array]': 'bit-array',
'[object Uint8ClampedArray]': 'bit-array',
'[object Error]': 'error',
'[object FormData]': 'form-data',
'[object File]': 'file',
'[object Blob]': 'blob'
}
}, {}],
171: [function(require, module, exports) {
/**
* Export `fmt`
*/
module.exports = fmt;
/**
* Formatters
*/
fmt.o = JSON.stringify;
fmt.s = String;
fmt.d = parseInt;
/**
* Format the given `str`.
*
* @param {String} str
* @param {...} args
* @return {String}
* @api public
*/
function fmt(str){
var args = [].slice.call(arguments, 1);
var j = 0;
return str.replace(/%([a-z])/gi, function(_, f){
return fmt[f]
? fmt[f](args[j++])
: _ + f;
});
}
}, {}],
174: [function(require, module, exports) {
/**
* Expose `stack()`.
*/
module.exports = stack;
/**
* Return the stack.
*
* @return {Array}
* @api public
*/
function stack() {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
}, {}],
163: [function(require, module, exports) {
/**
* Module dependencies.
*/
var after = require('after');
var domify = require('component/domify');
var each = require('component/each');
var Emitter = require('emitter');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Add a new option to the integration by `key` with default `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Integration}
*/
exports.option = function(key, value){
this.prototype.defaults[key] = value;
return this;
};
/**
* Add a new mapping option.
*
* This will create a method `name` that will return a mapping
* for you to use.
*
* Example:
*
* Integration('My Integration')
* .mapping('events');
*
* new MyIntegration().track('My Event');
*
* .track = function(track){
* var events = this.events(track.event());
* each(events, send);
* };
*
* @param {String} name
* @return {Integration}
*/
exports.mapping = function(name){
this.option(name, []);
this.prototype[name] = function(str){
return this.map(this.options[name], str);
};
return this;
};
/**
* Register a new global variable `key` owned by the integration, which will be
* used to test whether the integration is already on the page.
*
* @param {String} global
* @return {Integration}
*/
exports.global = function(key){
this.prototype.globals.push(key);
return this;
};
/**
* Mark the integration as assuming an initial pageview, so to defer loading
* the script until the first `page` call, noop the first `initialize`.
*
* @return {Integration}
*/
exports.assumesPageview = function(){
this.prototype._assumesPageview = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnLoad = function(){
this.prototype._readyOnLoad = true;
return this;
};
/**
* Mark the integration as being "ready" once `initialize` is called.
*
* @return {Integration}
*/
exports.readyOnInitialize = function(){
this.prototype._readyOnInitialize = true;
return this;
};
/**
* Define a tag to be loaded.
*
* @param {String} str DOM tag as string or URL
* @return {Integration}
*/
exports.tag = function(name, str){
if (null == str) {
str = name;
name = 'library';
}
this.prototype.templates[name] = objectify(str);
return this;
};
/**
* Given a string, give back DOM attributes.
*
* Do it in a way where the browser doesn't load images or iframes.
* It turns out, domify will load images/iframes, because
* whenever you construct those DOM elements,
* the browser immediately loads them.
*
* @param {String} str
* @return {Object}
*/
function objectify(str) {
// replace `src` with `data-src` to prevent image loading
str = str.replace(' src="', ' data-src="');
var el = domify(str);
var attrs = {};
each(el.attributes, function(attr){
// then replace it back
var name = 'data-src' == attr.name ? 'src' : attr.name;
attrs[name] = attr.value;
});
return {
type: el.tagName.toLowerCase(),
attrs: attrs
};
}
}, {"after":10,"component/domify":176,"component/each":79,"emitter":17}],
176: [function(require, module, exports) {
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Tests for browser support.
*/
var div = document.createElement('div');
// Setup
div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
var innerHTMLBug = !div.getElementsByTagName('link').length;
div = undefined;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
// for script/link/style tags to work in IE6-8, you have to wrap
// in a div with a non-whitespace character in front, ha!
_default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return a DOM Node instance, which could be a TextNode,
* HTML DOM Node of some kind (<div> for example), or a DocumentFragment
* instance, depending on the contents of the `html` string.
*
* @param {String} html - HTML string to "domify"
* @param {Document} doc - The `document` instance to create the Node for
* @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance
* @api private
*/
function parse(html, doc) {
if ('string' != typeof html) throw new TypeError('String expected');
// default to the global `document` object
if (!doc) doc = document;
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return doc.createTextNode(html);
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
var tag = m[1];
// body support
if (tag == 'body') {
var el = doc.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = doc.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = doc.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
}, {}],
164: [function(require, module, exports) {
var bind = require('bind')
, bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
}, {"bind":33,"bind-all":34}],
165: [function(require, module, exports) {
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
}, {"./lib/debug":177,"./debug":178}],
177: [function(require, module, exports) {
/**
* Module dependencies.
*/
var tty = require('tty');
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Enabled debuggers.
*/
var names = []
, skips = [];
(process.env.DEBUG || '')
.split(/[\s,]+/)
.forEach(function(name){
name = name.replace('*', '.*?');
if (name[0] === '-') {
skips.push(new RegExp('^' + name.substr(1) + '$'));
} else {
names.push(new RegExp('^' + name + '$'));
}
});
/**
* Colors.
*/
var colors = [6, 2, 3, 4, 5, 1];
/**
* Previous debug() call.
*/
var prev = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Is stdout a TTY? Colored output is disabled when `true`.
*/
var isatty = tty.isatty(2);
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function color() {
return colors[prevColor++ % colors.length];
}
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
function humanize(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
}
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
function disabled(){}
disabled.enabled = false;
var match = skips.some(function(re){
return re.test(name);
});
if (match) return disabled;
match = names.some(function(re){
return re.test(name);
});
if (!match) return disabled;
var c = color();
function colored(fmt) {
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (prev[name] || curr);
prev[name] = curr;
fmt = ' \u001b[9' + c + 'm' + name + ' '
+ '\u001b[3' + c + 'm\u001b[90m'
+ fmt + '\u001b[3' + c + 'm'
+ ' +' + humanize(ms) + '\u001b[0m';
console.error.apply(this, arguments);
}
function plain(fmt) {
fmt = coerce(fmt);
fmt = new Date().toUTCString()
+ ' ' + name + ' ' + fmt;
console.error.apply(this, arguments);
}
colored.enabled = plain.enabled = true;
return isatty || process.env.DEBUG_COLORS
? colored
: plain;
}
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
}, {}],
178: [function(require, module, exports) {
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
}, {}],
166: [function(require, module, exports) {
/**
* Generate a slug from the given `str`.
*
* example:
*
* generate('foo bar');
* // > foo-bar
*
* @param {String} str
* @param {Object} options
* @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g`
* @config {String} [separator] separator to insert, defaulted to `-`
* @return {String}
*/
module.exports = function (str, options) {
options || (options = {});
return str.toLowerCase()
.replace(options.replace || /[^a-z0-9]/g, ' ')
.replace(/^ +| +$/g, '')
.replace(/ +/g, options.separator || '-')
};
}, {}],
160: [function(require, module, exports) {
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
}, {"to-space-case":179}],
179: [function(require, module, exports) {
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
}, {"to-no-case":69}],
161: [function(require, module, exports) {
/**
* Protocol.
*/
module.exports = function (url) {
switch (arguments.length) {
case 0: return check();
case 1: return transform(url);
}
};
/**
* Transform a protocol-relative `url` to the use the proper protocol.
*
* @param {String} url
* @return {String}
*/
function transform (url) {
return check() ? 'https:' + url : 'http:' + url;
}
/**
* Check whether `https:` be used for loading scripts.
*
* @return {Boolean}
*/
function check () {
return (
location.protocol == 'https:' ||
location.protocol == 'chrome-extension:'
);
}
}, {}],
84: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var onbody = require('on-body');
var domify = require('domify');
var Queue = require('queue');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Script loader queue.
*/
var q = new Queue({ concurrency: 1, timeout: 2000 });
/**
* Expose `AdWords`.
*/
var AdWords = module.exports = integration('AdWords')
.option('conversionId', '')
.option('remarketing', false)
.tag('conversion', '<script src="//www.googleadservices.com/pagead/conversion.js">')
.mapping('events');
/**
* Load.
*
* @param {Function} fn
* @api public
*/
AdWords.prototype.initialize = function(){
onbody(this.ready);
};
/**
* Loaded.
*
* @return {Boolean}
* @api public
*/
AdWords.prototype.loaded = function(){
return !! document.body;
};
/**
* Page.
*
* https://support.google.com/adwords/answer/3111920#standard_parameters
*
* @param {Page} page
*/
AdWords.prototype.page = function(page){
var remarketing = this.options.remarketing;
var id = this.options.conversionId;
if (remarketing) this.remarketing(id);
};
/**
* Track.
*
* @param {Track}
* @api public
*/
AdWords.prototype.track = function(track){
var id = this.options.conversionId;
var events = this.events(track.event());
var revenue = track.revenue() || 0;
var self = this;
each(events, function(label){
self.conversion({
conversionId: id,
value: revenue,
label: label,
});
});
};
/**
* Report AdWords conversion.
*
* @param {Object} obj
* @param {Function} [fn]
* @api private
*/
AdWords.prototype.conversion = function(obj, fn){
this.enqueue({
google_conversion_id: obj.conversionId,
google_conversion_language: 'en',
google_conversion_format: '3',
google_conversion_color: 'ffffff',
google_conversion_label: obj.label,
google_conversion_value: obj.value,
google_remarketing_only: false
}, fn);
};
/**
* Add remarketing.
*
* @param {String} id Conversion ID
* @api private
*/
AdWords.prototype.remarketing = function(id){
this.enqueue({
google_conversion_id: id,
google_remarketing_only: true
});
};
/**
* Queue external call.
*
* @param {Object} obj
* @param {Function} [fn]
*/
AdWords.prototype.enqueue = function(obj, fn){
this.debug('sending %o', obj);
var self = this;
q.push(function(next){
self.globalize(obj);
self.shim();
self.load('conversion', function(){
if (fn) fn();
next();
});
});
};
/**
* Set global variables.
*
* @param {Object} obj
*/
AdWords.prototype.globalize = function(obj){
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
window[name] = obj[name];
}
}
};
/**
* Shim for `document.write`.
*
* @api private
*/
AdWords.prototype.shim = function(){
var self = this;
var write = document.write;
document.write = append;
function append(str){
var el = domify(str);
if (!el.src) return write(str);
if (!/googleadservices/.test(el.src)) return write(str);
self.debug('append %o', el);
document.body.appendChild(el);
document.write = write;
}
}
}, {"segmentio/analytics.js-integration":159,"on-body":180,"domify":181,"queue":182,"each":5}],
180: [function(require, module, exports) {
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
}, {"each":79}],
181: [function(require, module, exports) {
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) {
if ('string' != typeof html) throw new TypeError('String expected');
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
}, {}],
182: [function(require, module, exports) {
/**
* Module dependencies.
*/
var Emitter;
var bind;
try {
Emitter = require('emitter');
bind = require('bind');
} catch (err) {
Emitter = require('component-emitter');
bind = require('component-bind');
}
/**
* Expose `Queue`.
*/
module.exports = Queue;
/**
* Initialize a `Queue` with the given options:
*
* - `concurrency` [1]
* - `timeout` [0]
*
* @param {Object} options
* @api public
*/
function Queue(options) {
options = options || {};
this.timeout = options.timeout || 0;
this.concurrency = options.concurrency || 1;
this.pending = 0;
this.jobs = [];
}
/**
* Mixin emitter.
*/
Emitter(Queue.prototype);
/**
* Return queue length.
*
* @return {Number}
* @api public
*/
Queue.prototype.length = function(){
return this.pending + this.jobs.length;
};
/**
* Queue `fn` for execution.
*
* @param {Function} fn
* @param {Function} [cb]
* @api public
*/
Queue.prototype.push = function(fn, cb){
this.jobs.push([fn, cb]);
setTimeout(bind(this, this.run), 0);
};
/**
* Run jobs at the specified concurrency.
*
* @api private
*/
Queue.prototype.run = function(){
while (this.pending < this.concurrency) {
var job = this.jobs.shift();
if (!job) break;
this.exec(job);
}
};
/**
* Execute `job`.
*
* @param {Array} job
* @api private
*/
Queue.prototype.exec = function(job){
var self = this;
var ms = this.timeout;
var fn = job[0];
var cb = job[1];
if (ms) fn = timeout(fn, ms);
this.pending++;
fn(function(err, res){
cb && cb(err, res);
self.pending--;
self.run();
});
};
/**
* Decorate `fn` with a timeout of `ms`.
*
* @param {Function} fn
* @param {Function} ms
* @return {Function}
* @api private
*/
function timeout(fn, ms) {
return function(cb){
var done;
var id = setTimeout(function(){
done = true;
var err = new Error('Timeout of ' + ms + 'ms exceeded');
err.timeout = timeout;
cb(err);
}, ms);
fn(function(err, res){
if (done) return;
clearTimeout(id);
cb(err, res);
});
}
}
}, {"emitter":183,"bind":33,"component-emitter":183,"component-bind":33}],
183: [function(require, module, exports) {
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
}, {}],
85: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose Alexa integration.
*/
var Alexa = module.exports = integration('Alexa')
.assumesPageview()
.global('_atrk_opts')
.option('account', null)
.option('domain', '')
.option('dynamic', true)
.tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Alexa.prototype.initialize = function(page){
var self = this;
window._atrk_opts = {
atrk_acct: this.options.account,
domain: this.options.domain,
dynamic: this.options.dynamic
};
this.load(function(){
window.atrk();
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Alexa.prototype.loaded = function(){
return !! window.atrk;
};
}, {"segmentio/analytics.js-integration":159}],
86: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `Amplitude` integration.
*/
var Amplitude = module.exports = integration('Amplitude')
.assumesPageview()
.global('amplitude')
.option('apiKey', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');
/**
* Initialize.
*
* https://github.com/amplitude/Amplitude-Javascript
*
* @param {Object} page
*/
Amplitude.prototype.initialize = function(page){
(function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"]; for (var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document);
window.amplitude.init(this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Amplitude.prototype.loaded = function(){
return !! (window.amplitude && window.amplitude.options);
};
/**
* Page.
*
* @param {Page} page
*/
Amplitude.prototype.page = function(page){
var properties = page.properties();
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Identify.
*
* @param {Facade} identify
*/
Amplitude.prototype.identify = function(identify){
var id = identify.userId();
var traits = identify.traits();
if (id) window.amplitude.setUserId(id);
if (traits) window.amplitude.setGlobalUserProperties(traits);
};
/**
* Track.
*
* @param {Track} event
*/
Amplitude.prototype.track = function(track){
var props = track.properties();
var event = track.event();
window.amplitude.logEvent(event, props);
};
}, {"segmentio/analytics.js-integration":159}],
87: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Appcues);
};
/**
* Expose `Appcues` integration.
*/
var Appcues = exports.Integration = integration('Appcues')
.assumesPageview()
.global('Appcues')
.global('AppcuesIdentity')
.option('appcuesId', '')
.option('userId', '')
.option('userEmail', '');
/**
* Initialize.
*
* http://appcues.com/docs/
*
* @param {Object}
*/
Appcues.prototype.initialize = function(){
this.load(function() {
window.Appcues.init();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Appcues.prototype.loaded = function(){
return is.object(window.Appcues);
};
/**
* Load the Appcues library.
*
* @param {Function} callback
*/
Appcues.prototype.load = function(callback){
var script = load('//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js', callback);
script.setAttribute('data-appcues-id', this.options.appcuesId);
script.setAttribute('data-user-id', this.options.userId);
script.setAttribute('data-user-email', this.options.userEmail);
};
/**
* Identify.
*
* http://appcues.com/docs#identify
*
* @param {Identify} identify
*/
Appcues.prototype.identify = function(identify){
window.Appcues.identify(identify.traits());
};
}, {"segmentio/analytics.js-integration":159,"load-script":168,"is":18}],
88: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var each = require('each');
/**
* Expose `Awesm` integration.
*/
var Awesm = module.exports = integration('awe.sm')
.assumesPageview()
.global('AWESM')
.option('apiKey', '')
.tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">')
.mapping('events');
/**
* Initialize.
*
* http://developers.awe.sm/guides/javascript/
*
* @param {Object} page
*/
Awesm.prototype.initialize = function(page){
window.AWESM = { api_key: this.options.apiKey };
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesm.prototype.loaded = function(){
return !! (window.AWESM && window.AWESM._exists);
};
/**
* Track.
*
* @param {Track} track
*/
Awesm.prototype.track = function(track){
var user = this.analytics.user();
var goals = this.events(track.event());
each(goals, function(goal){
window.AWESM.convert(goal, track.cents(), null, user.id());
});
};
}, {"segmentio/analytics.js-integration":159,"each":5}],
89: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
var noop = function(){};
var onBody = require('on-body');
/**
* Expose `Awesomatic` integration.
*/
var Awesomatic = module.exports = integration('Awesomatic')
.assumesPageview()
.global('Awesomatic')
.global('AwesomaticSettings')
.global('AwsmSetup')
.global('AwsmTmp')
.option('appId', '')
.tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Awesomatic.prototype.initialize = function(page){
var self = this;
var user = this.analytics.user();
var id = user.id();
var options = user.traits();
options.appId = this.options.appId;
if (id) options.user_id = id;
this.load(function(){
window.Awesomatic.initialize(options, function(){
self.ready(); // need to wait for initialize to callback
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesomatic.prototype.loaded = function(){
return is.object(window.Awesomatic);
};
}, {"segmentio/analytics.js-integration":159,"is":18,"on-body":180}],
90: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var onbody = require('on-body');
var domify = require('domify');
var extend = require('extend');
var bind = require('bind');
var when = require('when');
var each = require('each');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Noop.
*/
var noop = function(){};
/**
* Expose `Bing`.
*
* https://bingads.microsoft.com/campaign/signup
*/
var Bing = module.exports = integration('Bing Ads')
.option('siteId', '')
.option('domainId', '')
.tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">')
.mapping('events');
/**
* Initialize.
*
* http://msdn.microsoft.com/en-us/library/bing-ads-campaign-management-campaign-analytics-scripts.aspx
*
* @param {Object} page
*/
Bing.prototype.initialize = function(page){
if (!window.mstag) {
window.mstag = {
loadTag: noop,
time: (new Date()).getTime(),
// they use document.write, which doesn't work when loaded async.
// they provide a way to override it.
// the first time it is called, load the script,
// and only when that script is done, is "loading" done.
_write: writeToAppend
};
};
var self = this;
onbody(function(){
self.load(function(){
var loaded = bind(self, self.loaded);
// poll until this.loaded() is true.
// have to do a weird hack like this because
// the first script loads a second script,
// and only after the second script is it actually loaded.
when(loaded, self.ready);
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bing.prototype.loaded = function(){
return !! (window.mstag && window.mstag.loadTag !== noop);
};
/**
* Track.
*
* @param {Track} track
*/
Bing.prototype.track = function(track){
var events = this.events(track.event());
var revenue = track.revenue() || 0;
var self = this;
each(events, function(goal){
window.mstag.loadTag('analytics', {
domainId: self.options.domainId,
revenue: revenue,
dedup: '1',
type: '1',
actionid: goal
});
});
};
/**
* Convert `document.write` to `document.appendChild`.
*
* TODO: make into a component.
*
* @param {String} str
*/
function writeToAppend(str) {
var first = document.getElementsByTagName('script')[0];
var el = domify(str);
// https://github.com/component/domify/issues/14
if ('script' == el.tagName.toLowerCase() && el.getAttribute('src')) {
var tmp = document.createElement('script');
tmp.src = el.getAttribute('src');
tmp.async = true;
el = tmp;
}
document.body.appendChild(el);
}
}, {"segmentio/analytics.js-integration":159,"on-body":180,"domify":181,"extend":40,"bind":33,"when":184,"each":5}],
184: [function(require, module, exports) {
var callback = require('callback');
/**
* Expose `when`.
*/
module.exports = when;
/**
* Loop on a short interval until `condition()` is true, then call `fn`.
*
* @param {Function} condition
* @param {Function} fn
* @param {Number} interval (optional)
*/
function when (condition, fn, interval) {
if (condition()) return callback.async(fn);
var ref = setInterval(function () {
if (!condition()) return;
callback(fn);
clearInterval(ref);
}, interval || 10);
}
}, {"callback":12}],
91: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var pixel = require('load-pixel')('http://app.bronto.com/public/');
var qs = require('querystring');
var each = require('each');
/**
* Expose `Bronto` integration.
*/
var Bronto = module.exports = integration('Bronto')
.global('__bta')
.option('siteId', '')
.option('host', '')
.tag('<script src="//p.bm23.com/bta.js">');
/**
* Initialize.
*
* http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite
* http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB
* http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB
*
* @param {Object} page
*/
Bronto.prototype.initialize = function(page){
var self = this;
var params = qs.parse(window.location.search);
if (!params._bta_tid && !params._bta_c) {
this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.');
}
this.load(function(){
var opts = self.options;
self.bta = new window.__bta(opts.siteId);
if (opts.host) self.bta.setHost(opts.host);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bronto.prototype.loaded = function(){
return this.bta;
};
/**
* Track.
*
* The JS conversion tracking toggles must be on
* in the application in order for you to see the data
* in your account, and for it to function as it should.
* If the toggle is not on the system will ignore
* any requests coming into it.
*
* To create a test user, create a contact in Bronto,
* send that contact an email, then process through your site
* to place a test order to hit the JS code.
*
* Provided you have Click Through Link Tracking enabled,
* when a contact clicks a link contained in an email you send them via Bronto,
* we create a tracking cookie (most commonly used for tracking conversions).
*
* https://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_url_parameters
*
* @param {Track} event
*/
Bronto.prototype.track = function(track){
var revenue = track.revenue();
var event = track.event();
var type = 'number' == typeof revenue ? '$' : 't';
this.bta.addConversionLegacy(type, event, revenue);
};
/**
* Completed order.
*
* The cookie is used to link the order being processed back to the delivery,
* message, and contact which makes it a conversion.
* Passing in just the email ensures that the order itself
* gets linked to the contact record in Bronto even if the user
* does not have a tracking cookie.
*
* @param {Track} track
* @api private
*/
Bronto.prototype.completedOrder = function(track){
var user = this.analytics.user();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
var email = identify.email();
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
item_id: track.id() || track.sku(),
desc: product.description || track.name(),
quantity: track.quantity(),
amount: track.price(),
});
});
// add conversion
this.bta.addOrder({
order_id: track.orderId(),
email: email,
// they recommend not putting in a date
// because it needs to be formatted correctly
// YYYY-MM-DDTHH:MM:SS
items: items
});
};
}, {"segmentio/analytics.js-integration":159,"facade":27,"load-pixel":185,"querystring":186,"each":5}],
185: [function(require, module, exports) {
/**
* Module dependencies.
*/
var stringify = require('querystring').stringify;
var sub = require('substitute');
/**
* Factory function to create a pixel loader.
*
* @param {String} path
* @return {Function}
* @api public
*/
module.exports = function(path){
return function(query, obj, fn){
if ('function' == typeof obj) fn = obj, obj = {};
obj = obj || {};
fn = fn || function(){};
var url = sub(path, obj);
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
query = stringify(query);
if (query) query = '?' + query;
img.src = url + query;
img.width = 1;
img.height = 1;
return img;
};
};
/**
* Create an error handler.
*
* @param {Fucntion} fn
* @param {String} message
* @param {Image} img
* @return {Function}
* @api private
*/
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
}, {"querystring":186,"substitute":187}],
186: [function(require, module, exports) {
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
}, {"trim":50,"type":35}],
187: [function(require, module, exports) {
/**
* Expose `substitute`
*/
module.exports = substitute;
/**
* Substitute `:prop` with the given `obj` in `str`
*
* @param {String} str
* @param {Object} obj
* @param {RegExp} expr
* @return {String}
* @api public
*/
function substitute(str, obj, expr){
if (!obj) throw new TypeError('expected an object');
expr = expr || /:(\w+)/g;
return str.replace(expr, function(_, prop){
return null != obj[prop]
? obj[prop]
: _;
});
}
}, {}],
92: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var tick = require('next-tick');
/**
* Expose `BugHerd` integration.
*/
var BugHerd = module.exports = integration('BugHerd')
.assumesPageview()
.global('BugHerdConfig')
.global('_bugHerd')
.option('apiKey', '')
.option('showFeedbackTab', true)
.tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');
/**
* Initialize.
*
* http://support.bugherd.com/home
*
* @param {Object} page
*/
BugHerd.prototype.initialize = function(page){
window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }};
var ready = this.ready;
this.load(function(){
tick(ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
BugHerd.prototype.loaded = function(){
return !! window._bugHerd;
};
}, {"segmentio/analytics.js-integration":159,"next-tick":45}],
93: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
var extend = require('extend');
var onError = require('on-error');
/**
* Expose `Bugsnag` integration.
*/
var Bugsnag = module.exports = integration('Bugsnag')
.global('Bugsnag')
.option('apiKey', '')
.tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');
/**
* Initialize.
*
* https://bugsnag.com/docs/notifiers/js
*
* @param {Object} page
*/
Bugsnag.prototype.initialize = function(page){
var self = this;
this.load(function(){
window.Bugsnag.apiKey = self.options.apiKey;
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bugsnag.prototype.loaded = function(){
return is.object(window.Bugsnag);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Bugsnag.prototype.identify = function(identify){
window.Bugsnag.metaData = window.Bugsnag.metaData || {};
extend(window.Bugsnag.metaData, identify.traits());
};
}, {"segmentio/analytics.js-integration":159,"is":18,"extend":40,"on-error":188}],
188: [function(require, module, exports) {
/**
* Expose `onError`.
*/
module.exports = onError;
/**
* Callbacks.
*/
var callbacks = [];
/**
* Preserve existing handler.
*/
if ('function' == typeof window.onerror) callbacks.push(window.onerror);
/**
* Bind to `window.onerror`.
*/
window.onerror = handler;
/**
* Error handler.
*/
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
/**
* Call a `fn` on `window.onerror`.
*
* @param {Function} fn
*/
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
}, {}],
94: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var defaults = require('defaults');
var onBody = require('on-body');
/**
* Expose `Chartbeat` integration.
*/
var Chartbeat = module.exports = integration('Chartbeat')
.assumesPageview()
.global('_sf_async_config')
.global('_sf_endpt')
.global('pSUPERFLY')
.option('domain', '')
.option('uid', null)
.tag('<script src="//static.chartbeat.com/js/chartbeat.js">');
/**
* Initialize.
*
* http://chartbeat.com/docs/configuration_variables/
*
* @param {Object} page
*/
Chartbeat.prototype.initialize = function(page){
var self = this;
window._sf_async_config = window._sf_async_config || {};
window._sf_async_config.useCanonical = true;
defaults(window._sf_async_config, this.options);
onBody(function(){
window._sf_endpt = new Date().getTime();
// Note: Chartbeat depends on document.body existing so the script does
// not load until that is confirmed. Otherwise it may trigger errors.
self.load(self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Chartbeat.prototype.loaded = function(){
return !! window.pSUPERFLY;
};
/**
* Page.
*
* http://chartbeat.com/docs/handling_virtual_page_changes/
*
* @param {Page} page
*/
Chartbeat.prototype.page = function(page){
var props = page.properties();
var name = page.fullName();
window.pSUPERFLY.virtualPage(props.path, name || props.title);
};
}, {"segmentio/analytics.js-integration":159,"defaults":189,"on-body":180}],
189: [function(require, module, exports) {
/**
* Expose `defaults`.
*/
module.exports = defaults;
function defaults (dest, defaults) {
for (var prop in defaults) {
if (! (prop in dest)) {
dest[prop] = defaults[prop];
}
}
return dest;
};
}, {}],
95: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_cbq');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Supported events
*/
var supported = {
activation: true,
changePlan: true,
register: true,
refund: true,
charge: true,
cancel: true,
login: true
};
/**
* Expose `ChurnBee` integration.
*/
var ChurnBee = module.exports = integration('ChurnBee')
.global('_cbq')
.global('ChurnBee')
.option('apiKey', '')
.tag('<script src="//api.churnbee.com/cb.js">')
.mapping('events');
/**
* Initialize.
*
* https://churnbee.com/docs
*
* @param {Object} page
*/
ChurnBee.prototype.initialize = function(page){
push('_setApiKey', this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
ChurnBee.prototype.loaded = function(){
return !! window.ChurnBee;
};
/**
* Track.
*
* @param {Track} event
*/
ChurnBee.prototype.track = function(track){
var event = track.event();
var events = this.events(event);
events.push(event);
each(events, function(event){
if (true != supported[event]) return;
push(event, track.properties({ revenue: 'amount' }));
});
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}],
190: [function(require, module, exports) {
/**
* Expose `generate`.
*/
module.exports = generate;
/**
* Generate a global queue pushing method with `name`.
*
* @param {String} name
* @param {Object} options
* @property {Boolean} wrap
* @return {Function}
*/
function generate (name, options) {
options = options || {};
return function (args) {
args = [].slice.call(arguments);
window[name] || (window[name] = []);
options.wrap === false
? window[name].push.apply(window[name], args)
: window[name].push(args);
};
}
}, {}],
96: [function(require, module, exports) {
/**
* Module dependencies.
*/
var date = require('load-date');
var domify = require('domify');
var each = require('each');
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
var useHttps = require('use-https');
var onBody = require('on-body');
/**
* Expose `ClickTale` integration.
*/
var ClickTale = module.exports = integration('ClickTale')
.assumesPageview()
.global('WRInitTime')
.global('ClickTale')
.global('ClickTaleSetUID')
.global('ClickTaleField')
.global('ClickTaleEvent')
.option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js')
.option('httpsCdnUrl', '')
.option('projectId', '')
.option('recordingRatio', 0.01)
.option('partitionId', '')
.tag('<script src="{{src}}">');
/**
* Initialize.
*
* http://wiki.clicktale.com/Article/JavaScript_API
*
* @param {Object} page
*/
ClickTale.prototype.initialize = function(page){
var self = this;
window.WRInitTime = date.getTime();
onBody(function(body){
body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'));
});
var http = this.options.httpCdnUrl;
var https = this.options.httpsCdnUrl;
if (useHttps() && !https) return this.debug('https option required');
var src = useHttps() ? https : http;
this.load({ src: src }, function(){
window.ClickTale(
self.options.projectId,
self.options.recordingRatio,
self.options.partitionId
);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
ClickTale.prototype.loaded = function(){
return is.fn(window.ClickTale);
};
/**
* Identify.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField
*
* @param {Identify} identify
*/
ClickTale.prototype.identify = function(identify){
var id = identify.userId();
window.ClickTaleSetUID(id);
each(identify.traits(), function(key, value){
window.ClickTaleField(key, value);
});
};
/**
* Track.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent
*
* @param {Track} track
*/
ClickTale.prototype.track = function(track){
window.ClickTaleEvent(track.event());
};
}, {"load-date":191,"domify":181,"each":5,"segmentio/analytics.js-integration":159,"is":18,"use-https":161,"on-body":180}],
191: [function(require, module, exports) {
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
}, {}],
97: [function(require, module, exports) {
/**
* Module dependencies.
*/
var Identify = require('facade').Identify;
var extend = require('extend');
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
/**
* Expose `Clicky` integration.
*/
var Clicky = module.exports = integration('Clicky')
.assumesPageview()
.global('clicky')
.global('clicky_site_ids')
.global('clicky_custom')
.option('siteId', null)
.tag('<script src="//static.getclicky.com/js"></script>');
/**
* Initialize.
*
* http://clicky.com/help/customization
*
* @param {Object} page
*/
Clicky.prototype.initialize = function(page){
var user = this.analytics.user();
window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId];
this.identify(new Identify({
userId: user.id(),
traits: user.traits()
}));
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Clicky.prototype.loaded = function(){
return is.object(window.clicky);
};
/**
* Page.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Page} page
*/
Clicky.prototype.page = function(page){
var properties = page.properties();
var category = page.category();
var name = page.fullName();
window.clicky.log(properties.path, name || properties.title);
};
/**
* Identify.
*
* @param {Identify} id (optional)
*/
Clicky.prototype.identify = function(identify){
window.clicky_custom = window.clicky_custom || {};
window.clicky_custom.session = window.clicky_custom.session || {};
extend(window.clicky_custom.session, identify.traits());
};
/**
* Track.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Track} event
*/
Clicky.prototype.track = function(track){
window.clicky.goal(track.event(), track.revenue());
};
}, {"facade":27,"extend":40,"segmentio/analytics.js-integration":159,"is":18}],
98: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var useHttps = require('use-https');
/**
* Expose `Comscore` integration.
*/
var Comscore = module.exports = integration('comScore')
.assumesPageview()
.global('_comscore')
.global('COMSCORE')
.option('c1', '2')
.option('c2', '')
.tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">')
.tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Comscore.prototype.initialize = function(page){
window._comscore = window._comscore || [this.options];
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Comscore.prototype.loaded = function(){
return !! window.COMSCORE;
};
}, {"segmentio/analytics.js-integration":159,"use-https":161}],
99: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `CrazyEgg` integration.
*/
var CrazyEgg = module.exports = integration('Crazy Egg')
.assumesPageview()
.global('CE2')
.option('accountNumber', '')
.tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');
/**
* Initialize.
*
* @param {Object} page
*/
CrazyEgg.prototype.initialize = function(page){
var number = this.options.accountNumber;
var path = number.slice(0,4) + '/' + number.slice(4);
var cache = Math.floor(new Date().getTime() / 3600000);
this.load({ path: path, cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
CrazyEgg.prototype.loaded = function(){
return !! window.CE2;
};
}, {"segmentio/analytics.js-integration":159}],
100: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_curebitq');
var Identify = require('facade').Identify;
var throttle = require('throttle');
var Track = require('facade').Track;
var iso = require('to-iso-string');
var clone = require('clone');
var each = require('each');
var bind = require('bind');
/**
* Expose `Curebit` integration.
*/
var Curebit = module.exports = integration('Curebit')
.global('_curebitq')
.global('curebit')
.option('siteId', '')
.option('iframeWidth', '100%')
.option('iframeHeight', '480')
.option('iframeBorder', 0)
.option('iframeId', 'curebit_integration')
.option('responsive', true)
.option('device', '')
.option('insertIntoId', '')
.option('campaigns', {})
.option('server', 'https://www.curebit.com')
.tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Curebit.prototype.initialize = function(page){
push('init', { site_id: this.options.siteId, server: this.options.server });
this.load(this.ready);
// throttle the call to `page` since curebit needs to append an iframe
this.page = throttle(bind(this, this.page), 250);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Curebit.prototype.loaded = function(){
return !!window.curebit;
};
/**
* Page.
*
* Call the `register_affiliate` method of the Curebit API that will load a
* custom iframe onto the page, only if this page's path is marked as a
* campaign.
*
* http://www.curebit.com/docs/affiliate/registration
*
* This is throttled to prevent accidentally drawing the iframe multiple times,
* from multiple `.page()` calls. The `250` is from the curebit script.
*
* @param {String} url
* @param {String} id
* @param {Function} fn
* @api private
*/
Curebit.prototype.injectIntoId = function(url, id, fn){
var server = this.options.server;
when(function(){
return document.getElementById(id);
}, function(){
var script = document.createElement('script');
script.src = url;
var parent = document.getElementById(id);
parent.appendChild(script);
onload(script, fn);
});
};
/**
* Campaign tags.
*
* @param {Page} page
*/
Curebit.prototype.page = function(page){
var user = this.analytics.user();
var campaigns = this.options.campaigns;
var path = window.location.pathname;
if (!campaigns[path]) return;
var tags = (campaigns[path] || '').split(',');
if (!tags.length) return;
var settings = {
responsive: this.options.responsive,
device: this.options.device,
campaign_tags: tags,
iframe: {
width: this.options.iframeWidth,
height: this.options.iframeHeight,
id: this.options.iframeId,
frameborder: this.options.iframeBorder,
container: this.options.insertIntoId
}
};
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
// if we have an email, add any information about the user
if (identify.email()) {
settings.affiliate_member = {
email: identify.email(),
first_name: identify.firstName(),
last_name: identify.lastName(),
customer_id: identify.userId()
};
}
push('register_affiliate', settings);
};
/**
* Completed order.
*
* Fire the Curebit `register_purchase` with the order details and items.
*
* https://www.curebit.com/docs/ecommerce/custom
*
* @param {Track} track
*/
Curebit.prototype.completedOrder = function(track){
var user = this.analytics.user();
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
traits: user.traits(),
userId: user.id()
});
each(products, function(product){
var track = new Track({ properties: product });
items.push({
product_id: track.id() || track.sku(),
quantity: track.quantity(),
image_url: product.image,
price: track.price(),
title: track.name(),
url: product.url,
});
});
push('register_purchase', {
order_date: iso(props.date || new Date()),
order_number: orderId,
coupon_code: track.coupon(),
subtotal: track.total(),
customer_id: identify.userId(),
first_name: identify.firstName(),
last_name: identify.lastName(),
email: identify.email(),
items: items
});
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"throttle":192,"to-iso-string":193,"clone":194,"each":5,"bind":33}],
192: [function(require, module, exports) {
/**
* Module exports.
*/
module.exports = throttle;
/**
* Returns a new function that, when invoked, invokes `func` at most one time per
* `wait` milliseconds.
*
* @param {Function} func The `Function` instance to wrap.
* @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations.
* @return {Function} A new function that wraps the `func` function passed in.
* @api public
*/
function throttle (func, wait) {
var rtn; // return value
var last = 0; // last invokation timestamp
return function throttled () {
var now = new Date().getTime();
var delta = now - last;
if (delta >= wait) {
rtn = func.apply(this, arguments);
last = now;
}
return rtn;
};
}
}, {}],
193: [function(require, module, exports) {
/**
* Expose `toIsoString`.
*/
module.exports = toIsoString;
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {String}
*/
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/**
* Pad a `number` with a ten's place zero.
*
* @param {Number} number
* @return {String}
*/
function pad (number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
}, {}],
194: [function(require, module, exports) {
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
}, {"type":35}],
101: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var convertDates = require('convert-dates');
var Identify = require('facade').Identify;
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `Customerio` integration.
*/
var Customerio = module.exports = integration('Customer.io')
.assumesPageview()
.global('_cio')
.option('siteId', '')
.tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');
/**
* Initialize.
*
* http://customer.io/docs/api/javascript.html
*
* @param {Object} page
*/
Customerio.prototype.initialize = function(page){
window._cio = window._cio || [];
(function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Customerio.prototype.loaded = function(){
return !! (window._cio && window._cio.pageHasLoaded);
};
/**
* Identify.
*
* http://customer.io/docs/api/javascript.html#section-Identify_customers
*
* @param {Identify} identify
*/
Customerio.prototype.identify = function(identify){
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
window._cio.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Customerio.prototype.group = function(group){
var traits = group.traits();
var user = this.analytics.user();
traits = alias(traits, function(trait){
return 'Group ' + trait;
});
this.identify(new Identify({
userId: user.id(),
traits: traits
}));
};
/**
* Track.
*
* http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
*
* @param {Track} track
*/
Customerio.prototype.track = function(track){
var properties = track.properties();
properties = convertDates(properties, convertDate);
window._cio.track(track.event(), properties);
};
/**
* Convert a date to the format Customer.io supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate(date){
return Math.floor(date.getTime() / 1000);
}
}, {"alias":195,"convert-dates":196,"facade":27,"segmentio/analytics.js-integration":159}],
195: [function(require, module, exports) {
var type = require('type');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `alias`.
*/
module.exports = alias;
/**
* Alias an `object`.
*
* @param {Object} obj
* @param {Mixed} method
*/
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
/**
* Convert the keys in an `obj` using a dictionary of `aliases`.
*
* @param {Object} obj
* @param {Object} aliases
*/
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
/**
* Convert the keys in an `obj` using a `convert` function.
*
* @param {Object} obj
* @param {Function} convert
*/
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
}, {"type":35,"clone":62}],
196: [function(require, module, exports) {
var is = require('is');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `convertDates`.
*/
module.exports = convertDates;
/**
* Recursively convert an `obj`'s dates to new values.
*
* @param {Object} obj
* @param {Function} convert
* @return {Object}
*/
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
}, {"is":18,"clone":14}],
102: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_dcq');
/**
* Expose `Drip` integration.
*/
var Drip = module.exports = integration('Drip')
.assumesPageview()
.global('dc')
.global('_dcq')
.global('_dcs')
.option('account', '')
.tag('<script src="//tag.getdrip.com/{{ account }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Drip.prototype.initialize = function(page){
window._dcq = window._dcq || [];
window._dcs = window._dcs || {};
window._dcs.account = this.options.account;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Drip.prototype.loaded = function(){
return is.object(window.dc);
};
/**
* Track.
*
* @param {Track} track
*/
Drip.prototype.track = function(track){
var props = track.properties();
var cents = Math.round(track.cents());
props.action = track.event();
if (cents) props.value = cents;
delete props.revenue;
push('track', props);
};
}, {"alias":195,"segmentio/analytics.js-integration":159,"is":18,"load-script":168,"global-queue":190}],
103: [function(require, module, exports) {
/**
* Module dependencies.
*/
var extend = require('extend');
var integration = require('segmentio/analytics.js-integration');
var onError = require('on-error');
var push = require('global-queue')('_errs');
/**
* Expose `Errorception` integration.
*/
var Errorception = module.exports = integration('Errorception')
.assumesPageview()
.global('_errs')
.option('projectId', '')
.option('meta', true)
.tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');
/**
* Initialize.
*
* https://github.com/amplitude/Errorception-Javascript
*
* @param {Object} page
*/
Errorception.prototype.initialize = function(page){
window._errs = window._errs || [this.options.projectId];
onError(push);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Errorception.prototype.loaded = function(){
return !! (window._errs && window._errs.push !== Array.prototype.push);
};
/**
* Identify.
*
* http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html
*
* @param {Object} identify
*/
Errorception.prototype.identify = function(identify){
if (!this.options.meta) return;
var traits = identify.traits();
window._errs = window._errs || [];
window._errs.meta = window._errs.meta || {};
extend(window._errs.meta, traits);
};
}, {"extend":40,"segmentio/analytics.js-integration":159,"on-error":188,"global-queue":190}],
104: [function(require, module, exports) {
/**
* Module dependencies.
*/
var each = require('each');
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_aaq');
/**
* Expose `Evergage` integration.integration.
*/
var Evergage = module.exports = integration('Evergage')
.assumesPageview()
.global('_aaq')
.option('account', '')
.option('dataset', '')
.tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Evergage.prototype.initialize = function(page){
var account = this.options.account;
var dataset = this.options.dataset;
window._aaq = window._aaq || [];
push('setEvergageAccount', account);
push('setDataset', dataset);
push('setUseSiteConfig', true);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Evergage.prototype.loaded = function(){
return !! (window._aaq && window._aaq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Evergage.prototype.page = function(page){
var props = page.properties();
var name = page.name();
if (name) push('namePage', name);
each(props, function(key, value){
push('setCustomField', key, value, 'page');
});
window.Evergage.init(true);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Evergage.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push('setUser', id);
var traits = identify.traits({
email: 'userEmail',
name: 'userName'
});
each(traits, function(key, value){
push('setUserField', key, value, 'page');
});
};
/**
* Group.
*
* @param {Group} group
*/
Evergage.prototype.group = function(group){
var props = group.traits();
var id = group.groupId();
if (!id) return;
push('setCompany', id);
each(props, function(key, value){
push('setAccountField', key, value, 'page');
});
};
/**
* Track.
*
* @param {Track} track
*/
Evergage.prototype.track = function(track){
push('trackAction', track.event(), track.properties());
};
}, {"each":5,"segmentio/analytics.js-integration":159,"global-queue":190}],
105: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_fbq');
var each = require('each');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Facebook`
*/
var Facebook = module.exports = integration('Facebook Ads')
.global('_fbq')
.option('currency', 'USD')
.tag('<script src="//connect.facebook.net/en_US/fbds.js">')
.mapping('events');
/**
* Initialize Facebook Ads.
*
* https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration
*
* @param {Object} page
*/
Facebook.prototype.initialize = function(page){
window._fbq = window._fbq || [];
this.load(this.ready);
window._fbq.loaded = true;
};
/**
* Loaded?
*
* @return {Boolean}
*/
Facebook.prototype.loaded = function(){
return !! (window._fbq && window._fbq.loaded);
};
/**
* Track.
*
* https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel
*
* @param {Track} track
*/
Facebook.prototype.track = function(track){
var event = track.event();
var events = this.events(event);
var revenue = track.revenue() || 0;
var self = this;
each(events, function(event){
push('track', event, {
value: String(revenue.toFixed(2)),
currency: self.options.currency
});
});
if (!events.length) {
var data = track.properties();
push('track', event, data);
}
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}],
106: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_fxm');
var integration = require('segmentio/analytics.js-integration');
var Track = require('facade').Track;
var each = require('each');
/**
* Expose `FoxMetrics` integration.
*/
var FoxMetrics = module.exports = integration('FoxMetrics')
.assumesPageview()
.global('_fxm')
.option('appId', '')
.tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');
/**
* Initialize.
*
* http://foxmetrics.com/documentation/apijavascript
*
* @param {Object} page
*/
FoxMetrics.prototype.initialize = function(page){
window._fxm = window._fxm || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
FoxMetrics.prototype.loaded = function(){
return !! (window._fxm && window._fxm.appId);
};
/**
* Page.
*
* @param {Page} page
*/
FoxMetrics.prototype.page = function(page){
var properties = page.proxy('properties');
var category = page.category();
var name = page.name();
this._category = category; // store for later
push(
'_fxm.pages.view',
properties.title, // title
name, // name
category, // category
properties.url, // url
properties.referrer // referrer
);
};
/**
* Identify.
*
* @param {Identify} identify
*/
FoxMetrics.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push(
'_fxm.visitor.profile',
id, // user id
identify.firstName(), // first name
identify.lastName(), // last name
identify.email(), // email
identify.address(), // address
undefined, // social
undefined, // partners
identify.traits() // attributes
);
};
/**
* Track.
*
* @param {Track} track
*/
FoxMetrics.prototype.track = function(track){
var props = track.properties();
var category = this._category || props.category;
push(track.event(), category, props);
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.viewedProduct = function(track){
ecommerce('productview', track);
};
/**
* Removed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.removedProduct = function(track){
ecommerce('removecartitem', track);
};
/**
* Added product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.addedProduct = function(track){
ecommerce('cartitem', track);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
// transaction
push(
'_fxm.ecommerce.order',
orderId,
track.subtotal(),
track.shipping(),
track.tax(),
track.city(),
track.state(),
track.zip(),
track.quantity()
);
// items
each(track.products(), function(product){
var track = new Track({ properties: product });
ecommerce('purchaseitem', track, [
track.quantity(),
track.price(),
orderId
]);
});
};
/**
* Track ecommerce `event` with `track`
* with optional `arr` to append.
*
* @param {String} event
* @param {Track} track
* @param {Array} arr
* @api private
*/
function ecommerce(event, track, arr){
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
}
}, {"global-queue":190,"segmentio/analytics.js-integration":159,"facade":27,"each":5}],
107: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var bind = require('bind');
var when = require('when');
var is = require('is');
/**
* Expose `Frontleaf` integration.
*/
var Frontleaf = module.exports = integration('Frontleaf')
.assumesPageview()
.global('_fl')
.global('_flBaseUrl')
.option('baseUrl', 'https://api.frontleaf.com')
.option('token', '')
.option('stream', '')
.option('trackNamedPages', false)
.option('trackCategorizedPages', false)
.tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');
/**
* Initialize.
*
* http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon
*
* @param {Object} page
*/
Frontleaf.prototype.initialize = function(page){
window._fl = window._fl || [];
window._flBaseUrl = window._flBaseUrl || this.options.baseUrl;
this._push('setApiToken', this.options.token);
this._push('setStream', this.options.stream);
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load({ baseUrl: window._flBaseUrl }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Frontleaf.prototype.loaded = function(){
return is.array(window._fl) && window._fl.ready === true;
};
/**
* Identify.
*
* @param {Identify} identify
*/
Frontleaf.prototype.identify = function(identify){
var userId = identify.userId();
if (userId) {
this._push('setUser', {
id: userId,
name: identify.name() || identify.username(),
data: clean(identify.traits())
});
}
};
/**
* Group.
*
* @param {Group} group
*/
Frontleaf.prototype.group = function(group){
var groupId = group.groupId();
if (groupId) {
this._push('setAccount', {
id: groupId,
name: group.proxy('traits.name'),
data: clean(group.traits())
});
}
};
/**
* Page.
*
* @param {Page} page
*/
Frontleaf.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* @param {Track} track
*/
Frontleaf.prototype.track = function(track){
var event = track.event();
this._push('event', event, clean(track.properties()));
};
/**
* Push a command onto the global Frontleaf queue.
*
* @param {String} command
* @return {Object} args
* @api private
*/
Frontleaf.prototype._push = function(command){
var args = [].slice.call(arguments, 1);
window._fl.push(function(t){ t[command].apply(command, args); });
};
/**
* Clean all nested objects and arrays.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function clean(obj){
var ret = {};
// Remove traits/properties that are already represented
// outside of the data container
var excludeKeys = ["id","name","firstName","lastName"];
var len = excludeKeys.length;
for (var i = 0; i < len; i++) {
clear(obj, excludeKeys[i]);
}
// Flatten nested hierarchy, preserving arrays
obj = flatten(obj);
// Discard nulls, represent arrays as comma-separated strings
for (var key in obj) {
var val = obj[key];
if (null == val) {
continue;
}
if (is.array(val)) {
ret[key] = val.toString();
continue;
}
ret[key] = val;
}
return ret;
}
/**
* Remove a property from an object if set.
*
* @param {Object} obj
* @param {String} key
* @api private
*/
function clear(obj, key){
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
/**
* Flatten a nested object into a single level space-delimited
* hierarchy.
*
* Based on https://github.com/hughsk/flat
*
* @param {Object} source
* @return {Object}
* @api private
*/
function flatten(source){
var output = {};
function step(object, prev){
for (var key in object) {
var value = object[key];
var newKey = prev ? prev + ' ' + key : key;
if (!is.array(value) && is.object(value)) {
return step(value, newKey);
}
output[newKey] = value;
}
}
step(source);
return output;
}
}, {"segmentio/analytics.js-integration":159,"bind":33,"when":184,"is":18}],
108: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_gauges');
/**
* Expose `Gauges` integration.
*/
var Gauges = module.exports = integration('Gauges')
.assumesPageview()
.global('_gauges')
.option('siteId', '')
.tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');
/**
* Initialize Gauges.
*
* http://get.gaug.es/documentation/tracking/
*
* @param {Object} page
*/
Gauges.prototype.initialize = function(page){
window._gauges = window._gauges || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Gauges.prototype.loaded = function(){
return !! (window._gauges && window._gauges.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Gauges.prototype.page = function(page){
push('track');
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190}],
109: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var onBody = require('on-body');
/**
* Expose `GetSatisfaction` integration.
*/
var GetSatisfaction = module.exports = integration('Get Satisfaction')
.assumesPageview()
.global('GSFN')
.option('widgetId', '')
.tag('<script src="https://loader.engage.gsfn.us/loader.js">');
/**
* Initialize.
*
* https://console.getsatisfaction.com/start/101022?signup=true#engage
*
* @param {Object} page
*/
GetSatisfaction.prototype.initialize = function(page){
var self = this;
var widget = this.options.widgetId;
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + widget;
onBody(function(body){ body.appendChild(div); });
// usually the snippet is sync, so wait for it before initializing the tab
this.load(function(){
window.GSFN.loadWidget(widget, { containerId: id });
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
GetSatisfaction.prototype.loaded = function(){
return !! window.GSFN;
};
}, {"segmentio/analytics.js-integration":159,"on-body":180}],
110: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_gaq');
var length = require('object').length;
var canonical = require('canonical');
var useHttps = require('use-https');
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var keys = require('object').keys;
var dot = require('obj-case');
var each = require('each');
var type = require('type');
var url = require('url');
var is = require('is');
var group;
var user;
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(GA);
group = analytics.group();
user = analytics.user();
};
/**
* Expose `GA` integration.
*
* http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
*/
var GA = exports.Integration = integration('Google Analytics')
.readyOnLoad()
.global('ga')
.global('gaplugins')
.global('_gaq')
.global('GoogleAnalyticsObject')
.option('anonymizeIp', false)
.option('classic', false)
.option('domain', 'none')
.option('doubleClick', false)
.option('enhancedLinkAttribution', false)
.option('ignoredReferrers', null)
.option('includeSearch', false)
.option('siteSpeedSampleRate', 1)
.option('trackingId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('sendUserId', false)
.option('metrics', {})
.option('dimensions', {})
.tag('library', '<script src="//www.google-analytics.com/analytics.js">')
.tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">')
.tag('http', '<script src="http://www.google-analytics.com/ga.js">')
.tag('https', '<script src="https://ssl.google-analytics.com/ga.js">');
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
GA.on('construct', function(integration){
if (!integration.options.classic) return;
integration.initialize = integration.initializeClassic;
integration.loaded = integration.loadedClassic;
integration.page = integration.pageClassic;
integration.track = integration.trackClassic;
integration.completedOrder = integration.completedOrderClassic;
});
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced
*/
GA.prototype.initialize = function(){
var opts = this.options;
// setup the tracker globals
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function(){
window.ga.q = window.ga.q || [];
window.ga.q.push(arguments);
};
window.ga.l = new Date().getTime();
window.ga('create', opts.trackingId, {
cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string
siteSpeedSampleRate: opts.siteSpeedSampleRate,
allowLinker: true
});
// display advertising
if (opts.doubleClick) {
window.ga('require', 'displayfeatures');
}
// send global id
if (opts.sendUserId && user.id()) {
window.ga('set', '&uid', user.id());
}
// anonymize after initializing, otherwise a warning is shown
// in google analytics debugger
if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true);
// custom dimensions & metrics
var custom = metrics(user.traits(), opts);
if (length(custom)) window.ga('set', custom);
this.load('library', this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
GA.prototype.loaded = function(){
return !! window.gaplugins;
};
/**
* Page.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
*
* @param {Page} page
*/
GA.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var pageview = {};
var track;
this._category = category; // store for later
// send
window.ga('send', 'pageview', {
page: path(props, this.options),
title: name || props.title,
location: props.url
});
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/events
* https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference
*
* @param {Track} event
*/
GA.prototype.track = function(track, options){
var opts = options || track.options(this.name);
var props = track.properties();
window.ga('send', 'event', {
eventAction: track.event(),
eventCategory: props.category || this._category || 'All',
eventLabel: props.label,
eventValue: formatValue(props.value || track.revenue()),
nonInteraction: props.noninteraction || opts.noninteraction
});
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrder = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
// require ecommerce
if (!this.ecommerce) {
window.ga('require', 'ecommerce', 'ecommerce.js');
this.ecommerce = true;
}
// add transaction
window.ga('ecommerce:addTransaction', {
affiliation: props.affiliation,
shipping: track.shipping(),
revenue: total,
tax: track.tax(),
id: orderId
});
// add products
each(products, function(product){
var track = new Track({ properties: product });
window.ga('ecommerce:addItem', {
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
sku: track.sku(),
id: orderId
});
});
// send
window.ga('ecommerce:send');
};
/**
* Initialize (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*/
GA.prototype.initializeClassic = function(){
var opts = this.options;
var anonymize = opts.anonymizeIp;
var db = opts.doubleClick;
var domain = opts.domain;
var enhanced = opts.enhancedLinkAttribution;
var ignore = opts.ignoredReferrers;
var sample = opts.siteSpeedSampleRate;
window._gaq = window._gaq || [];
push('_setAccount', opts.trackingId);
push('_setAllowLinker', true);
if (anonymize) push('_gat._anonymizeIp');
if (domain) push('_setDomainName', domain);
if (sample) push('_setSiteSpeedSampleRate', sample);
if (enhanced) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
push('_require', 'inpage_linkid', pluginUrl);
}
if (ignore) {
if (!is.array(ignore)) ignore = [ignore];
each(ignore, function (domain) {
push('_addIgnoredRef', domain);
});
}
if (this.options.doubleClick) {
this.load('double click', this.ready);
} else {
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
}
};
/**
* Loaded? (classic)
*
* @return {Boolean}
*/
GA.prototype.loadedClassic = function(){
return !! (window._gaq && window._gaq.push !== Array.prototype.push);
};
/**
* Page (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*
* @param {Page} page
*/
GA.prototype.pageClassic = function(page){
var opts = page.options(this.name);
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
push('_trackPageview', path(props, this.options));
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
*
* @param {Track} track
*/
GA.prototype.trackClassic = function(track, options){
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var category = this._category || props.category || 'All';
var label = props.label;
var value = formatValue(revenue || props.value);
var noninteraction = props.noninteraction || opts.noninteraction;
push('_trackEvent', category, event, label, value, noninteraction);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrderClassic = function(track){
var total = track.total() || track.revenue() || 0;
var orderId = track.orderId();
var products = track.products() || [];
var props = track.properties();
// required
if (!orderId) return;
// add transaction
push('_addTrans'
, orderId
, props.affiliation
, total
, track.tax()
, track.shipping()
, track.city()
, track.state()
, track.country());
// add items
each(products, function(product){
var track = new Track({ properties: product });
push('_addItem'
, orderId
, track.sku()
, track.name()
, track.category()
, track.price()
, track.quantity());
})
// send
push('_trackTrans');
};
/**
* Return the path based on `properties` and `options`.
*
* @param {Object} properties
* @param {Object} options
*/
function path(properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
/**
* Format the value property to Google's liking.
*
* @param {Number} value
* @return {Number}
*/
function formatValue(value) {
if (!value || value < 0) return 0;
return Math.round(value);
}
/**
* Map google's custom dimensions & metrics with `obj`.
*
* Example:
*
* metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } });
* // => { metric8: 1.9 }
*
* metrics({ revenue: 1.9 }, {});
* // => {}
*
* @param {Object} obj
* @param {Object} data
* @return {Object|null}
* @api private
*/
function metrics(obj, data){
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = names[i];
var key = metrics[name] || dimensions[name];
var value = dot(obj, name);
if (null == value) continue;
ret[key] = value;
}
return ret;
}
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"object":25,"canonical":13,"use-https":161,"facade":27,"callback":12,"load-script":168,"obj-case":60,"each":5,"type":35,"url":26,"is":18}],
111: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('dataLayer', { wrap: false });
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `GTM`.
*/
var GTM = module.exports = integration('Google Tag Manager')
.assumesPageview()
.global('dataLayer')
.global('google_tag_manager')
.option('containerId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');
/**
* Initialize.
*
* https://developers.google.com/tag-manager
*
* @param {Object} page
*/
GTM.prototype.initialize = function(){
push({ 'gtm.start': +new Date, event: 'gtm.js' });
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
GTM.prototype.loaded = function(){
return !! (window.dataLayer && [].push != window.dataLayer.push);
};
/**
* Page.
*
* @param {Page} page
* @api public
*/
GTM.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var track;
// all
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* https://developers.google.com/tag-manager/devguide#events
*
* @param {Track} track
* @api public
*/
GTM.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
push(props);
};
}, {"global-queue":190,"segmentio/analytics.js-integration":159}],
112: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var onBody = require('on-body');
var each = require('each');
/**
* Expose `GoSquared` integration.
*/
var GoSquared = module.exports = integration('GoSquared')
.assumesPageview()
.global('_gs')
.option('siteToken', '')
.option('anonymizeIP', false)
.option('cookieDomain', null)
.option('useCookies', true)
.option('trackHash', false)
.option('trackLocal', false)
.option('trackParams', true)
.tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');
/**
* Initialize.
*
* https://www.gosquared.com/developer/tracker
* Options: https://www.gosquared.com/developer/tracker/configuration
*
* @param {Object} page
*/
GoSquared.prototype.initialize = function(page){
var self = this;
var options = this.options;
var user = this.analytics.user();
push(options.siteToken);
each(options, function(name, value){
if ('siteToken' == name) return;
if (null == value) return;
push('set', name, value);
});
self.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
self.load(this.ready);
};
/**
* Loaded? (checks if the tracker version is set)
*
* @return {Boolean}
*/
GoSquared.prototype.loaded = function(){
return !! (window._gs && window._gs.v);
};
/**
* Page.
*
* https://www.gosquared.com/developer/tracker/pageviews
*
* @param {Page} page
*/
GoSquared.prototype.page = function(page){
var props = page.properties();
var name = page.fullName();
push('track', props.path, name || props.title)
};
/**
* Identify.
*
* https://www.gosquared.com/developer/tracker/tagging
*
* @param {Identify} identify
*/
GoSquared.prototype.identify = function(identify){
var traits = identify.traits({ userId: 'userID' });
var username = identify.username();
var email = identify.email();
var id = identify.userId();
if (id) push('set', 'visitorID', id);
var name = email || username || id;
if (name) push('set', 'visitorName', name);
push('set', 'visitor', traits);
};
/**
* Track.
*
* https://www.gosquared.com/developer/tracker/events
*
* @param {Track} track
*/
GoSquared.prototype.track = function(track){
push('event', track.event(), track.properties());
};
/**
* Checked out.
*
* @param {Track} track
* @api private
*/
GoSquared.prototype.completedOrder = function(track){
var products = track.products();
var items = [];
each(products, function(product){
var track = new Track({ properties: product });
items.push({
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
});
})
push('transaction', track.orderId(), {
revenue: track.total(),
track: true
}, items);
};
/**
* Push to `_gs.q`.
*
* @param {...} args
* @api private
*/
function push(){
var _gs = window._gs = window._gs || function(){
(_gs.q = _gs.q || []).push(arguments);
};
_gs.apply(null, arguments);
}
}, {"segmentio/analytics.js-integration":159,"facade":27,"callback":12,"load-script":168,"on-body":180,"each":5}],
113: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var alias = require('alias');
/**
* Expose `Heap` integration.
*/
var Heap = module.exports = integration('Heap')
.assumesPageview()
.global('heap')
.global('_heapid')
.option('apiKey', '')
.tag('<script src="//d36lvucg9kzous.cloudfront.net">');
/**
* Initialize.
*
* https://heapanalytics.com/docs#installWeb
*
* @param {Object} page
*/
Heap.prototype.initialize = function(page){
window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for (var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);};
window.heap.load(this.options.apiKey);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Heap.prototype.loaded = function(){
return (window.heap && window.heap.appid);
};
/**
* Identify.
*
* https://heapanalytics.com/docs#identify
*
* @param {Identify} identify
*/
Heap.prototype.identify = function(identify){
var traits = identify.traits();
var username = identify.username();
var id = identify.userId();
var handle = username || id;
if (handle) traits.handle = handle;
delete traits.username;
window.heap.identify(traits);
};
/**
* Track.
*
* https://heapanalytics.com/docs#track
*
* @param {Track} track
*/
Heap.prototype.track = function(track){
window.heap.track(track.event(), track.properties());
};
}, {"segmentio/analytics.js-integration":159,"alias":195}],
114: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `hellobar.com` integration.
*/
var Hellobar = module.exports = integration('Hello Bar')
.assumesPageview()
.global('_hbq')
.option('apiKey', '')
.tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');
/**
* Initialize.
*
* https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js
*
* @param {Object} page
*/
Hellobar.prototype.initialize = function(page){
window._hbq = window._hbq || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Hellobar.prototype.loaded = function(){
return !! (window._hbq && window._hbq.push !== Array.prototype.push);
};
}, {"segmentio/analytics.js-integration":159}],
115: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
/**
* Expose `HitTail` integration.
*/
var HitTail = module.exports = integration('HitTail')
.assumesPageview()
.global('htk')
.option('siteId', '')
.tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');
/**
* Initialize.
*
* @param {Object} page
*/
HitTail.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
HitTail.prototype.loaded = function(){
return is.fn(window.htk);
};
}, {"segmentio/analytics.js-integration":159,"is":18}],
116: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
/**
* Expose `hublo.com` integration.
*/
var Hublo = module.exports = integration('Hublo')
.assumesPageview()
.global('_hublo_')
.option('apiKey', null)
.tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">');
/**
* Initialize.
*
* https://cdn.hublo.co/5353a2e62b26c1277b000004.js
*
* @param {Object} page
*/
Hublo.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Hublo.prototype.loaded = function(){
return !! (window._hublo_ && typeof window._hublo_.setup === 'function');
};
}, {"analytics.js-integration":159}],
117: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_hsq');
var convert = require('convert-dates');
/**
* Expose `HubSpot` integration.
*/
var HubSpot = module.exports = integration('HubSpot')
.assumesPageview()
.global('_hsq')
.option('portalId', null)
.tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
HubSpot.prototype.initialize = function(page){
window._hsq = [];
var cache = Math.ceil(new Date() / 300000) * 300000;
this.load({ cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
HubSpot.prototype.loaded = function(){
return !! (window._hsq && window._hsq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
HubSpot.prototype.page = function(page){
push('_trackPageview');
};
/**
* Identify.
*
* @param {Identify} identify
*/
HubSpot.prototype.identify = function(identify){
if (!identify.email()) return;
var traits = identify.traits();
traits = convertDates(traits);
push('identify', traits);
};
/**
* Track.
*
* @param {Track} track
*/
HubSpot.prototype.track = function(track){
var props = track.properties();
props = convertDates(props);
push('trackEvent', track.event(), props);
};
/**
* Convert all the dates in the HubSpot properties to millisecond times
*
* @param {Object} properties
*/
function convertDates(properties){
return convert(properties, function(date){ return date.getTime(); });
}
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196}],
118: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var alias = require('alias');
/**
* Expose `Improvely` integration.
*/
var Improvely = module.exports = integration('Improvely')
.assumesPageview()
.global('_improvely')
.global('improvely')
.option('domain', '')
.option('projectId', null)
.tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');
/**
* Initialize.
*
* http://www.improvely.com/docs/landing-page-code
*
* @param {Object} page
*/
Improvely.prototype.initialize = function(page){
window._improvely = [];
window.improvely = { init: function(e, t){ window._improvely.push(["init", e, t]); }, goal: function(e){ window._improvely.push(["goal", e]); }, label: function(e){ window._improvely.push(["label", e]); }};
var domain = this.options.domain;
var id = this.options.projectId;
window.improvely.init(domain, id);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Improvely.prototype.loaded = function(){
return !! (window.improvely && window.improvely.identify);
};
/**
* Identify.
*
* http://www.improvely.com/docs/labeling-visitors
*
* @param {Identify} identify
*/
Improvely.prototype.identify = function(identify){
var id = identify.userId();
if (id) window.improvely.label(id);
};
/**
* Track.
*
* http://www.improvely.com/docs/conversion-code
*
* @param {Track} track
*/
Improvely.prototype.track = function(track){
var props = track.properties({ revenue: 'amount' });
props.type = track.event();
window.improvely.goal(props);
};
}, {"segmentio/analytics.js-integration":159,"alias":195}],
119: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('analytics.js-integration');
var push = require('global-queue')('_iva');
var is = require('is');
/**
* Expose `InsideVault` integration.
*/
var InsideVault = module.exports = integration('InsideVault')
.global('_iva')
.option('clientId', '')
.option('domain', '')
.tag('<script src="//analytics.staticiv.com/iva.js">');
/**
* Initialize.
*
* @param page
*/
InsideVault.prototype.initialize = function(page){
var domain = this.options.domain;
window._iva = window._iva || [];
push('setClientId', this.options.clientId);
if (domain) push('setDomain', domain);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
InsideVault.prototype.loaded = function(){
return !! (window._iva && window._iva.push !== Array.prototype.push);
};
/**
* Track.
*
* Tracks everything except 'sale' events.
*
* @param {Track} track
*/
InsideVault.prototype.track = function(track){
var event = track.event();
var value = track.revenue() || track.value() || 0;
var orderId = track.orderId() || '';
// 'sale' is a special event that will be routed to a table that is deprecated on our end.
// We don't want a generic 'sale' event to go to our deprecated table.
if (event != 'sale') {
push('trackEvent', event, value, orderId);
}
};
}, {"analytics.js-integration":159,"global-queue":190,"is":18}],
120: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('__insp');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `Inspectlet` integration.
*/
var Inspectlet = module.exports = integration('Inspectlet')
.assumesPageview()
.global('__insp')
.global('__insp_')
.option('wid', '')
.tag('<script src="//www.inspectlet.com/inspectlet.js">');
/**
* Initialize.
*
* https://www.inspectlet.com/dashboard/embedcode/1492461759/initial
*
* @param {Object} page
*/
Inspectlet.prototype.initialize = function(page){
push('wid', this.options.wid);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Inspectlet.prototype.loaded = function(){
return !! window.__insp_;
};
/**
* Identify.
*
* http://www.inspectlet.com/docs#tagging
*
* @param {Identify} identify
*/
Inspectlet.prototype.identify = function (identify) {
var traits = identify.traits({ id: 'userid' });
push('tagSession', traits);
};
/**
* Track.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.track = function(track){
push('tagSession', track.event());
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"alias":195,"clone":194}],
121: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var convertDates = require('convert-dates');
var defaults = require('defaults');
var isEmail = require('is-email');
var load = require('load-script');
var empty = require('is-empty');
var alias = require('alias');
var each = require('each');
var when = require('when');
var is = require('is');
/**
* Expose `Intercom` integration.
*/
var Intercom = module.exports = integration('Intercom')
.assumesPageview()
.global('Intercom')
.option('activator', '#IntercomDefaultWidget')
.option('appId', '')
.option('inbox', false)
.tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');
/**
* Initialize.
*
* http://docs.intercom.io/
* http://docs.intercom.io/#IntercomJS
*
* @param {Object} page
*/
Intercom.prototype.initialize = function(page){
var self = this;
this.load(function(){
when(function(){ return self.loaded(); }, self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Intercom.prototype.loaded = function(){
return is.fn(window.Intercom);
};
/**
* Page.
*
* @param {Page} page
*/
Intercom.prototype.page = function(page){
window.Intercom('update');
};
/**
* Identify.
*
* http://docs.intercom.io/#IntercomJS
*
* @param {Identify} identify
*/
Intercom.prototype.identify = function(identify){
var traits = identify.traits({ userId: 'user_id' });
var activator = this.options.activator;
var opts = identify.options(this.name);
var companyCreated = identify.companyCreated();
var created = identify.created();
var email = identify.email();
var name = identify.name();
var id = identify.userId();
var group = this.analytics.group();
if (!id && !traits.email) return; // one is required
traits.app_id = this.options.appId;
// intercom requires `company` to be an object. default it with group traits
// so that we guarantee an `id` is there, since they require it
if (null != traits.company && !is.object(traits.company)) delete traits.company;
if (traits.company) defaults(traits.company, group.traits());
// name
if (name) traits.name = name;
// handle dates
if (traits.company && companyCreated) traits.company.created = companyCreated;
if (created) traits.created = created;
// convert dates
traits = convertDates(traits, formatDate);
traits = alias(traits, { created: 'created_at'});
if (traits.company) traits.company = alias(traits.company, { created: 'created_at' });
// handle options
if (opts.increments) traits.increments = opts.increments;
if (opts.userHash) traits.user_hash = opts.userHash;
if (opts.user_hash) traits.user_hash = opts.user_hash;
// Intercom, will force the widget to appear
// if the selector is #IntercomDefaultWidget
// so no need to check inbox, just need to check
// that the selector isn't #IntercomDefaultWidget.
if ('#IntercomDefaultWidget' != activator) {
traits.widget = { activator: activator };
}
var method = this._id !== id ? 'boot': 'update';
this._id = id; // cache for next time
window.Intercom(method, traits);
};
/**
* Group.
*
* @param {Group} group
*/
Intercom.prototype.group = function(group){
var props = group.properties();
var id = group.groupId();
if (id) props.id = id;
window.Intercom('update', { company: props });
};
/**
* Track.
*
* @param {Track} track
*/
Intercom.prototype.track = function(track){
window.Intercom('trackEvent', track.event(), track.properties());
};
/**
* Format a date to Intercom's liking.
*
* @param {Date} date
* @return {Number}
*/
function formatDate(date) {
return Math.floor(date / 1000);
}
}, {"segmentio/analytics.js-integration":159,"convert-dates":196,"defaults":189,"is-email":19,"load-script":168,"is-empty":44,"alias":195,"each":5,"when":184,"is":18}],
122: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `Keen IO` integration.
*/
var Keen = module.exports = integration('Keen IO')
.global('Keen')
.option('projectId', '')
.option('readKey', '')
.option('writeKey', '')
.option('trackNamedPages', true)
.option('trackAllPages', false)
.option('trackCategorizedPages', true)
.tag('<script src="//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js">');
/**
* Initialize.
*
* https://keen.io/docs/
*/
Keen.prototype.initialize = function(){
var options = this.options;
window.Keen = window.Keen||{ configure:function(e){this._cf=e;}, addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);}, setGlobalProperties:function(e){this._gp=e;}, onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}};
window.Keen.configure({
projectId: options.projectId,
writeKey: options.writeKey,
readKey: options.readKey
});
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Keen.prototype.loaded = function(){
return !! (window.Keen && window.Keen.Base64);
};
/**
* Page.
*
* @param {Page} page
*/
Keen.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* TODO: migrate from old `userId` to simpler `id`
*
* @param {Identify} identify
*/
Keen.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
var user = {};
if (id) user.userId = id;
if (traits) user.traits = traits;
window.Keen.setGlobalProperties(function(){
return { user: user };
});
};
/**
* Track.
*
* @param {Track} track
*/
Keen.prototype.track = function(track){
window.Keen.addEvent(track.event(), track.properties());
};
}, {"segmentio/analytics.js-integration":159}],
123: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var indexof = require('indexof');
var is = require('is');
/**
* Expose `Kenshoo` integration.
*/
var Kenshoo = module.exports = integration('Kenshoo')
.global('k_trackevent')
.option('cid', '')
.option('subdomain', '')
.option('events', [])
.tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');
/**
* Initialize.
*
* See https://gist.github.com/justinboyle/7875832
*
* @param {Object} page
*/
Kenshoo.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded? (checks if the tracking function is set)
*
* @return {Boolean}
*/
Kenshoo.prototype.loaded = function(){
return is.fn(window.k_trackevent);
};
/**
* Track.
*
* Only tracks events if they are listed in the events array option.
* We've asked for docs a few times but no go :/
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} event
*/
Kenshoo.prototype.track = function(track){
var events = this.options.events;
var traits = track.traits();
var event = track.event();
var revenue = track.revenue() || 0;
if (!~indexof(events, event)) return;
var params = [
'id=' + this.options.cid,
'type=conv',
'val=' + revenue,
'orderId=' + track.orderId(),
'promoCode=' + track.coupon(),
'valueCurrency=' + track.currency(),
// Live tracking fields. Ignored for now (until we get documentation).
'GCID=',
'kw=',
'product='
];
window.k_trackevent(params, this.options.subdomain);
};
}, {"segmentio/analytics.js-integration":159,"indexof":46,"is":18}],
124: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_kmq');
var Track = require('facade').Track;
var alias = require('alias');
var Batch = require('batch');
var each = require('each');
var is = require('is');
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = module.exports = integration('KISSmetrics')
.assumesPageview()
.global('_kmq')
.global('KM')
.global('_kmil')
.option('apiKey', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('prefixProperties', true)
.tag('useless', '<script src="//i.kissmetrics.com/i.js">')
.tag('library', '<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');
/**
* Check if browser is mobile, for kissmetrics.
*
* http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile
*/
exports.isMobile = navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/iPhone|iPod/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/Opera Mini/i)
|| navigator.userAgent.match(/IEMobile/i);
/**
* Initialize.
*
* http://support.kissmetrics.com/apis/javascript
*
* @param {Object} page
*/
KISSmetrics.prototype.initialize = function(page){
var self = this;
window._kmq = [];
if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' });
var batch = new Batch();
batch.push(function(done){ self.load('useless', done); }) // :)
batch.push(function(done){ self.load('library', done); })
batch.end(function(){
self.trackPage(page);
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function(){
return is.object(window.KM);
};
/**
* Page.
*
* @param {Page} page
*/
KISSmetrics.prototype.page = function(page){
if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView();
this.trackPage(page);
};
/**
* Track page.
*
* @param {Page} page
*/
KISSmetrics.prototype.trackPage = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function(track){
var mapping = { revenue: 'Billing Amount' };
var event = track.event();
var properties = track.properties(mapping);
if (this.options.prefixProperties) properties = prefix(event, properties);
push('record', event, properties);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function(alias){
push('alias', alias.to(), alias.from());
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track){
var products = track.products();
var event = track.event();
// transaction
push('record', event, prefix(event, track.properties()));
// items
window._kmq.push(function(){
var km = window.KM;
each(products, function(product, i){
var temp = new Track({ event: event, properties: product });
var item = prefix(event, product);
item._t = km.ts() + i;
item._d = 1;
km.set(item);
});
});
};
/**
* Prefix properties with the event name.
*
* @param {String} event
* @param {Object} properties
* @return {Object} prefixed
* @api private
*/
function prefix(event, properties){
var prefixed = {};
each(properties, function(key, val){
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"alias":195,"batch":197,"each":5,"is":18}],
197: [function(require, module, exports) {
/**
* Module dependencies.
*/
try {
var EventEmitter = require('events').EventEmitter;
} catch (err) {
var Emitter = require('emitter');
}
/**
* Noop.
*/
function noop(){}
/**
* Expose `Batch`.
*/
module.exports = Batch;
/**
* Create a new Batch.
*/
function Batch() {
if (!(this instanceof Batch)) return new Batch;
this.fns = [];
this.concurrency(Infinity);
this.throws(true);
for (var i = 0, len = arguments.length; i < len; ++i) {
this.push(arguments[i]);
}
}
/**
* Inherit from `EventEmitter.prototype`.
*/
if (EventEmitter) {
Batch.prototype.__proto__ = EventEmitter.prototype;
} else {
Emitter(Batch.prototype);
}
/**
* Set concurrency to `n`.
*
* @param {Number} n
* @return {Batch}
* @api public
*/
Batch.prototype.concurrency = function(n){
this.n = n;
return this;
};
/**
* Queue a function.
*
* @param {Function} fn
* @return {Batch}
* @api public
*/
Batch.prototype.push = function(fn){
this.fns.push(fn);
return this;
};
/**
* Set wether Batch will or will not throw up.
*
* @param {Boolean} throws
* @return {Batch}
* @api public
*/
Batch.prototype.throws = function(throws) {
this.e = !!throws;
return this;
};
/**
* Execute all queued functions in parallel,
* executing `cb(err, results)`.
*
* @param {Function} cb
* @return {Batch}
* @api public
*/
Batch.prototype.end = function(cb){
var self = this
, total = this.fns.length
, pending = total
, results = []
, errors = []
, cb = cb || noop
, fns = this.fns
, max = this.n
, throws = this.e
, index = 0
, done;
// empty
if (!fns.length) return cb(null, results);
// process
function next() {
var i = index++;
var fn = fns[i];
if (!fn) return;
var start = new Date;
try {
fn(callback);
} catch (err) {
callback(err);
}
function callback(err, res){
if (done) return;
if (err && throws) return done = true, cb(err);
var complete = total - pending + 1;
var end = new Date;
results[i] = res;
errors[i] = err;
self.emit('progress', {
index: i,
value: res,
error: err,
pending: pending,
total: total,
complete: complete,
percent: complete / total * 100 | 0,
start: start,
end: end,
duration: end - start
});
if (--pending) next()
else if(!throws) cb(errors, results);
else cb(null, results);
}
}
// concurrency
for (var i = 0; i < fns.length; i++) {
if (i == max) break;
next();
}
return this;
};
}, {"emitter":198}],
198: [function(require, module, exports) {
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
}, {}],
125: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_learnq');
var tick = require('next-tick');
var alias = require('alias');
/**
* Trait aliases.
*/
var aliases = {
id: '$id',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
phone: '$phone_number',
title: '$title'
};
/**
* Expose `Klaviyo` integration.
*/
var Klaviyo = module.exports = integration('Klaviyo')
.assumesPageview()
.global('_learnq')
.option('apiKey', '')
.tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');
/**
* Initialize.
*
* https://www.klaviyo.com/docs/getting-started
*
* @param {Object} page
*/
Klaviyo.prototype.initialize = function(page){
var self = this;
push('account', this.options.apiKey);
this.load(function(){
tick(self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Klaviyo.prototype.loaded = function(){
return !! (window._learnq && window._learnq.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Klaviyo.prototype.identify = function(identify){
var traits = identify.traits(aliases);
if (!traits.$id && !traits.$email) return;
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
Klaviyo.prototype.group = function(group){
var props = group.properties();
if (!props.name) return;
push('identify', { $organization: props.name });
};
/**
* Track.
*
* @param {Track} track
*/
Klaviyo.prototype.track = function(track){
push('track', track.event(), track.properties({
revenue: '$value'
}));
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"next-tick":45,"alias":195}],
126: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `LeadLander` integration.
*/
var LeadLander = module.exports = integration('LeadLander')
.assumesPageview()
.global('llactid')
.global('trackalyzer')
.option('accountId', null)
.tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');
/**
* Initialize.
*
* @param {Object} page
*/
LeadLander.prototype.initialize = function(page){
window.llactid = this.options.accountId;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
LeadLander.prototype.loaded = function(){
return !! window.trackalyzer;
};
}, {"segmentio/analytics.js-integration":159}],
127: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var clone = require('clone');
var each = require('each');
var when = require('when');
/**
* Expose `LiveChat` integration.
*/
var LiveChat = module.exports = integration('LiveChat')
.assumesPageview()
.global('__lc')
.global('__lc_inited')
.global('LC_API')
.global('LC_Invite')
.option('group', 0)
.option('license', '')
.tag('<script src="//cdn.livechatinc.com/tracking.js">');
/**
* Initialize.
*
* http://www.livechatinc.com/api/javascript-api
*
* @param {Object} page
*/
LiveChat.prototype.initialize = function(page){
var self = this;
window.__lc = clone(this.options);
this.load(function(){
when(function(){ return self.loaded(); }, self.ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
LiveChat.prototype.loaded = function(){
return !!(window.LC_API && window.LC_Invite);
};
/**
* Identify.
*
* @param {Identify} identify
*/
LiveChat.prototype.identify = function(identify){
var traits = identify.traits({ userId: 'User ID' });
window.LC_API.set_custom_variables(convert(traits));
};
/**
* Convert a traits object into the format LiveChat requires.
*
* @param {Object} traits
* @return {Array}
*/
function convert(traits){
var arr = [];
each(traits, function(key, value){
arr.push({ name: key, value: value });
});
return arr;
}
}, {"segmentio/analytics.js-integration":159,"clone":194,"each":5,"when":184}],
128: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var Identify = require('facade').Identify;
var useHttps = require('use-https');
/**
* Expose `LuckyOrange` integration.
*/
var LuckyOrange = module.exports = integration('Lucky Orange')
.assumesPageview()
.global('_loq')
.global('__wtw_watcher_added')
.global('__wtw_lucky_site_id')
.global('__wtw_lucky_is_segment_io')
.global('__wtw_custom_user_data')
.option('siteId', null)
.tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">')
.tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');
/**
* Initialize.
*
* @param {Object} page
*/
LuckyOrange.prototype.initialize = function(page){
var user = this.analytics.user();
window._loq || (window._loq = []);
window.__wtw_lucky_site_id = this.options.siteId;
this.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
var cache = Math.floor(new Date().getTime() / 60000);
var name = useHttps() ? 'https' : 'http';
this.load(name, { cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
LuckyOrange.prototype.loaded = function(){
return !! window.__wtw_watcher_added;
};
/**
* Identify.
*
* @param {Identify} identify
*/
LuckyOrange.prototype.identify = function(identify){
var traits = identify.traits();
var email = identify.email();
var name = identify.name();
if (name) traits.name = name;
if (email) traits.email = email;
window.__wtw_custom_user_data = traits;
};
}, {"segmentio/analytics.js-integration":159,"facade":27,"use-https":161}],
129: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var alias = require('alias');
/**
* Expose `Lytics` integration.
*/
var Lytics = module.exports = integration('Lytics')
.global('jstag')
.option('cid', '')
.option('cookie', 'seerid')
.option('delay', 2000)
.option('sessionTimeout', 1800)
.option('url', '//c.lytics.io')
.tag('<script src="//c.lytics.io/static/io.min.js">');
/**
* Options aliases.
*/
var aliases = {
sessionTimeout: 'sessecs'
};
/**
* Initialize.
*
* http://admin.lytics.io/doc#jstag
*
* @param {Object} page
*/
Lytics.prototype.initialize = function(page){
var options = alias(this.options, aliases);
window.jstag = (function(){var t = { _q: [], _c: options, ts: (new Date()).getTime() }; t.send = function(){this._q.push(['ready', 'send', Array.prototype.slice.call(arguments)]); return this; }; return t; })();
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Lytics.prototype.loaded = function(){
return !! (window.jstag && window.jstag.bind);
};
/**
* Page.
*
* @param {Page} page
*/
Lytics.prototype.page = function(page){
window.jstag.send(page.properties());
};
/**
* Idenfity.
*
* @param {Identify} identify
*/
Lytics.prototype.identify = function(identify){
var traits = identify.traits({ userId: '_uid' });
window.jstag.send(traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Lytics.prototype.track = function(track){
var props = track.properties();
props._e = track.event();
window.jstag.send(props);
};
}, {"segmentio/analytics.js-integration":159,"alias":195}],
130: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var clone = require('clone');
var dates = require('convert-dates');
var integration = require('segmentio/analytics.js-integration');
var iso = require('to-iso-string');
var indexof = require('indexof');
var del = require('obj-case').del;
/**
* Expose `Mixpanel` integration.
*/
var Mixpanel = module.exports = integration('Mixpanel')
.global('mixpanel')
.option('increments', [])
.option('cookieName', '')
.option('nameTag', true)
.option('pageview', false)
.option('people', false)
.option('token', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');
/**
* Options aliases.
*/
var optionsAliases = {
cookieName: 'cookie_name'
};
/**
* Initialize.
*
* https://mixpanel.com/help/reference/javascript#installing
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init
*/
Mixpanel.prototype.initialize = function(){
(function(c, a){window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function(b, c, f){function d(a, b){var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function(){a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []);
this.options.increments = lowercase(this.options.increments);
var options = alias(this.options, optionsAliases);
window.mixpanel.init(options.token, options);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mixpanel.prototype.loaded = function(){
return !! (window.mixpanel && window.mixpanel.config);
};
/**
* Page.
*
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Mixpanel.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Trait aliases.
*/
var traitAliases = {
created: '$created',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
lastSeen: '$last_seen',
name: '$name',
username: '$username',
phone: '$phone'
};
/**
* Identify.
*
* https://mixpanel.com/help/reference/javascript#super-properties
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript#storing-user-profiles
*
* @param {Identify} identify
*/
Mixpanel.prototype.identify = function(identify){
var username = identify.username();
var email = identify.email();
var id = identify.userId();
// id
if (id) window.mixpanel.identify(id);
// name tag
var nametag = email || username || id;
if (nametag) window.mixpanel.name_tag(nametag);
// traits
var traits = identify.traits(traitAliases);
if (traits.$created) del(traits, 'createdAt');
window.mixpanel.register(traits);
if (this.options.people) window.mixpanel.people.set(traits);
};
/**
* Track.
*
* https://mixpanel.com/help/reference/javascript#sending-events
* https://mixpanel.com/help/reference/javascript#tracking-revenue
*
* @param {Track} track
*/
Mixpanel.prototype.track = function(track){
var increments = this.options.increments;
var increment = track.event().toLowerCase();
var people = this.options.people;
var props = track.properties();
var revenue = track.revenue();
// delete mixpanel's reserved properties, so they don't conflict
delete props.distinct_id;
delete props.ip;
delete props.mp_name_tag;
delete props.mp_note;
delete props.token;
// increment properties in mixpanel people
if (people && ~indexof(increments, increment)) {
window.mixpanel.people.increment(track.event());
window.mixpanel.people.set('Last ' + track.event(), new Date);
}
// track the event
props = dates(props, iso);
window.mixpanel.track(track.event(), props);
// track revenue specifically
if (revenue && people) {
window.mixpanel.people.track_charge(revenue);
}
};
/**
* Alias.
*
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias
*
* @param {Alias} alias
*/
Mixpanel.prototype.alias = function(alias){
var mp = window.mixpanel;
var to = alias.to();
if (mp.get_distinct_id && mp.get_distinct_id() === to) return;
// HACK: internal mixpanel API to ensure we don't overwrite
if (mp.get_property && mp.get_property('$people_distinct_id') === to) return;
// although undocumented, mixpanel takes an optional original id
mp.alias(to, alias.from());
};
/**
* Lowercase the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function lowercase(arr){
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
}
}, {"alias":195,"clone":194,"convert-dates":196,"segmentio/analytics.js-integration":159,"to-iso-string":193,"indexof":46,"obj-case":60}],
131: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var bind = require('bind');
var when = require('when');
var is = require('is');
/**
* Expose `Mojn`
*/
var Mojn = module.exports = integration('Mojn')
.option('customerCode', '')
.global('_mojnTrack')
.tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Mojn.prototype.initialize = function(){
window._mojnTrack = window._mojnTrack || [];
window._mojnTrack.push({ cid: this.options.customerCode });
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mojn.prototype.loaded = function(){
return is.object(window._mojnTrack);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Mojn.prototype.identify = function(identify){
var email = identify.email();
if (!email) return;
var img = new Image();
img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email;
img.width = 1;
img.height = 1;
return img;
};
/**
* Track.
*
* @param {Track} event
*/
Mojn.prototype.track = function(track){
var properties = track.properties();
var revenue = properties.revenue;
var currency = properties.currency || '';
var conv = currency + revenue;
if (!revenue) return;
window._mojnTrack.push({ conv: conv });
return conv;
};
}, {"segmentio/analytics.js-integration":159,"bind":33,"when":184,"is":18}],
132: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_mfq');
var integration = require('segmentio/analytics.js-integration');
var each = require('each');
/**
* Expose `Mouseflow`.
*/
var Mouseflow = module.exports = integration('Mouseflow')
.assumesPageview()
.global('mouseflow')
.global('_mfq')
.option('apiKey', '')
.option('mouseflowHtmlDelay', 0)
.tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');
/**
* Initalize.
*
* @param {Object} page
*/
Mouseflow.prototype.initialize = function(page){
window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mouseflow.prototype.loaded = function(){
return !! window.mouseflow;
};
/**
* Page.
*
* http://mouseflow.zendesk.com/entries/22528817-Single-page-websites
*
* @param {Page} page
*/
Mouseflow.prototype.page = function(page){
if (!window.mouseflow) return;
if ('function' != typeof mouseflow.newPageView) return;
mouseflow.newPageView();
};
/**
* Identify.
*
* http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Identify} identify
*/
Mouseflow.prototype.identify = function(identify){
set(identify.traits());
};
/**
* Track.
*
* http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Track} track
*/
Mouseflow.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
set(props);
};
/**
* Push each key and value in the given `obj` onto the queue.
*
* @param {Object} obj
*/
function set(obj){
each(obj, function(key, value){
push('setVariable', key, value);
});
}
}, {"global-queue":190,"segmentio/analytics.js-integration":159,"each":5}],
133: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var useHttps = require('use-https');
var each = require('each');
var is = require('is');
/**
* Expose `MouseStats` integration.
*/
var MouseStats = module.exports = integration('MouseStats')
.assumesPageview()
.global('msaa')
.global('MouseStatsVisitorPlaybacks')
.option('accountNumber', '')
.tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">')
.tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');
/**
* Initialize.
*
* http://www.mousestats.com/docs/pages/allpages
*
* @param {Object} page
*/
MouseStats.prototype.initialize = function(page){
var number = this.options.accountNumber;
var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number;
var cache = Math.floor(new Date().getTime() / 60000);
var name = useHttps() ? 'https' : 'http';
this.load(name, { path: path, cache: cache }, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
MouseStats.prototype.loaded = function(){
return is.array(window.MouseStatsVisitorPlaybacks);
};
/**
* Identify.
*
* http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks
*
* @param {Identify} identify
*/
MouseStats.prototype.identify = function(identify){
each(identify.traits(), function (key, value) {
window.MouseStatsVisitorPlaybacks.customVariable(key, value);
});
};
}, {"segmentio/analytics.js-integration":159,"use-https":161,"each":5,"is":18}],
134: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('__nls');
/**
* Expose `Navilytics` integration.
*/
var Navilytics = module.exports = integration('Navilytics')
.assumesPageview()
.global('__nls')
.option('memberId', '')
.option('projectId', '')
.tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');
/**
* Initialize.
*
* https://www.navilytics.com/member/code_settings
*
* @param {Object} page
*/
Navilytics.prototype.initialize = function(page){
window.__nls = window.__nls || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Navilytics.prototype.loaded = function(){
return !! (window.__nls && [].push != window.__nls.push);
};
/**
* Track.
*
* https://www.navilytics.com/docs#tags
*
* @param {Track} track
*/
Navilytics.prototype.track = function(track){
push('tagRecording', track.event());
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190}],
135: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var https = require('use-https');
var tick = require('next-tick');
/**
* Expose `Olark` integration.
*/
var Olark = module.exports = integration('Olark')
.assumesPageview()
.global('olark')
.option('identify', true)
.option('page', true)
.option('siteId', '')
.option('groupId', '')
.option('track', false);
/**
* Initialize.
*
* http://www.olark.com/documentation
* https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup
*
* @param {Object} page
*/
Olark.prototype.initialize = function(page){
var self = this;
this.load(function(){
tick(self.ready);
});
// assign chat to a specific site
var groupId = this.options.groupId;
if (groupId) {
chat('setOperatorGroup', { group: groupId });
}
// keep track of the widget's open state
var self = this;
box('onExpand', function(){ self._open = true; });
box('onShrink', function(){ self._open = false; });
};
/**
* Loaded?
*
* @return {Boolean}
*/
Olark.prototype.loaded = function(){
return !! window.olark;
};
/**
* Load.
*
* @param {Function} callback
*/
Olark.prototype.load = function(callback){
var el = document.getElementById('olark');
//if (!el) {
window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while (q--) {(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={ 0:+new Date() };a.P=function(u){a.p[u]=new Date()-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return ["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if (!m) {return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if (/MSIE[ ]+6/.test(navigator.userAgent)) {b.src="javascript:false"}b.allowTransparency="true";v[j](b);try {b.contentWindow[g].open()}catch (w) {c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try {var t=b.contentWindow[g];t.write(p());t.close()}catch (x) {b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({ loader: "static.olark.com/jsclient/loader0.js", name:"olark", methods:["configure","extend","declare","identify"] });
window.olark.identify(this.options.siteId);
//}
callback();
};
/**
* Page.
*
* @param {Page} page
*/
Olark.prototype.page = function(page){
if (!this.options.page || !this._open) return;
var props = page.properties();
var name = page.fullName();
if (!name && !props.url) return;
var msg = name ? name.toLowerCase() + ' page' : props.url;
chat('sendNotificationToOperator', {
body: 'looking at ' + msg // lowercase since olark does
});
};
/**
* Identify.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
*/
Olark.prototype.identify = function(identify){
if (!this.options.identify) return;
var username = identify.username();
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
var phone = identify.phone();
var name = identify.name()
|| identify.firstName();
visitor('updateCustomFields', traits);
if (email) visitor('updateEmailAddress', { emailAddress: email });
if (phone) visitor('updatePhoneNumber', { phoneNumber: phone });
// figure out best name
if (name) visitor('updateFullName', { fullName: name });
// figure out best nickname
var nickname = name || email || username || id;
if (name && email) nickname += ' (' + email + ')';
if (nickname) chat('updateVisitorNickname', { snippet: nickname });
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Olark.prototype.track = function(track){
if (!this.options.track || !this._open) return;
chat('sendNotificationToOperator', {
body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does
});
};
/**
* Helper method for Olark box API calls.
*
* @param {String} action
* @param {Object} value
*/
function box(action, value){
window.olark('api.box.' + action, value);
}
/**
* Helper method for Olark visitor API calls.
*
* @param {String} action
* @param {Object} value
*/
function visitor(action, value){
window.olark('api.visitor.' + action, value);
}
/**
* Helper method for Olark chat API calls.
*
* @param {String} action
* @param {Object} value
*/
function chat(action, value){
window.olark('api.chat.' + action, value);
}
}, {"segmentio/analytics.js-integration":159,"use-https":161,"next-tick":45}],
136: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('optimizely');
var callback = require('callback');
var tick = require('next-tick');
var bind = require('bind');
var each = require('each');
/**
* Expose `Optimizely` integration.
*/
var Optimizely = module.exports = integration('Optimizely')
.option('variations', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://www.optimizely.com/docs/api#function-calls
*/
Optimizely.prototype.initialize = function(){
if (this.options.variations) {
var self = this;
tick(function(){
self.replay();
});
}
this.ready();
};
/**
* Track.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Track} track
*/
Optimizely.prototype.track = function(track){
var props = track.properties();
if (props.revenue) props.revenue *= 100;
push('trackEvent', track.event(), props);
};
/**
* Page.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Page} page
*/
Optimizely.prototype.page = function(page){
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Replay experiment data as traits to other enabled providers.
*
* https://www.optimizely.com/docs/api#data-object
*/
Optimizely.prototype.replay = function(){
if (!window.optimizely) return; // in case the snippet isnt on the page
var data = window.optimizely.data;
if (!data) return;
var experiments = data.experiments;
var map = data.state.variationNamesMap;
var traits = {};
each(map, function(experimentId, variation){
var experiment = experiments[experimentId].name;
traits['Experiment: ' + experiment] = variation;
});
this.analytics.identify(traits);
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"callback":12,"next-tick":45,"bind":33,"each":5}],
137: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `PerfectAudience` integration.
*/
var PerfectAudience = module.exports = integration('Perfect Audience')
.assumesPageview()
.global('_pa')
.option('siteId', '')
.tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');
/**
* Initialize.
*
* https://www.perfectaudience.com/docs#javascript_api_autoopen
*
* @param {Object} page
*/
PerfectAudience.prototype.initialize = function(page){
window._pa = window._pa || {};
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
PerfectAudience.prototype.loaded = function(){
return !! (window._pa && window._pa.track);
};
/**
* Track.
*
* @param {Track} event
*/
PerfectAudience.prototype.track = function(track){
window._pa.track(track.event(), track.properties());
};
}, {"segmentio/analytics.js-integration":159}],
138: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_prum');
var date = require('load-date');
/**
* Expose `Pingdom` integration.
*/
var Pingdom = module.exports = integration('Pingdom')
.assumesPageview()
.global('_prum')
.global('PRUM_EPISODES')
.option('id', '')
.tag('<script src="//rum-static.pingdom.net/prum.min.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Pingdom.prototype.initialize = function(page){
window._prum = window._prum || [];
push('id', this.options.id);
push('mark', 'firstbyte', date.getTime());
var self = this;
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Pingdom.prototype.loaded = function(){
return !! (window._prum && window._prum.push !== Array.prototype.push);
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"load-date":191}],
139: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_paq');
var each = require('each');
/**
* Expose `Piwik` integration.
*/
var Piwik = module.exports = integration('Piwik')
.global('_paq')
.option('url', null)
.option('siteId', '')
.mapping('goals')
.tag('<script src="{{ url }}/piwik.js">');
/**
* Initialize.
*
* http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
*/
Piwik.prototype.initialize = function(){
window._paq = window._paq || [];
push('setSiteId', this.options.siteId);
push('setTrackerUrl', this.options.url + '/piwik.php');
push('enableLinkTracking');
this.load(this.ready);
};
/**
* Check if Piwik is loaded
*/
Piwik.prototype.loaded = function(){
return !! (window._paq && window._paq.push != [].push);
};
/**
* Page
*
* @param {Page} page
*/
Piwik.prototype.page = function(page){
push('trackPageView');
};
/**
* Track.
*
* @param {Track} track
*/
Piwik.prototype.track = function(track){
var goals = this.goals(track.event());
var revenue = track.revenue() || 0;
each(goals, function(goal){
push('trackGoal', goal, revenue);
});
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"each":5}],
140: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var convertDates = require('convert-dates');
var push = require('global-queue')('_lnq');
var alias = require('alias');
/**
* Expose `Preact` integration.
*/
var Preact = module.exports = integration('Preact')
.assumesPageview()
.global('_lnq')
.option('projectCode', '')
.tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');
/**
* Initialize.
*
* http://www.preact.io/api/javascript
*
* @param {Object} page
*/
Preact.prototype.initialize = function(page){
window._lnq = window._lnq || [];
push('_setCode', this.options.projectCode);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Preact.prototype.loaded = function(){
return !! (window._lnq && window._lnq.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Preact.prototype.identify = function(identify){
if (!identify.userId()) return;
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
push('_setPersonData', {
name: identify.name(),
email: identify.email(),
uid: identify.userId(),
properties: traits
});
};
/**
* Group.
*
* @param {String} id
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Preact.prototype.group = function(group){
if (!group.groupId()) return;
push('_setAccount', group.traits());
};
/**
* Track.
*
* @param {Track} track
*/
Preact.prototype.track = function(track){
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var special = { name: event };
if (revenue) {
special.revenue = revenue * 100;
delete props.revenue;
}
if (props.note) {
special.note = props.note;
delete props.note;
}
push('_logEvent', special, props);
};
/**
* Convert a `date` to a format Preact supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate(date){
return Math.floor(date / 1000);
}
}, {"segmentio/analytics.js-integration":159,"convert-dates":196,"global-queue":190,"alias":195}],
141: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_kiq');
var Facade = require('facade');
var Identify = Facade.Identify;
var bind = require('bind');
var when = require('when');
/**
* Expose `Qualaroo` integration.
*/
var Qualaroo = module.exports = integration('Qualaroo')
.assumesPageview()
.global('_kiq')
.option('customerId', '')
.option('siteToken', '')
.option('track', false)
.tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Qualaroo.prototype.initialize = function(page){
window._kiq = window._kiq || [];
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Qualaroo.prototype.loaded = function(){
return !! (window._kiq && window._kiq.push !== Array.prototype.push);
};
/**
* Identify.
*
* http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
* http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
*
* @param {Identify} identify
*/
Qualaroo.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
if (email) id = email;
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Qualaroo.prototype.track = function(track){
if (!this.options.track) return;
var event = track.event();
var traits = {};
traits['Triggered: ' + event] = true;
this.identify(new Identify({ traits: traits }));
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"facade":27,"bind":33,"when":184}],
142: [function(require, module, exports) {
/**
* Module dependencies.
*/
var push = require('global-queue')('_qevents', { wrap: false });
var integration = require('segmentio/analytics.js-integration');
var useHttps = require('use-https');
/**
* Expose `Quantcast` integration.
*/
var Quantcast = module.exports = integration('Quantcast')
.assumesPageview()
.global('_qevents')
.global('__qc')
.option('pCode', null)
.option('advertise', false)
.tag('http', '<script src="http://edge.quantserve.com/quant.js">')
.tag('https', '<script src="https://secure.quantserve.com/quant.js">');
/**
* Initialize.
*
* https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {Page} page
*/
Quantcast.prototype.initialize = function(page){
window._qevents = window._qevents || [];
var opts = this.options;
var settings = { qacct: opts.pCode };
var user = this.analytics.user();
if (user.id()) settings.uid = user.id();
if (page) {
settings.labels = this.labels('page', page.category(), page.name());
}
push(settings);
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Quantcast.prototype.loaded = function(){
return !! window.__qc;
};
/**
* Page.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Page} page
*/
Quantcast.prototype.page = function(page){
var category = page.category();
var name = page.name();
var settings = {
event: 'refresh',
labels: this.labels('page', category, name),
qacct: this.options.pCode,
};
var user = this.analytics.user();
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Identify.
*
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {String} id (optional)
*/
Quantcast.prototype.identify = function(identify){
// edit the initial quantcast settings
// TODO: could be done in a cleaner way
var id = identify.userId();
if (id) {
window._qevents[0] = window._qevents[0] || {};
window._qevents[0].uid = id;
}
};
/**
* Track.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Track} track
*/
Quantcast.prototype.track = function(track){
var name = track.event();
var revenue = track.revenue();
var settings = {
event: 'click',
labels: this.labels('event', name),
qacct: this.options.pCode
};
var user = this.analytics.user();
if (null != revenue) settings.revenue = (revenue+''); // convert to string
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
Quantcast.prototype.completedOrder = function(track){
var name = track.event();
var revenue = track.total();
var labels = this.labels('event', name);
var category = track.category();
if (this.options.advertise && category) {
labels += ',' + this.labels('pcat', category);
}
var settings = {
event: 'refresh', // the example Quantcast sent has completed order send refresh not click
labels: labels,
revenue: (revenue+''), // convert to string
orderid: track.orderId(),
qacct: this.options.pCode
};
push(settings);
};
/**
* Generate quantcast labels.
*
* Example:
*
* options.advertise = false;
* labels('event', 'my event');
* // => "event.my event"
*
* options.advertise = true;
* labels('event', 'my event');
* // => "_fp.event.my event"
*
* @param {String} type
* @param {String} ...
* @return {String}
* @api private
*/
Quantcast.prototype.labels = function(type){
var args = [].slice.call(arguments, 1);
var advertise = this.options.advertise;
var ret = [];
if (advertise && 'page' == type) type = 'event';
if (advertise) type = '_fp.' + type;
for (var i = 0; i < args.length; ++i) {
if (null == args[i]) continue;
var value = String(args[i]);
ret.push(value.replace(/,/g, ';'));
}
ret = advertise ? ret.join(' ') : ret.join('.');
return [type, ret].join('.');
};
}, {"global-queue":190,"segmentio/analytics.js-integration":159,"use-https":161}],
143: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var extend = require('extend');
var is = require('is');
/**
* Expose `Rollbar` integration.
*/
var RollbarIntegration = module.exports = integration('Rollbar')
.global('Rollbar')
.option('identify', true)
.option('accessToken', '')
.option('environment', 'unknown')
.option('captureUncaught', true);
/**
* Initialize.
*
* @param {Object} page
*/
RollbarIntegration.prototype.initialize = function(page){
var _rollbarConfig = this.config = {
accessToken: this.options.accessToken,
captureUncaught: this.options.captureUncaught,
payload: {
environment: this.options.environment
}
};
(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0 === a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if (this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={ shim:b, method:c, args:f, ts:new Date };return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if (b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try {return a.apply(this,arguments)} catch (c) {b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if ("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if (h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for (f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if (void 0===a._rollbarPayloadQueue){var c,d,f,g;for (b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for (f=c.args,g=0;g<f.length;++g)if (d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if ("function"!=typeof b)return b;if (b._isWrap)return b;if (!b._wrapped){b._wrapped=function(){try {return b.apply(this,arguments)} catch (c) {throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for (var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for (var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
RollbarIntegration.prototype.loaded = function(){
return is.object(window.Rollbar) && null == window.Rollbar.shimId;
};
/**
* Load.
*
* @param {Function} callback
*/
RollbarIntegration.prototype.load = function(callback){
window.Rollbar.loadFull(window, document, true, this.config, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
RollbarIntegration.prototype.identify = function(identify){
// do stuff with `id` or `traits`
if (!this.options.identify) return;
// Don't allow identify without a user id
var uid = identify.userId();
if (uid === null || uid === undefined) return;
var rollbar = window.Rollbar;
var person = { id: uid };
extend(person, identify.traits());
rollbar.configure({ payload: { person: person }});
};
}, {"segmentio/analytics.js-integration":159,"extend":40,"is":18}],
144: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
/**
* Expose `SaaSquatch` integration.
*/
var SaaSquatch = module.exports = integration('SaaSquatch')
.option('tenantAlias', '')
.global('_sqh')
.tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');
/**
* Initialize.
*
* @param {Page} page
*/
SaaSquatch.prototype.initialize = function(page){
window._sqh = window._sqh || [];
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
SaaSquatch.prototype.loaded = function(){
return window._sqh && window._sqh.push != [].push;
};
/**
* Identify.
*
* @param {Facade} identify
*/
SaaSquatch.prototype.identify = function(identify){
var sqh = window._sqh;
var accountId = identify.proxy('traits.accountId');
var image = identify.proxy('traits.referralImage');
var opts = identify.options(this.name);
var id = identify.userId();
var email = identify.email();
if (!(id || email)) return;
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
first_name: identify.firstName(),
last_name: identify.lastName(),
user_image: identify.avatar(),
email: email,
user_id: id,
};
if (accountId) init.account_id = accountId;
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
}, {"segmentio/analytics.js-integration":159}],
145: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
/**
* Expose `Sentry` integration.
*/
var Sentry = module.exports = integration('Sentry')
.global('Raven')
.option('config', '')
.tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');
/**
* Initialize.
*
* http://raven-js.readthedocs.org/en/latest/config/index.html
*/
Sentry.prototype.initialize = function(){
var config = this.options.config;
var self = this;
this.load(function(){
// for now, raven basically requires `install` to be called
// https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113
window.Raven.config(config).install();
self.ready();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Sentry.prototype.loaded = function(){
return is.object(window.Raven);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Sentry.prototype.identify = function(identify){
window.Raven.setUser(identify.traits());
};
}, {"segmentio/analytics.js-integration":159,"is":18}],
146: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var is = require('is');
/**
* Expose `SnapEngage` integration.
*/
var SnapEngage = module.exports = integration('SnapEngage')
.assumesPageview()
.global('SnapABug')
.option('apiKey', '')
.tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');
/**
* Initialize.
*
* http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
*
* @param {Object} page
*/
SnapEngage.prototype.initialize = function(page){
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
SnapEngage.prototype.loaded = function(){
return is.object(window.SnapABug);
};
/**
* Identify.
*
* @param {Identify} identify
*/
SnapEngage.prototype.identify = function(identify){
var email = identify.email();
if (!email) return;
window.SnapABug.setUserEmail(email);
};
}, {"segmentio/analytics.js-integration":159,"is":18}],
147: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var bind = require('bind');
var when = require('when');
/**
* Expose `Spinnakr` integration.
*/
var Spinnakr = module.exports = integration('Spinnakr')
.assumesPageview()
.global('_spinnakr_site_id')
.global('_spinnakr')
.option('siteId', '')
.tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Spinnakr.prototype.initialize = function(page){
window._spinnakr_site_id = this.options.siteId;
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, ready);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Spinnakr.prototype.loaded = function(){
return !! window._spinnakr;
};
}, {"segmentio/analytics.js-integration":159,"bind":33,"when":184}],
148: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var slug = require('slug');
var push = require('global-queue')('_tsq');
/**
* Expose `Tapstream` integration.
*/
var Tapstream = module.exports = integration('Tapstream')
.assumesPageview()
.global('_tsq')
.option('accountName', '')
.option('trackAllPages', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');
/**
* Initialize.
*
* @param {Object} page
*/
Tapstream.prototype.initialize = function(page){
window._tsq = window._tsq || [];
push('setAccountName', this.options.accountName);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Tapstream.prototype.loaded = function(){
return !! (window._tsq && window._tsq.push !== Array.prototype.push);
};
/**
* Page.
*
* @param {Page} page
*/
Tapstream.prototype.page = function(page){
var category = page.category();
var opts = this.options;
var name = page.fullName();
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Track.
*
* @param {Track} track
*/
Tapstream.prototype.track = function(track){
var props = track.properties();
push('fireHit', slug(track.event()), [props.url]); // needs events as slugs
};
}, {"segmentio/analytics.js-integration":159,"slug":166,"global-queue":190}],
149: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `Trakio` integration.
*/
var Trakio = module.exports = integration('trak.io')
.assumesPageview()
.global('trak')
.option('token', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');
/**
* Options aliases.
*/
var optionsAliases = {
initialPageview: 'auto_track_page_view'
};
/**
* Initialize.
*
* https://docs.trak.io
*
* @param {Object} page
*/
Trakio.prototype.initialize = function(page){
var options = this.options;
window.trak = window.trak || [];
window.trak.io = window.trak.io || {};
window.trak.push = window.trak.push || function(){};
window.trak.io.load = window.trak.io.load || function(e){var r = function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); };
window.trak.io.load(options.token, alias(options, optionsAliases));
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Trakio.prototype.loaded = function(){
return !! (window.trak && window.trak.loaded);
};
/**
* Page.
*
* @param {Page} page
*/
Trakio.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
window.trak.io.page_view(props.path, name || props.title);
// named pages
if (name && this.options.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && this.options.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Trait aliases.
*
* http://docs.trak.io/properties.html#special
*/
var traitAliases = {
avatar: 'avatar_url',
firstName: 'first_name',
lastName: 'last_name'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Trakio.prototype.identify = function(identify){
var traits = identify.traits(traitAliases);
var id = identify.userId();
if (id) {
window.trak.io.identify(id, traits);
} else {
window.trak.io.identify(traits);
}
};
/**
* Group.
*
* @param {String} id (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*
* TODO: add group
* TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special
*/
/**
* Track.
*
* @param {Track} track
*/
Trakio.prototype.track = function(track){
window.trak.io.track(track.event(), track.properties());
};
/**
* Alias.
*
* @param {Alias} alias
*/
Trakio.prototype.alias = function(alias){
if (!window.trak.io.distinct_id) return;
var from = alias.from();
var to = alias.to();
if (to === window.trak.io.distinct_id()) return;
if (from) {
window.trak.io.alias(from, to);
} else {
window.trak.io.alias(to);
}
};
}, {"segmentio/analytics.js-integration":159,"alias":195,"clone":194}],
150: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var each = require('each');
/**
* HOP.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `TwitterAds`.
*/
var TwitterAds = module.exports = integration('Twitter Ads')
.tag('pixel', '<img src="//analytics.twitter.com/i/adsct?txn_id={{ event }}&p_id=Twitter"/>')
.mapping('events');
/**
* Initialize.
*
* @param {Object} page
*/
TwitterAds.prototype.initialize = function(){
this.ready();
};
/**
* Track.
*
* @param {Track} track
*/
TwitterAds.prototype.track = function(track){
var events = this.events(track.event());
var self = this;
each(events, function(event){
var el = self.load('pixel', {
event: event
});
});
};
}, {"segmentio/analytics.js-integration":159,"each":5}],
151: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_uc');
/**
* Expose `Usercycle` integration.
*/
var Usercycle = module.exports = integration('USERcycle')
.assumesPageview()
.global('_uc')
.option('key', '')
.tag('<script src="//api.usercycle.com/javascripts/track.js">');
/**
* Initialize.
*
* http://docs.usercycle.com/javascript_api
*
* @param {Object} page
*/
Usercycle.prototype.initialize = function(page){
push('_key', this.options.key);
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Usercycle.prototype.loaded = function(){
return !! (window._uc && window._uc.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Usercycle.prototype.identify = function(identify){
var traits = identify.traits();
var id = identify.userId();
if (id) push('uid', id);
// there's a special `came_back` event used for retention and traits
push('action', 'came_back', traits);
};
/**
* Track.
*
* @param {Track} track
*/
Usercycle.prototype.track = function(track){
push('action', track.event(), track.properties({
revenue: 'revenue_amount'
}));
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190}],
152: [function(require, module, exports) {
/**
* Module dependencies.
*/
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('analytics.js-integration');
var load = require('load-script');
var push = require('global-queue')('_ufq');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Userfox);
};
/**
* Expose `Userfox` integration.
*/
var Userfox = exports.Integration = integration('userfox')
.assumesPageview()
.readyOnLoad()
.global('_ufq')
.option('clientId', '');
/**
* Initialize.
*
* https://www.userfox.com/docs/
*
* @param {Object} page
*/
Userfox.prototype.initialize = function(page){
window._ufq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Userfox.prototype.loaded = function(){
return !! (window._ufq && window._ufq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Userfox.prototype.load = function(callback){
load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback);
};
/**
* Identify.
*
* https://www.userfox.com/docs/#custom-data
*
* @param {Identify} identify
*/
Userfox.prototype.identify = function(identify){
var traits = identify.traits({ created: 'signup_date' });
var email = identify.email();
if (!email) return;
// initialize the library with the email now that we have it
push('init', {
clientId: this.options.clientId,
email: email
});
traits = convertDates(traits, formatDate);
push('track', traits);
};
/**
* Convert a `date` to a format userfox supports.
*
* @param {Date} date
* @return {String}
*/
function formatDate(date){
return Math.round(date.getTime() / 1000).toString();
}
}, {"alias":195,"callback":12,"convert-dates":196,"analytics.js-integration":159,"load-script":168,"global-queue":190}],
153: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('UserVoice');
var convertDates = require('convert-dates');
var unix = require('to-unix-timestamp');
var alias = require('alias');
var clone = require('clone');
/**
* Expose `UserVoice` integration.
*/
var UserVoice = module.exports = integration('UserVoice')
.assumesPageview()
.global('UserVoice')
.global('showClassicWidget')
.option('apiKey', '')
.option('classic', false)
.option('forumId', null)
.option('showWidget', true)
.option('mode', 'contact')
.option('accentColor', '#448dd6')
.option('smartvote', true)
.option('trigger', null)
.option('triggerPosition', 'bottom-right')
.option('triggerColor', '#ffffff')
.option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)')
// BACKWARDS COMPATIBILITY: classic options
.option('classicMode', 'full')
.option('primaryColor', '#cc6d00')
.option('linkColor', '#007dbf')
.option('defaultMode', 'support')
.option('tabLabel', 'Feedback & Support')
.option('tabColor', '#cc6d00')
.option('tabPosition', 'middle-right')
.option('tabInverted', false)
.tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
UserVoice.on('construct', function(integration){
if (!integration.options.classic) return;
integration.group = undefined;
integration.identify = integration.identifyClassic;
integration.initialize = integration.initializeClassic;
});
/**
* Initialize.
*
* @param {Object} page
*/
UserVoice.prototype.initialize = function(page){
var options = this.options;
var opts = formatOptions(options);
push('set', opts);
push('autoprompt', {});
if (options.showWidget) {
options.trigger
? push('addTrigger', options.trigger, opts)
: push('addTrigger', opts);
}
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
UserVoice.prototype.loaded = function(){
return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push);
};
/**
* Identify.
*
* @param {Identify} identify
*/
UserVoice.prototype.identify = function(identify){
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
UserVoice.prototype.group = function(group){
var traits = group.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', { account: traits });
};
/**
* Initialize (classic).
*
* @param {Object} options
* @param {Function} ready
*/
UserVoice.prototype.initializeClassic = function(){
var options = this.options;
window.showClassicWidget = showClassicWidget; // part of public api
if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options));
this.load(this.ready);
};
/**
* Identify (classic).
*
* @param {Identify} identify
*/
UserVoice.prototype.identifyClassic = function(identify){
push('setCustomFields', identify.traits());
};
/**
* Format the options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatOptions(options){
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position'
});
}
/**
* Format the classic options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatClassicOptions(options){
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
}
/**
* Show the classic version of the UserVoice widget. This method is usually part
* of UserVoice classic's public API.
*
* @param {String} type ('showTab' or 'showLightbox')
* @param {Object} options (optional)
*/
function showClassicWidget(type, options){
type = type || 'showLightbox';
push(type, 'classic_widget', options);
}
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"convert-dates":196,"to-unix-timestamp":199,"alias":195,"clone":194}],
199: [function(require, module, exports) {
/**
* Expose `toUnixTimestamp`.
*/
module.exports = toUnixTimestamp;
/**
* Convert a `date` into a Unix timestamp.
*
* @param {Date}
* @return {Number}
*/
function toUnixTimestamp (date) {
return Math.floor(date.getTime() / 1000);
}
}, {}],
154: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var push = require('global-queue')('_veroq');
var cookie = require('component/cookie');
/**
* Expose `Vero` integration.
*/
var Vero = module.exports = integration('Vero')
.global('_veroq')
.option('apiKey', '')
.tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');
/**
* Initialize.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md
*
* @param {Object} page
*/
Vero.prototype.initialize = function(page){
// clear default cookie so vero parses correctly.
// this is for the tests.
// basically, they have window.addEventListener('unload')
// which then saves their "command_store", which is an array.
// so we just want to create that initially so we can reload the tests.
if (!cookie('__veroc4')) cookie('__veroc4', '[]');
push('init', { api_key: this.options.apiKey });
this.load(this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Vero.prototype.loaded = function(){
return !! (window._veroq && window._veroq.push !== Array.prototype.push);
};
/**
* Page.
*
* https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews
*
* @param {Page} page
*/
Vero.prototype.page = function(page){
push('trackPageview');
};
/**
* Identify.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification
*
* @param {Identify} identify
*/
Vero.prototype.identify = function(identify){
var traits = identify.traits();
var email = identify.email();
var id = identify.userId();
if (!id || !email) return; // both required
push('user', traits);
};
/**
* Track.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events
*
* @param {Track} track
*/
Vero.prototype.track = function(track){
push('track', track.event(), track.properties());
};
}, {"segmentio/analytics.js-integration":159,"global-queue":190,"component/cookie":28}],
155: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var tick = require('next-tick');
var each = require('each');
/**
* Expose `VWO` integration.
*/
var VWO = module.exports = integration('Visual Website Optimizer')
.option('replay', true);
/**
* Initialize.
*
* http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
*/
VWO.prototype.initialize = function(){
if (this.options.replay) this.replay();
this.ready();
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function(){
var analytics = this.analytics;
tick(function(){
experiments(function(err, traits){
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} fn
* @return {Object}
*/
function experiments(fn){
enqueue(function(){
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return fn();
each(ids, function(id){
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
fn(null, data);
});
}
/**
* Add a `fn` to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn
*/
function enqueue(fn){
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id
* @return {String}
*/
function variation(id){
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
}, {"segmentio/analytics.js-integration":159,"next-tick":45,"each":5}],
156: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var useHttps = require('use-https');
/**
* Expose `WebEngage` integration.
*/
var WebEngage = module.exports = integration('WebEngage')
.assumesPageview()
.global('_weq')
.global('webengage')
.option('widgetVersion', '4.0')
.option('licenseCode', '')
.tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">')
.tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');
/**
* Initialize.
*
* @param {Object} page
*/
WebEngage.prototype.initialize = function(page){
var _weq = window._weq = window._weq || {};
_weq['webengage.licenseCode'] = this.options.licenseCode;
_weq['webengage.widgetVersion'] = this.options.widgetVersion;
var name = useHttps() ? 'https' : 'http';
this.load(name, this.ready);
};
/**
* Loaded?
*
* @return {Boolean}
*/
WebEngage.prototype.loaded = function(){
return !! window.webengage;
};
}, {"segmentio/analytics.js-integration":159,"use-https":161}],
157: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var snake = require('to-snake-case');
var isEmail = require('is-email');
var extend = require('extend');
var each = require('each');
var type = require('type');
/**
* Expose `Woopra` integration.
*/
var Woopra = module.exports = integration('Woopra')
.global('woopra')
.option('domain', '')
.option('cookieName', 'wooTracker')
.option('cookieDomain', null)
.option('cookiePath', '/')
.option('ping', true)
.option('pingInterval', 12000)
.option('idleTimeout', 300000)
.option('downloadTracking', true)
.option('outgoingTracking', true)
.option('outgoingIgnoreSubdomain', true)
.option('downloadPause', 200)
.option('outgoingPause', 400)
.option('ignoreQueryUrl', true)
.option('hideCampaign', false)
.tag('<script src="//static.woopra.com/js/w.js">');
/**
* Initialize.
*
* http://www.woopra.com/docs/setup/javascript-tracking/
*
* @param {Object} page
*/
Woopra.prototype.initialize = function(page){
(function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra');
this.load(this.ready);
each(this.options, function(key, value){
key = snake(key);
if (null == value) return;
if ('' === value) return;
window.woopra.config(key, value);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Woopra.prototype.loaded = function(){
return !! (window.woopra && window.woopra.loaded);
};
/**
* Page.
*
* @param {String} category (optional)
*/
Woopra.prototype.page = function(page){
var props = page.properties();
var name = page.fullName();
if (name) props.title = name;
window.woopra.track('pv', props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Woopra.prototype.identify = function(identify){
var traits = identify.traits();
if (identify.name()) traits.name = identify.name();
window.woopra.identify(traits).push(); // `push` sends it off async
};
/**
* Track.
*
* @param {Track} track
*/
Woopra.prototype.track = function(track){
window.woopra.track(track.event(), track.properties());
};
}, {"segmentio/analytics.js-integration":159,"to-snake-case":160,"is-email":19,"extend":40,"each":5,"type":35}],
158: [function(require, module, exports) {
/**
* Module dependencies.
*/
var integration = require('segmentio/analytics.js-integration');
var tick = require('next-tick');
var bind = require('bind');
var when = require('when');
/**
* Expose `Yandex` integration.
*/
var Yandex = module.exports = integration('Yandex Metrica')
.assumesPageview()
.global('yandex_metrika_callbacks')
.global('Ya')
.option('counterId', null)
.tag('<script src="//mc.yandex.ru/metrika/watch.js">');
/**
* Initialize.
*
* http://api.yandex.com/metrika/
* https://metrica.yandex.com/22522351?step=2#tab=code
*
* @param {Object} page
*/
Yandex.prototype.initialize = function(page){
var id = this.options.counterId;
push(function(){
window['yaCounter' + id] = new window.Ya.Metrika({ id: id });
});
var loaded = bind(this, this.loaded);
var ready = this.ready;
this.load(function(){
when(loaded, function(){
tick(ready);
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Yandex.prototype.loaded = function(){
return !! (window.Ya && window.Ya.Metrika);
};
/**
* Push a new callback on the global Yandex queue.
*
* @param {Function} callback
*/
function push(callback){
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
}
}, {"segmentio/analytics.js-integration":159,"next-tick":45,"bind":33,"when":184}]}, {}, {"1":"analytics"})
|
ajax/libs/core-js/2.0.0-alpha/library.js
|
sufuf3/cdnjs
|
/**
* core-js 2.0.0-alpha
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2015 Denis Pushkarev
*/
!function(__e, __g, undefined){
'use strict';
/******/ (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__) {
__webpack_require__(1);
__webpack_require__(33);
__webpack_require__(42);
__webpack_require__(44);
__webpack_require__(46);
__webpack_require__(48);
__webpack_require__(50);
__webpack_require__(51);
__webpack_require__(52);
__webpack_require__(53);
__webpack_require__(54);
__webpack_require__(55);
__webpack_require__(56);
__webpack_require__(57);
__webpack_require__(58);
__webpack_require__(59);
__webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(64);
__webpack_require__(65);
__webpack_require__(66);
__webpack_require__(67);
__webpack_require__(68);
__webpack_require__(69);
__webpack_require__(70);
__webpack_require__(72);
__webpack_require__(73);
__webpack_require__(74);
__webpack_require__(76);
__webpack_require__(77);
__webpack_require__(78);
__webpack_require__(80);
__webpack_require__(81);
__webpack_require__(82);
__webpack_require__(83);
__webpack_require__(84);
__webpack_require__(85);
__webpack_require__(86);
__webpack_require__(87);
__webpack_require__(88);
__webpack_require__(89);
__webpack_require__(90);
__webpack_require__(91);
__webpack_require__(92);
__webpack_require__(94);
__webpack_require__(96);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(103);
__webpack_require__(104);
__webpack_require__(108);
__webpack_require__(110);
__webpack_require__(111);
__webpack_require__(112);
__webpack_require__(113);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(119);
__webpack_require__(120);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(128);
__webpack_require__(129);
__webpack_require__(132);
__webpack_require__(134);
__webpack_require__(136);
__webpack_require__(138);
__webpack_require__(139);
__webpack_require__(140);
__webpack_require__(147);
__webpack_require__(150);
__webpack_require__(151);
__webpack_require__(153);
__webpack_require__(154);
__webpack_require__(155);
__webpack_require__(156);
__webpack_require__(157);
__webpack_require__(158);
__webpack_require__(159);
__webpack_require__(160);
__webpack_require__(161);
__webpack_require__(162);
__webpack_require__(163);
__webpack_require__(164);
__webpack_require__(166);
__webpack_require__(167);
__webpack_require__(168);
__webpack_require__(169);
__webpack_require__(170);
__webpack_require__(171);
__webpack_require__(173);
__webpack_require__(174);
__webpack_require__(175);
__webpack_require__(176);
__webpack_require__(177);
__webpack_require__(179);
__webpack_require__(180);
__webpack_require__(182);
__webpack_require__(183);
__webpack_require__(184);
__webpack_require__(185);
__webpack_require__(186);
__webpack_require__(187);
__webpack_require__(190);
__webpack_require__(125);
__webpack_require__(192);
__webpack_require__(191);
__webpack_require__(193);
__webpack_require__(194);
__webpack_require__(195);
__webpack_require__(196);
__webpack_require__(197);
__webpack_require__(199);
__webpack_require__(200);
__webpack_require__(201);
__webpack_require__(203);
module.exports = __webpack_require__(204);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, $export = __webpack_require__(3)
, DESCRIPTORS = __webpack_require__(8)
, createDesc = __webpack_require__(10)
, html = __webpack_require__(11)
, cel = __webpack_require__(12)
, has = __webpack_require__(14)
, cof = __webpack_require__(15)
, invoke = __webpack_require__(16)
, fails = __webpack_require__(9)
, anObject = __webpack_require__(17)
, aFunction = __webpack_require__(7)
, isObject = __webpack_require__(13)
, toObject = __webpack_require__(18)
, toIObject = __webpack_require__(20)
, toInteger = __webpack_require__(22)
, toIndex = __webpack_require__(23)
, toLength = __webpack_require__(24)
, IObject = __webpack_require__(21)
, IE_PROTO = __webpack_require__(25)('__proto__')
, createArrayMethod = __webpack_require__(26)
, arrayIndexOf = __webpack_require__(32)(false)
, ObjectProto = Object.prototype
, ArrayProto = Array.prototype
, arraySlice = ArrayProto.slice
, arrayJoin = ArrayProto.join
, defineProperty = $.setDesc
, getOwnDescriptor = $.getDesc
, defineProperties = $.setDescs
, factories = {}
, IE8_DOM_DEFINE;
if(!DESCRIPTORS){
IE8_DOM_DEFINE = !fails(function(){
return defineProperty(cel('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
$.setDesc = function(O, P, Attributes){
if(IE8_DOM_DEFINE)try {
return defineProperty(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)anObject(O)[P] = Attributes.value;
return O;
};
$.getDesc = function(O, P){
if(IE8_DOM_DEFINE)try {
return getOwnDescriptor(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]);
};
$.setDescs = defineProperties = function(O, Properties){
anObject(O);
var keys = $.getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)$.setDesc(O, P = keys[i++], Properties[P]);
return O;
};
}
$export($export.S + $export.F * !DESCRIPTORS, 'Object', {
// 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $.getDesc,
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
defineProperty: $.setDesc,
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
defineProperties: defineProperties
});
// IE 8- don't enum bug keys
var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' +
'toLocaleString,toString,valueOf').split(',')
// Additional keys for getOwnPropertyNames
, keys2 = keys1.concat('length', 'prototype')
, keysLen1 = keys1.length;
// Create object with `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = cel('iframe')
, i = keysLen1
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict.prototype[keys1[i]];
return createDict();
};
var createGetKeys = function(names, length){
return function(object){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
};
var Empty = function(){};
$export($export.S, 'Object', {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
getPrototypeOf: $.getProto = $.getProto || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
},
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true),
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
create: $.create = $.create || function(O, /*?*/Properties){
var result;
if(O !== null){
Empty.prototype = anObject(O);
result = new Empty();
Empty.prototype = null;
// add "__proto__" for Object.getPrototypeOf shim
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : defineProperties(result, Properties);
},
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false)
});
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
}
return factories[len](F, args);
};
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
$export($export.P, 'Function', {
bind: function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
}
});
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * fails(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
$export($export.P + $export.F * (IObject != Object), 'Array', {
join: function join(separator){
return arrayJoin.call(IObject(this), separator === undefined ? ',' : separator);
}
});
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
$export($export.S, 'Array', {isArray: __webpack_require__(28)});
var createArrayReduce = function(isRight){
return function(callbackfn, memo){
aFunction(callbackfn);
var O = IObject(this)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(arguments.length < 2)for(;;){
if(index in O){
memo = O[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in O){
memo = callbackfn(memo, O[index], index, this);
}
return memo;
};
};
var methodize = function($fn){
return function(arg1/*, arg2 = undefined */){
return $fn(this, arg1, arguments[1]);
};
};
$export($export.P, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: $.each = $.each || methodize(createArrayMethod(0)),
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: methodize(createArrayMethod(1)),
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: methodize(createArrayMethod(2)),
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: methodize(createArrayMethod(3)),
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: methodize(createArrayMethod(4)),
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: createArrayReduce(false),
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: createArrayReduce(true),
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: methodize(arrayIndexOf),
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function(el, fromIndex /* = @[*-1] */){
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(fromIndex));
if(index < 0)index = toLength(length + index);
for(;index >= 0; index--)if(index in O)if(O[index] === el)return index;
return -1;
}
});
// 20.3.3.1 / 15.9.4.4 Date.now()
$export($export.S, 'Date', {now: function(){ return +new Date; }});
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(this))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
/***/ },
/* 2 */
/***/ function(module, exports) {
var $Object = Object;
module.exports = {
create: $Object.create,
getProto: $Object.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: $Object.getOwnPropertyDescriptor,
setDesc: $Object.defineProperty,
setDescs: $Object.defineProperties,
getKeys: $Object.keys,
getNames: $Object.getOwnPropertyNames,
getSymbols: $Object.getOwnPropertySymbols,
each: [].forEach
};
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, core = __webpack_require__(5)
, ctx = __webpack_require__(6)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(param){
return this instanceof C ? new C(param) : C(param);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
module.exports = $export;
/***/ },
/* 4 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 5 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.0.0-alpha'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(7);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(9)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 9 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 10 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(4).document && document.documentElement;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13)
, document = __webpack_require__(4).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 14 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 15 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 16 */
/***/ function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(19);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 19 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(21)
, defined = __webpack_require__(19);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(15);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 22 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(22)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(22)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 25 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(6)
, IObject = __webpack_require__(21)
, toObject = __webpack_require__(18)
, toLength = __webpack_require__(24)
, asc = __webpack_require__(27);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var isObject = __webpack_require__(13)
, isArray = __webpack_require__(28)
, SPECIES = __webpack_require__(29)('species');
module.exports = function(original, length){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return new (C === undefined ? Array : C)(length);
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(15);
module.exports = Array.isArray || function(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(30)('wks')
, uid = __webpack_require__(25)
, Symbol = __webpack_require__(4).Symbol
, USE_SYMBOL = __webpack_require__(31);
module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, $Symbol = global.Symbol
, document = global.document || {}
, GEBTN = 'getElementsByTagName';
module.exports = typeof $Symbol == 'function' && (document[GEBTN] === undefined || !__webpack_require__(9)(function(){
// Chromium 38-40 Symbol has a bug with some kinds of DOM collections
var htc = document.createElement('x')[GEBTN]('y')
, sym = $Symbol();
htc[sym] = 7;
return htc[sym] !== 7;
}));
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(20)
, toLength = __webpack_require__(24)
, toIndex = __webpack_require__(23);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var $ = __webpack_require__(2)
, global = __webpack_require__(4)
, has = __webpack_require__(14)
, DESCRIPTORS = __webpack_require__(8)
, $export = __webpack_require__(3)
, redefine = __webpack_require__(34)
, META = __webpack_require__(36).KEY
, $fails = __webpack_require__(9)
, shared = __webpack_require__(30)
, setToStringTag = __webpack_require__(37)
, uid = __webpack_require__(25)
, wks = __webpack_require__(29)
, keyOf = __webpack_require__(38)
, $names = __webpack_require__(39)
, enumKeys = __webpack_require__(40)
, isArray = __webpack_require__(28)
, anObject = __webpack_require__(17)
, toIObject = __webpack_require__(20)
, createDesc = __webpack_require__(10)
, USE_NATIVE = __webpack_require__(31)
, getDesc = $.getDesc
, setDesc = $.setDesc
, _create = $.create
, getNames = $names.get
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, setter = false
, HIDDEN = wks('_hidden')
, isEnum = $.isEnum
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, ObjectProto = Object.prototype;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(setDesc({}, 'a', {
get: function(){ return setDesc(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = getDesc(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
setDesc(it, key, D);
if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc);
} : setDesc;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol.prototype);
sym._k = tag;
DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, {
configurable: true,
set: function(value){
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
}
});
return sym;
};
var isSymbol = function(it){
return typeof it == 'symbol';
};
var $defineProperty = function defineProperty(it, key, D){
if(D && has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return setDesc(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key);
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key]
? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
var D = getDesc(it = toIObject(it), key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = getNames(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var names = getNames(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]);
return result;
};
var $stringify = function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, $$ = arguments
, replacer, $replacer;
while($$.length > i)args.push($$[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
};
var BUGGY_JSON = $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
});
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(isSymbol(this))throw TypeError('Symbol is not a constructor');
return wrap(uid(arguments.length > 0 ? arguments[0] : undefined));
};
redefine($Symbol.prototype, 'toString', function toString(){
return this._k;
});
isSymbol = function(it){
return it instanceof $Symbol;
};
$.create = $create;
$.isEnum = $propertyIsEnumerable;
$.getDesc = $getOwnPropertyDescriptor;
$.setDesc = $defineProperty;
$.setDescs = $defineProperties;
$.getNames = $names.get = $getOwnPropertyNames;
$.getSymbols = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(41)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
}
var symbolStatics = {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
return keyOf(SymbolRegistry, key);
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
};
// 19.4.2.2 Symbol.hasInstance
// 19.4.2.3 Symbol.isConcatSpreadable
// 19.4.2.4 Symbol.iterator
// 19.4.2.6 Symbol.match
// 19.4.2.8 Symbol.replace
// 19.4.2.9 Symbol.search
// 19.4.2.10 Symbol.species
// 19.4.2.11 Symbol.split
// 19.4.2.12 Symbol.toPrimitive
// 19.4.2.13 Symbol.toStringTag
// 19.4.2.14 Symbol.unscopables
$.each.call((
'hasInstance,isConcatSpreadable,iterator,match,replace,search,' +
'species,split,toPrimitive,toStringTag,unscopables'
).split(','), function(it){
var sym = wks(it);
symbolStatics[it] = USE_NATIVE ? sym : wrap(sym);
});
setter = true;
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', symbolStatics);
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || BUGGY_JSON), 'JSON', {stringify: $stringify});
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(35);
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, createDesc = __webpack_require__(10);
module.exports = __webpack_require__(8) ? function(object, key, value){
return $.setDesc(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(25)('meta')
, isObject = __webpack_require__(13)
, has = __webpack_require__(14)
, setDesc = __webpack_require__(2).setDesc
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(9)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(2).setDesc
, has = __webpack_require__(14)
, TAG = __webpack_require__(29)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, toIObject = __webpack_require__(20);
module.exports = function(object, el){
var O = toIObject(object)
, keys = $.getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(20)
, getNames = __webpack_require__(2).getNames
, toString = {}.toString;
var windowNames = typeof window == 'object' && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return getNames(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.get = function getOwnPropertyNames(it){
if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it);
return getNames(toIObject(it));
};
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var $ = __webpack_require__(2);
module.exports = function(it){
var keys = $.getKeys(it)
, getSymbols = $.getSymbols;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = $.isEnum
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key);
}
return keys;
};
/***/ },
/* 41 */
/***/ function(module, exports) {
module.exports = true;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(3);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(43)});
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.1 Object.assign(target, source, ...)
var $ = __webpack_require__(2)
, toObject = __webpack_require__(18)
, IObject = __webpack_require__(21);
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = __webpack_require__(9)(function(){
var a = Object.assign
, A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, $$ = arguments
, $$len = $$.length
, index = 1
, getKeys = $.getKeys
, getSymbols = $.getSymbols
, isEnum = $.isEnum;
while($$len > index){
var S = IObject($$[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
}
return T;
} : Object.assign;
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(3);
$export($export.S, 'Object', {is: __webpack_require__(45)});
/***/ },
/* 45 */
/***/ function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(3);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(47).set});
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var getDesc = __webpack_require__(2).getDesc
, isObject = __webpack_require__(13)
, anObject = __webpack_require__(17);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(6)(Function.call, getDesc(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(13)
, meta = __webpack_require__(36).onFreeze;
__webpack_require__(49)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(3)
, core = __webpack_require__(5)
, fails = __webpack_require__(9);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(13)
, meta = __webpack_require__(36).onFreeze;
__webpack_require__(49)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(13)
, meta = __webpack_require__(36).onFreeze;
__webpack_require__(49)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(13);
__webpack_require__(49)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(13);
__webpack_require__(49)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(13);
__webpack_require__(49)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(20);
__webpack_require__(49)('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(18);
__webpack_require__(49)('getPrototypeOf', function($getPrototypeOf){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(18);
__webpack_require__(49)('keys', function($keys){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(49)('getOwnPropertyNames', function(){
return __webpack_require__(39).get;
});
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, isObject = __webpack_require__(13)
, HAS_INSTANCE = __webpack_require__(29)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = $.getProto(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(3);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(3)
, _isFinite = __webpack_require__(4).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(3);
$export($export.S, 'Number', {isInteger: __webpack_require__(63)});
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(13)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(3);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(3)
, isInteger = __webpack_require__(63)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(3);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(3);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.12 Number.parseFloat(string)
var $export = __webpack_require__(3);
$export($export.S, 'Number', {parseFloat: parseFloat});
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.13 Number.parseInt(string, radix)
var $export = __webpack_require__(3);
$export($export.S, 'Number', {parseInt: parseInt});
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(3)
, log1p = __webpack_require__(71)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
// V8 bug https://code.google.com/p/v8/issues/detail?id=3509
$export($export.S + $export.F * !($acosh && Math.floor($acosh(Number.MAX_VALUE)) == 710), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ },
/* 71 */
/***/ function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(3);
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
$export($export.S, 'Math', {asinh: asinh});
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(3)
, sign = __webpack_require__(75);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ },
/* 75 */
/***/ function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(3)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {expm1: __webpack_require__(79)});
/***/ },
/* 79 */
/***/ function(module, exports) {
// 20.2.2.14 Math.expm1(x)
module.exports = Math.expm1 || function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
};
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(3)
, sign = __webpack_require__(75)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(3)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, $$ = arguments
, $$len = $$.length
, larg = 0
, arg, div;
while(i < $$len){
arg = abs($$[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(3)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(9)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {log1p: __webpack_require__(71)});
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {sign: __webpack_require__(75)});
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(3)
, expm1 = __webpack_require__(79)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(9)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(3)
, expm1 = __webpack_require__(79)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(3);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, toIndex = __webpack_require__(23)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, $$ = arguments
, $$len = $$.length
, i = 0
, code;
while($$len > i){
code = +$$[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, toIObject = __webpack_require__(20)
, toLength = __webpack_require__(24);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, $$ = arguments
, $$len = $$.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < $$len)res.push(String($$[i]));
} return res.join('');
}
});
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(93)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, defined = __webpack_require__(19)
, fails = __webpack_require__(9)
, spaces = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3)
, $at = __webpack_require__(95)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(22)
, defined = __webpack_require__(19);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(3)
, toLength = __webpack_require__(24)
, context = __webpack_require__(97)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(99)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, $$ = arguments
, endPosition = $$.length > 1 ? $$[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(98)
, defined = __webpack_require__(19);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(13)
, cof = __webpack_require__(15)
, MATCH = __webpack_require__(29)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(29)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(3)
, context = __webpack_require__(97)
, INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(99)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(102)
});
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(22)
, defined = __webpack_require__(19);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(3)
, toLength = __webpack_require__(24)
, context = __webpack_require__(97)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(99)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, $$ = arguments
, index = toLength(Math.min($$.length > 1 ? $$[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(95)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(105)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(41)
, $export = __webpack_require__(3)
, redefine = __webpack_require__(34)
, hide = __webpack_require__(35)
, has = __webpack_require__(14)
, Iterators = __webpack_require__(106)
, $iterCreate = __webpack_require__(107)
, setToStringTag = __webpack_require__(37)
, getProto = __webpack_require__(2).getProto
, ITERATOR = __webpack_require__(29)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getProto($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 106 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, descriptor = __webpack_require__(10)
, setToStringTag = __webpack_require__(37)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(35)(IteratorPrototype, __webpack_require__(29)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(109)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, fails = __webpack_require__(9)
, defined = __webpack_require__(19)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(109)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(109)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(109)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(109)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(109)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(109)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(109)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(109)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(109)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(109)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(109)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(109)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(6)
, $export = __webpack_require__(3)
, toObject = __webpack_require__(18)
, call = __webpack_require__(123)
, isArrayIter = __webpack_require__(124)
, toLength = __webpack_require__(24)
, getIterFn = __webpack_require__(125);
$export($export.S + $export.F * !__webpack_require__(127)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, $$ = arguments
, $$len = $$.length
, mapfn = $$len > 1 ? $$[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value;
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
result[index] = mapping ? mapfn(O[index], index) : O[index];
}
}
result.length = index;
return result;
}
});
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(17);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ },
/* 124 */
/***/ function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(106)
, ITERATOR = __webpack_require__(29)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(126)
, ITERATOR = __webpack_require__(29)('iterator')
, Iterators = __webpack_require__(106);
module.exports = __webpack_require__(5).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(15)
, TAG = __webpack_require__(29)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = (O = Object(it))[TAG]) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(29)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ safe = true; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(9)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, $$ = arguments
, $$len = $$.length
, result = new (typeof this == 'function' ? this : Array)($$len);
while($$len > index)result[index] = $$[index++];
result.length = $$len;
return result;
}
});
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(130)
, step = __webpack_require__(131)
, Iterators = __webpack_require__(106)
, toIObject = __webpack_require__(20);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(105)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 130 */
/***/ function(module, exports) {
module.exports = function(){ /* empty */ };
/***/ },
/* 131 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(133)('Array');
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var core = __webpack_require__(5)
, $ = __webpack_require__(2)
, DESCRIPTORS = __webpack_require__(8)
, SPECIES = __webpack_require__(29)('species');
module.exports = function(KEY){
var C = core[KEY];
if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(3);
$export($export.P, 'Array', {copyWithin: __webpack_require__(135)});
__webpack_require__(130)('copyWithin');
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(18)
, toIndex = __webpack_require__(23)
, toLength = __webpack_require__(24);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, $$ = arguments
, end = $$.length > 2 ? $$[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(3);
$export($export.P, 'Array', {fill: __webpack_require__(137)});
__webpack_require__(130)('fill');
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(18)
, toIndex = __webpack_require__(23)
, toLength = __webpack_require__(24);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, $$ = arguments
, $$len = $$.length
, index = toIndex($$len > 1 ? $$[1] : undefined, length)
, end = $$len > 2 ? $$[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(3)
, $find = __webpack_require__(26)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(130)(KEY);
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(3)
, $find = __webpack_require__(26)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(130)(KEY);
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, LIBRARY = __webpack_require__(41)
, global = __webpack_require__(4)
, ctx = __webpack_require__(6)
, classof = __webpack_require__(126)
, $export = __webpack_require__(3)
, isObject = __webpack_require__(13)
, anObject = __webpack_require__(17)
, aFunction = __webpack_require__(7)
, strictNew = __webpack_require__(141)
, forOf = __webpack_require__(142)
, setProto = __webpack_require__(47).set
, same = __webpack_require__(45)
, speciesConstructor = __webpack_require__(143)
, asap = __webpack_require__(144)
, PROMISE = 'Promise'
, process = global.process
, isNode = classof(process) == 'process'
, P = global[PROMISE]
, Wrapper;
var testResolve = function(sub){
var test = new P(function(){});
if(sub)test.constructor = Object;
return P.resolve(test) === test;
};
var USE_NATIVE = function(){
var works = false;
function P2(x){
var self = new P(x);
setProto(self, P2.prototype);
return self;
}
try {
works = P && P.resolve && testResolve();
setProto(P2, P);
P2.prototype = $.create(P.prototype, {constructor: {value: P2}});
// actual Firefox has broken subclass support, test that
if(!(P2.resolve(5).then(function(){}) instanceof P2)){
works = false;
}
// actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162
if(works && __webpack_require__(8)){
var thenableThenGotten = false;
P.resolve($.setDesc({}, 'then', {
get: function(){ thenableThenGotten = true; }
}));
works = thenableThenGotten;
}
} catch(e){ works = false; }
return works;
}();
// helpers
var sameConstructor = function(a, b){
// library wrapper special case
if(LIBRARY && a === P && b === Wrapper)return true;
return same(a, b);
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var PromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve),
this.reject = aFunction(reject)
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(record, isReject){
if(record.n)return;
record.n = true;
var chain = record.c;
asap(function(){
var value = record.v
, ok = record.s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, result, then;
try {
if(handler){
if(!ok)record.h = true;
result = handler === true ? value : handler(value);
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
chain.length = 0;
record.n = false;
if(isReject)setTimeout(function(){
var promise = record.p
, handler, console;
if(isUnhandled(promise)){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
} record.a = undefined;
}, 1);
});
};
var isUnhandled = function(promise){
var record = promise._d
, chain = record.a || record.c
, i = 0
, reaction;
if(record.h)return false;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var $reject = function(value){
var record = this;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
record.v = value;
record.s = 2;
record.a = record.c.slice();
notify(record, true);
};
var $resolve = function(value){
var record = this
, then;
if(record.d)return;
record.d = true;
record = record.r || record; // unwrap
try {
if(record.p === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
asap(function(){
var wrapper = {r: record, d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
record.v = value;
record.s = 1;
notify(record, false);
}
} catch(e){
$reject.call({r: record, d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
P = function Promise(executor){
aFunction(executor);
var record = this._d = {
p: strictNew(this, P, PROMISE), // <- promise
c: [], // <- awaiting reactions
a: undefined, // <- checked in isUnhandled reactions
s: 0, // <- state
d: false, // <- done
v: undefined, // <- value
h: false, // <- handled rejection
n: false // <- notify
};
try {
executor(ctx($resolve, record, 1), ctx($reject, record, 1));
} catch(err){
$reject.call(record, err);
}
};
__webpack_require__(146)(P.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = new PromiseCapability(speciesConstructor(this, P))
, promise = reaction.promise
, record = this._d;
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
record.c.push(reaction);
if(record.a)record.a.push(reaction);
if(record.s)notify(record, false);
return promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P});
__webpack_require__(37)(P, PROMISE);
__webpack_require__(133)(PROMISE);
Wrapper = __webpack_require__(5)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = new PromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof P && sameConstructor(x.constructor, this))return x;
var capability = new PromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(127)(function(iter){
P.all(iter)['catch'](function(){});
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = new PromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject
, values = [];
var abrupt = perform(function(){
forOf(iterable, false, values.push, values);
var remaining = values.length
, results = Array(remaining);
if(remaining)$.each.call(values, function(promise, index){
var alreadyCalled = false;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
results[index] = value;
--remaining || resolve(results);
}, reject);
});
else resolve(results);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = new PromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ },
/* 141 */
/***/ function(module, exports) {
module.exports = function(it, Constructor, name){
if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!");
return it;
};
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(6)
, call = __webpack_require__(123)
, isArrayIter = __webpack_require__(124)
, anObject = __webpack_require__(17)
, toLength = __webpack_require__(24)
, getIterFn = __webpack_require__(125);
module.exports = function(iterable, entries, fn, that){
var iterFn = getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
call(iterator, f, step.value, entries);
}
};
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(17)
, aFunction = __webpack_require__(7)
, SPECIES = __webpack_require__(29)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, macrotask = __webpack_require__(145).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(15)(process) == 'process'
, head, last, notify;
var flush = function(){
var parent, domain, fn;
if(isNode && (parent = process.domain)){
process.domain = null;
parent.exit();
}
while(head){
domain = head.domain;
fn = head.fn;
if(domain)domain.enter();
fn(); // <- currently we use it only for Promise - try / catch not required
if(domain)domain.exit();
head = head.next;
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = 1
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = -toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
notify = function(){
Promise.resolve().then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
module.exports = function asap(fn){
var task = {fn: fn, next: undefined, domain: isNode && process.domain};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(6)
, invoke = __webpack_require__(16)
, html = __webpack_require__(11)
, cel = __webpack_require__(12)
, global = __webpack_require__(4)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listner = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(15)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listner;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listner, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(34);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(148);
// 23.1 Map Objects
__webpack_require__(149)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, hide = __webpack_require__(35)
, redefineAll = __webpack_require__(146)
, ctx = __webpack_require__(6)
, strictNew = __webpack_require__(141)
, defined = __webpack_require__(19)
, forOf = __webpack_require__(142)
, $iterDefine = __webpack_require__(105)
, step = __webpack_require__(131)
, setSpecies = __webpack_require__(133)
, DESCRIPTORS = __webpack_require__(8)
, fastKey = __webpack_require__(36).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = $.create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)$.setDesc(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, global = __webpack_require__(4)
, $export = __webpack_require__(3)
, meta = __webpack_require__(36)
, fails = __webpack_require__(9)
, hide = __webpack_require__(35)
, redefineAll = __webpack_require__(146)
, forOf = __webpack_require__(142)
, strictNew = __webpack_require__(141)
, isObject = __webpack_require__(13)
, setToStringTag = __webpack_require__(37)
, DESCRIPTORS = __webpack_require__(8);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
C = wrapper(function(target, iterable){
strictNew(target, C, NAME);
target._c = new Base;
if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target);
});
$.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){
var IS_ADDER = KEY == 'add' || KEY == 'set';
if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){
if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false;
var result = this._c[KEY](a === 0 ? 0 : a, b);
return IS_ADDER ? this : result;
});
});
if('size' in proto)$.setDesc(C.prototype, 'size', {
get: function(){
return this._c.size;
}
});
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F, O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(148);
// 23.2 Set Objects
__webpack_require__(149)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(2).each
, redefine = __webpack_require__(34)
, meta = __webpack_require__(36)
, assign = __webpack_require__(43)
, weak = __webpack_require__(152)
, isObject = __webpack_require__(13)
, has = __webpack_require__(14)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = __webpack_require__(149)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each.call(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(146)
, getWeak = __webpack_require__(36).getWeak
, anObject = __webpack_require__(17)
, isObject = __webpack_require__(13)
, strictNew = __webpack_require__(141)
, forOf = __webpack_require__(142)
, createArrayMethod = __webpack_require__(26)
, $has = __webpack_require__(14)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new FrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(152);
// 23.4 WeakSet Objects
__webpack_require__(149)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(3)
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(target, thisArgument, argumentsList);
}
});
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $ = __webpack_require__(2)
, $export = __webpack_require__(3)
, aFunction = __webpack_require__(7)
, anObject = __webpack_require__(17)
, isObject = __webpack_require__(13)
, bind = Function.bind || __webpack_require__(5).Function.prototype.bind;
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * __webpack_require__(9)(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
if(args != undefined)switch(anObject(args).length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = $.create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var $ = __webpack_require__(2)
, $export = __webpack_require__(3)
, anObject = __webpack_require__(17);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(9)(function(){
Reflect.defineProperty($.setDesc({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
try {
$.setDesc(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(3)
, getDesc = __webpack_require__(2).getDesc
, anObject = __webpack_require__(17);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = getDesc(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(3)
, anObject = __webpack_require__(17);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
__webpack_require__(107)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var $ = __webpack_require__(2)
, has = __webpack_require__(14)
, $export = __webpack_require__(3)
, isObject = __webpack_require__(13)
, anObject = __webpack_require__(17);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = $.getDesc(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = $.getProto(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var $ = __webpack_require__(2)
, $export = __webpack_require__(3)
, anObject = __webpack_require__(17);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return $.getDesc(anObject(target), propertyKey);
}
});
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(3)
, getProto = __webpack_require__(2).getProto
, anObject = __webpack_require__(17);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(3);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(3)
, anObject = __webpack_require__(17)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(3);
$export($export.S, 'Reflect', {ownKeys: __webpack_require__(165)});
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var $ = __webpack_require__(2)
, anObject = __webpack_require__(17)
, Reflect = __webpack_require__(4).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = $.getNames(anObject(it))
, getSymbols = $.getSymbols;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(3)
, anObject = __webpack_require__(17)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var $ = __webpack_require__(2)
, has = __webpack_require__(14)
, $export = __webpack_require__(3)
, createDesc = __webpack_require__(10)
, anObject = __webpack_require__(17)
, isObject = __webpack_require__(13);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = $.getDesc(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = $.getProto(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = $.getDesc(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
$.setDesc(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(3)
, setProto = __webpack_require__(47);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 169 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3)
, $includes = __webpack_require__(32)(true);
$export($export.P, 'Array', {
// https://github.com/domenic/Array.prototype.includes
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(130)('includes');
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(3)
, $at = __webpack_require__(95)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3)
, $pad = __webpack_require__(172);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(24)
, repeat = __webpack_require__(102)
, defined = __webpack_require__(19);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength)return S;
if(fillStr == '')fillStr = ' ';
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3)
, $pad = __webpack_require__(172);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(93)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
/***/ },
/* 175 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(93)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/WebReflection/9353781
var $ = __webpack_require__(2)
, $export = __webpack_require__(3)
, ownKeys = __webpack_require__(165)
, toIObject = __webpack_require__(20)
, createDesc = __webpack_require__(10);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, setDesc = $.setDesc
, getDesc = $.getDesc
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i){
D = getDesc(O, key = keys[i++]);
if(key in result)setDesc(result, key, createDesc(0, D));
else result[key] = D;
} return result;
}
});
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
// http://goo.gl/XkBrjD
var $export = __webpack_require__(3)
, $values = __webpack_require__(178)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, toIObject = __webpack_require__(20)
, isEnum = $.isEnum;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = $.getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
// http://goo.gl/XkBrjD
var $export = __webpack_require__(3)
, $entries = __webpack_require__(178)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(3);
$export($export.P, 'Map', {toJSON: __webpack_require__(181)('Map')});
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var forOf = __webpack_require__(142)
, classof = __webpack_require__(126);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
var arr = [];
forOf(this, false, arr.push, arr);
return arr;
};
};
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(3);
$export($export.P, 'Set', {toJSON: __webpack_require__(181)('Set')});
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-global
var $export = __webpack_require__(3);
$export($export.S, 'System', {global: __webpack_require__(4)});
/***/ },
/* 184 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(3)
, cof = __webpack_require__(15);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
/***/ },
/* 185 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, $task = __webpack_require__(145);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(129);
var global = __webpack_require__(4)
, hide = __webpack_require__(35)
, Iterators = __webpack_require__(106)
, TO_STRING_TAG = __webpack_require__(29)('toStringTag')
, ArrayValues = Iterators.Array;
__webpack_require__(2).each.call((
'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' +
'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList'
).split(','), function(NAME){
var Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
});
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(4)
, $export = __webpack_require__(3)
, invoke = __webpack_require__(16)
, partial = __webpack_require__(188)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var path = __webpack_require__(189)
, invoke = __webpack_require__(16)
, aFunction = __webpack_require__(7);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, $$ = arguments
, $$len = $$.length
, j = 0, k = 0, args;
if(!holder && !$$len)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = $$[k++];
while($$len > k)args.push($$[k++]);
return invoke(fn, args, that);
};
};
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(5);
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $ = __webpack_require__(2)
, ctx = __webpack_require__(6)
, $export = __webpack_require__(3)
, createDesc = __webpack_require__(10)
, assign = __webpack_require__(43)
, keyOf = __webpack_require__(38)
, aFunction = __webpack_require__(7)
, forOf = __webpack_require__(142)
, isIterable = __webpack_require__(191)
, $iterCreate = __webpack_require__(107)
, step = __webpack_require__(131)
, isObject = __webpack_require__(13)
, toIObject = __webpack_require__(20)
, DESCRIPTORS = __webpack_require__(8)
, has = __webpack_require__(14)
, getKeys = $.getKeys;
// 0 -> Dict.forEach
// 1 -> Dict.map
// 2 -> Dict.filter
// 3 -> Dict.some
// 4 -> Dict.every
// 5 -> Dict.find
// 6 -> Dict.findKey
// 7 -> Dict.mapPairs
var createDictMethod = function(TYPE){
var IS_MAP = TYPE == 1
, IS_EVERY = TYPE == 4;
return function(object, callbackfn, that /* = undefined */){
var f = ctx(callbackfn, that, 3)
, O = toIObject(object)
, result = IS_MAP || TYPE == 7 || TYPE == 2
? new (typeof this == 'function' ? this : Dict) : undefined
, key, val, res;
for(key in O)if(has(O, key)){
val = O[key];
res = f(val, key, object);
if(TYPE){
if(IS_MAP)result[key] = res; // map
else if(res)switch(TYPE){
case 2: result[key] = val; break; // filter
case 3: return true; // some
case 5: return val; // find
case 6: return key; // findKey
case 7: result[res[0]] = res[1]; // mapPairs
} else if(IS_EVERY)return false; // every
}
}
return TYPE == 3 || IS_EVERY ? IS_EVERY : result;
};
};
var findKey = createDictMethod(6);
var createDictIter = function(kind){
return function(it){
return new DictIterator(it, kind);
};
};
var DictIterator = function(iterated, kind){
this._t = toIObject(iterated); // target
this._a = getKeys(iterated); // keys
this._i = 0; // next index
this._k = kind; // kind
};
$iterCreate(DictIterator, 'Dict', function(){
var that = this
, O = that._t
, keys = that._a
, kind = that._k
, key;
do {
if(that._i >= keys.length){
that._t = undefined;
return step(1);
}
} while(!has(O, key = keys[that._i++]));
if(kind == 'keys' )return step(0, key);
if(kind == 'values')return step(0, O[key]);
return step(0, [key, O[key]]);
});
function Dict(iterable){
var dict = $.create(null);
if(iterable != undefined){
if(isIterable(iterable)){
forOf(iterable, true, function(key, value){
dict[key] = value;
});
} else assign(dict, iterable);
}
return dict;
}
Dict.prototype = null;
function reduce(object, mapfn, init){
aFunction(mapfn);
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, i = 0
, memo, key;
if(arguments.length < 3){
if(!length)throw TypeError('Reduce of empty object with no initial value');
memo = O[keys[i++]];
} else memo = Object(init);
while(length > i)if(has(O, key = keys[i++])){
memo = mapfn(memo, O[key], key, object);
}
return memo;
}
function includes(object, el){
return (el == el ? keyOf(object, el) : findKey(object, function(it){
return it != it;
})) !== undefined;
}
function get(object, key){
if(has(object, key))return object[key];
}
function set(object, key, value){
if(DESCRIPTORS && key in Object)$.setDesc(object, key, createDesc(0, value));
else object[key] = value;
return object;
}
function isDict(it){
return isObject(it) && $.getProto(it) === Dict.prototype;
}
$export($export.G + $export.F, {Dict: Dict});
$export($export.S, 'Dict', {
keys: createDictIter('keys'),
values: createDictIter('values'),
entries: createDictIter('entries'),
forEach: createDictMethod(0),
map: createDictMethod(1),
filter: createDictMethod(2),
some: createDictMethod(3),
every: createDictMethod(4),
find: createDictMethod(5),
findKey: findKey,
mapPairs: createDictMethod(7),
reduce: reduce,
keyOf: keyOf,
includes: includes,
has: has,
get: get,
set: set,
isDict: isDict
});
/***/ },
/* 191 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(126)
, ITERATOR = __webpack_require__(29)('iterator')
, Iterators = __webpack_require__(106);
module.exports = __webpack_require__(5).isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
/***/ },
/* 192 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(17)
, get = __webpack_require__(125);
module.exports = __webpack_require__(5).getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(4)
, core = __webpack_require__(5)
, $export = __webpack_require__(3)
, partial = __webpack_require__(188);
// https://esdiscuss.org/topic/promise-returning-delay-function
$export($export.G + $export.F, {
delay: function delay(time){
return new (core.Promise || global.Promise)(function(resolve){
setTimeout(partial.call(resolve, true), time);
});
}
});
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
var path = __webpack_require__(189)
, $export = __webpack_require__(3);
// Placeholder
__webpack_require__(5)._ = path._ = path._ || {};
$export($export.P + $export.F, 'Function', {part: __webpack_require__(188)});
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3);
$export($export.S + $export.F, 'Object', {isObject: __webpack_require__(13)});
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3);
$export($export.S + $export.F, 'Object', {classof: __webpack_require__(126)});
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, define = __webpack_require__(198);
$export($export.S + $export.F, 'Object', {define: define});
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(2)
, ownKeys = __webpack_require__(165)
, toIObject = __webpack_require__(20);
module.exports = function define(target, mixin){
var keys = ownKeys(toIObject(mixin))
, length = keys.length
, i = 0, key;
while(length > i)$.setDesc(target, key = keys[i++], $.getDesc(mixin, key));
return target;
};
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(3)
, define = __webpack_require__(198)
, create = __webpack_require__(2).create;
$export($export.S + $export.F, 'Object', {
make: function(proto, mixin){
return define(create(proto), mixin);
}
});
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(105)(Number, 'Number', function(iterated){
this._l = +iterated;
this._i = 0;
}, function(){
var i = this._i++
, done = !(i < this._l);
return {done: done, value: done ? undefined : i};
});
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/benjamingr/RexExp.escape
var $export = __webpack_require__(3)
, $re = __webpack_require__(202)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
/***/ },
/* 202 */
/***/ function(module, exports) {
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3);
var $re = __webpack_require__(202)(/[&<>"']/g, {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
});
$export($export.P + $export.F, 'String', {escapeHTML: function escapeHTML(){ return $re(this); }});
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(3);
var $re = __webpack_require__(202)(/&(?:amp|lt|gt|quot|apos);/g, {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
});
$export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }});
/***/ }
/******/ ]);
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = __e;
// RequireJS export
else if(typeof define == 'function' && define.amd)define(function(){return __e});
// Export to global object
else __g.core = __e;
}(1, 1);
|
components/Queue.js
|
reneechar/React-Kanban
|
import React from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
import {receiveTasks} from '../actions/kanbanActions';
import styles from './sass/items.scss';
import EditTask from './EditTask';
import EditButton from './EditButton';
import MoveProgressButton from './MoveProgressButton';
import DeleteButton from './DeleteButton';
class Queue extends React.Component {
constructor() {
super()
}
render() {
let priority;
if (this.props.priority === 3) {
priority = 'High';
} else if (this.props.priority === 2) {
priority = 'Medium';
} else {
priority = 'Low';
}
let renderedElement;
if(this.props.showEditForm && this.props.user) {
renderedElement = (
<div >
<EditTask
title={this.props.title}
createdBy={this.props.createdBy}
assignedTo={this.props.assignedTo}
priority={this.props.priority}
index={this.props.index}
id={this.props.id}
/>
</div>
)
} else if (this.props.user) {
renderedElement = (
<div className={styles.item}>
<div className={styles.left}>
<p id={styles.taskTitle}>{this.props.title}</p>
<p>Priority: {priority}</p>
<p>Assigned By: {this.props.createdBy}</p>
<div id={styles.queueButtons} className={styles.buttonsContainer}>
<EditButton index={this.props.index} />
<DeleteButton id={this.props.id} />
<MoveProgressButton id={this.props.id} arrow={'>'} />
</div>
</div>
<div className={styles.right}>
<div className={styles.assignedTo}>
<p>{this.props.assignedTo}</p>
</div>
</div>
</div>
)
} else {
renderedElement = (
<div className={styles.item}>
<div className={styles.left}>
<p id={styles.taskTitle}>{this.props.title}</p>
<p>Priority: {priority}</p>
<p>Created By: {this.props.createdBy}</p>
</div>
<div className={styles.right}>
<p>{this.props.assignedTo}</p>
</div>
</div>
)
}
return(
<div id={styles.queueBorder} className={styles.list} >
{ renderedElement }
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
const { kanbanReducer } = state;
return {
user: kanbanReducer.get('login')
}
}
export default connect(
mapStateToProps
)(Queue);
|
test/components/ComicList.spec.js
|
rickychien/comiz
|
import expect from 'expect'
import { shallow } from 'enzyme'
import React from 'react'
import { ComicList } from '../../src/components/ComicList'
describe('<ComicList />', () => {
let props
beforeEach(() => {
props = {
comics: undefined,
isFetching: undefined,
fetchError: undefined,
onComicItemClick: undefined,
}
})
it('should render correctly', () => {
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.is('div')).toBe(true)
expect(wrapper.find('AppBar').length).toBe(1)
expect(wrapper.find('ComicItem').length).toBe(0)
})
it('should render correctly with comics', () => {
props.comics = [{ id: 1 }, { id: 2 }, { id: 3 }]
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.find('div.comicList').length).toBe(1)
expect(wrapper.find('ComicItem').length).toBe(props.comics.length)
})
it('should render correctly with isFetching', () => {
props.isFetching = true
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.find('i.loading-spinner').length).toBe(1)
})
it('should render correctly with isFetching and many comics', () => {
props.fetchError = true
props.comics = [{ id: 1 }, { id: 2 }, { id: 3 }]
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.find('div.comicList').length).toBe(1)
expect(wrapper.find('ComicItem').length).toBe(props.comics.length)
})
it('should render correctly with fetchError', () => {
props.fetchError = true
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.find('.statusPage h2').text()).toBe('Unable to find comics')
})
it('should render correctly with fetchError and comics', () => {
props.fetchError = true
props.comics = [{ id: 1 }, { id: 2 }, { id: 3 }]
const wrapper = shallow(<ComicList { ...props } />)
expect(wrapper.find('div.comicList').length).toBe(1)
expect(wrapper.find('ComicItem').length).toBe(props.comics.length)
})
})
|
ajax/libs/adapterjs/0.13.0/adapter.screenshare.js
|
emmy41124/cdnjs
|
/*! adapterjs - v0.13.0 - 2016-01-08 */
// Adapter's interface.
var AdapterJS = AdapterJS || {};
// Browserify compatibility
if(typeof exports !== 'undefined') {
module.exports = AdapterJS;
}
AdapterJS.options = AdapterJS.options || {};
// uncomment to get virtual webcams
// AdapterJS.options.getAllCams = true;
// uncomment to prevent the install prompt when the plugin in not yet installed
// AdapterJS.options.hidePluginInstallPrompt = true;
// AdapterJS version
AdapterJS.VERSION = '0.13.0';
// This function will be called when the WebRTC API is ready to be used
// Whether it is the native implementation (Chrome, Firefox, Opera) or
// the plugin
// You may Override this function to synchronise the start of your application
// with the WebRTC API being ready.
// If you decide not to override use this synchronisation, it may result in
// an extensive CPU usage on the plugin start (once per tab loaded)
// Params:
// - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
//
AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
// The WebRTC API is ready.
// Override me and do whatever you want here
};
// New interface to store multiple callbacks, private
AdapterJS._onwebrtcreadies = [];
// Sets a callback function to be called when the WebRTC interface is ready.
// The first argument is the function to callback.\
// Throws an error if the first argument is not a function
AdapterJS.webRTCReady = function (callback) {
if (typeof callback !== 'function') {
throw new Error('Callback provided is not a function');
}
if (true === AdapterJS.onwebrtcreadyDone) {
// All WebRTC interfaces are ready, just call the callback
callback(null !== AdapterJS.WebRTCPlugin.plugin);
} else {
// will be triggered automatically when your browser/plugin is ready.
AdapterJS._onwebrtcreadies.push(callback);
}
};
// Plugin namespace
AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
// The object to store plugin information
AdapterJS.WebRTCPlugin.pluginInfo = {
prefix : 'Tem',
plugName : 'TemWebRTCPlugin',
pluginId : 'plugin0',
type : 'application/x-temwebrtcplugin',
onload : '__TemWebRTCReady0',
portalLink : 'http://skylink.io/plugin/',
downloadLink : null, //set below
companyName: 'Temasys'
};
if(!!navigator.platform.match(/^Mac/i)) {
AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
}
else if(!!navigator.platform.match(/^Win/i)) {
AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
}
AdapterJS.WebRTCPlugin.TAGS = {
NONE : 'none',
AUDIO : 'audio',
VIDEO : 'video'
};
// Unique identifier of each opened page
AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
// Use this whenever you want to call the plugin.
AdapterJS.WebRTCPlugin.plugin = null;
// Set log level for the plugin once it is ready.
// The different values are
// This is an asynchronous function that will run when the plugin is ready
AdapterJS.WebRTCPlugin.setLogLevel = null;
// Defines webrtc's JS interface according to the plugin's implementation.
// Define plugin Browsers as WebRTC Interface.
AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
// This function detects whether or not a plugin is installed.
// Checks if Not IE (firefox, for example), else if it's IE,
// we're running IE and do something. If not it is not supported.
AdapterJS.WebRTCPlugin.isPluginInstalled = null;
// Lets adapter.js wait until the the document is ready before injecting the plugin
AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
// Inject the HTML DOM object element into the page.
AdapterJS.WebRTCPlugin.injectPlugin = null;
// States of readiness that the plugin goes through when
// being injected and stated
AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
NONE : 0, // no plugin use
INITIALIZING : 1, // Detected need for plugin
INJECTING : 2, // Injecting plugin
INJECTED: 3, // Plugin element injected but not usable yet
READY: 4 // Plugin ready to be used
};
// Current state of the plugin. You cannot use the plugin before this is
// equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
// True is AdapterJS.onwebrtcready was already called, false otherwise
// Used to make sure AdapterJS.onwebrtcready is only called once
AdapterJS.onwebrtcreadyDone = false;
// Log levels for the plugin.
// To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
/*
Log outputs are prefixed in some cases.
INFO: Information reported by the plugin.
ERROR: Errors originating from within the plugin.
WEBRTC: Error originating from within the libWebRTC library
*/
// From the least verbose to the most verbose
AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
NONE : 'NONE',
ERROR : 'ERROR',
WARNING : 'WARNING',
INFO: 'INFO',
VERBOSE: 'VERBOSE',
SENSITIVE: 'SENSITIVE'
};
// Does a waiting check before proceeding to load the plugin.
AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
// This methid will use an interval to wait for the plugin to be ready.
AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
// !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
// This function will be called when plugin is ready. It sends necessary
// details to the plugin.
// The function will wait for the document to be ready and the set the
// plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
// indicating that it can start being requested.
// This function is not in the IE/Safari condition brackets so that
// TemPluginLoaded function might be called on Chrome/Firefox.
// This function is the only private function that is not encapsulated to
// allow the plugin method to be called.
__TemWebRTCReady0 = function () {
webrtcDetectedVersion = AdapterJS.WebRTCPlugin.plugin.version;
if (document.readyState === 'complete') {
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
AdapterJS.maybeThroughWebRTCReady();
} else {
AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
if (document.readyState === 'complete') {
// TODO: update comments, we wait for the document to be ready
clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
AdapterJS.maybeThroughWebRTCReady();
}
}, 100);
}
};
AdapterJS.maybeThroughWebRTCReady = function() {
if (!AdapterJS.onwebrtcreadyDone) {
AdapterJS.onwebrtcreadyDone = true;
// If new interface for multiple callbacks used
if (AdapterJS._onwebrtcreadies.length) {
AdapterJS._onwebrtcreadies.forEach(function (callback) {
if (typeof(callback) === 'function') {
callback(AdapterJS.WebRTCPlugin.plugin !== null);
}
});
// Else if no callbacks on new interface assuming user used old(deprecated) way to set callback through AdapterJS.onwebrtcready = ...
} else if (typeof(AdapterJS.onwebrtcready) === 'function') {
AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
}
}
};
// Text namespace
AdapterJS.TEXT = {
PLUGIN: {
REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
'to work on this browser.',
NOT_SUPPORTED: 'Your browser does not support WebRTC.',
BUTTON: 'Install Now'
},
REFRESH: {
REQUIRE_REFRESH: 'Please refresh page',
BUTTON: 'Refresh Page'
}
};
// The result of ice connection states.
// - starting: Ice connection is starting.
// - checking: Ice connection is checking.
// - connected Ice connection is connected.
// - completed Ice connection is connected.
// - done Ice connection has been completed.
// - disconnected Ice connection has been disconnected.
// - failed Ice connection has failed.
// - closed Ice connection is closed.
AdapterJS._iceConnectionStates = {
starting : 'starting',
checking : 'checking',
connected : 'connected',
completed : 'connected',
done : 'completed',
disconnected : 'disconnected',
failed : 'failed',
closed : 'closed'
};
//The IceConnection states that has been fired for each peer.
AdapterJS._iceConnectionFiredStates = [];
// Check if WebRTC Interface is defined.
AdapterJS.isDefined = null;
// This function helps to retrieve the webrtc detected browser information.
// This sets:
// - webrtcDetectedBrowser: The browser agent name.
// - webrtcDetectedVersion: The browser version.
// - webrtcDetectedType: The types of webRTC support.
// - 'moz': Mozilla implementation of webRTC.
// - 'webkit': WebKit implementation of webRTC.
// - 'plugin': Using the plugin implementation.
AdapterJS.parseWebrtcDetectedBrowser = function () {
var hasMatch, checkMatch = navigator.userAgent.match(
/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(checkMatch[1])) {
hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
webrtcDetectedBrowser = 'IE';
webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
} else if (checkMatch[1] === 'Chrome') {
hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
if (hasMatch !== null) {
webrtcDetectedBrowser = 'opera';
webrtcDetectedVersion = parseInt(hasMatch[1], 10);
}
}
if (navigator.userAgent.indexOf('Safari')) {
if (typeof InstallTrigger !== 'undefined') {
webrtcDetectedBrowser = 'firefox';
} else if (/*@cc_on!@*/ false || !!document.documentMode) {
webrtcDetectedBrowser = 'IE';
} else if (
Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
webrtcDetectedBrowser = 'safari';
} else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
webrtcDetectedBrowser = 'opera';
} else if (!!window.chrome) {
webrtcDetectedBrowser = 'chrome';
}
}
if (!webrtcDetectedBrowser) {
webrtcDetectedVersion = checkMatch[1];
}
if (!webrtcDetectedVersion) {
try {
checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
[navigator.appName, navigator.appVersion, '-?'];
if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
checkMatch.splice(1, 1, hasMatch[1]);
}
webrtcDetectedVersion = parseInt(checkMatch[1], 10);
} catch (error) { }
}
};
// To fix configuration as some browsers does not support
// the 'urls' attribute.
AdapterJS.maybeFixConfiguration = function (pcConfig) {
if (pcConfig === null) {
return;
}
for (var i = 0; i < pcConfig.iceServers.length; i++) {
if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
delete pcConfig.iceServers[i].urls;
}
}
};
AdapterJS.addEvent = function(elem, evnt, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt, func, false);
} else if (elem.attachEvent) {// OLD IE DOM
elem.attachEvent('on'+evnt, func);
} else { // No much to do
elem[evnt] = func;
}
};
AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
// only inject once the page is ready
if (document.readyState !== 'complete') {
return;
}
var w = window;
var i = document.createElement('iframe');
i.style.position = 'fixed';
i.style.top = '-41px';
i.style.left = 0;
i.style.right = 0;
i.style.width = '100%';
i.style.height = '40px';
i.style.backgroundColor = '#ffffe1';
i.style.border = 'none';
i.style.borderBottom = '1px solid #888888';
i.style.zIndex = '9999999';
if(typeof i.style.webkitTransition === 'string') {
i.style.webkitTransition = 'all .5s ease-out';
} else if(typeof i.style.transition === 'string') {
i.style.transition = 'all .5s ease-out';
}
document.body.appendChild(i);
c = (i.contentWindow) ? i.contentWindow :
(i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
c.document.open();
c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
'middle; cursor: default;">' + text + '</span>');
if(buttonText && buttonLink) {
c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
c.document.close();
// On click on okay
AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
if (!!displayRefreshBar) {
AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
}
window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
e.preventDefault();
try {
event.cancelBubble = true;
} catch(error) { }
var pluginInstallInterval = setInterval(function(){
if(! isIE) {
navigator.plugins.refresh(false);
}
AdapterJS.WebRTCPlugin.isPluginInstalled(
AdapterJS.WebRTCPlugin.pluginInfo.prefix,
AdapterJS.WebRTCPlugin.pluginInfo.plugName,
function() { // plugin now installed
clearInterval(pluginInstallInterval);
AdapterJS.WebRTCPlugin.defineWebRTCInterface();
},
function() {
// still no plugin detected, nothing to do
});
} , 500);
});
// On click on Cancel
AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
w.document.body.removeChild(i);
});
} else {
c.document.close();
}
setTimeout(function() {
if(typeof i.style.webkitTransform === 'string') {
i.style.webkitTransform = 'translateY(40px)';
} else if(typeof i.style.transform === 'string') {
i.style.transform = 'translateY(40px)';
} else {
i.style.top = '0px';
}
}, 300);
};
// -----------------------------------------------------------
// Detected webrtc implementation. Types are:
// - 'moz': Mozilla implementation of webRTC.
// - 'webkit': WebKit implementation of webRTC.
// - 'plugin': Using the plugin implementation.
webrtcDetectedType = null;
// Set the settings for creating DataChannels, MediaStream for
// Cross-browser compability.
// - This is only for SCTP based support browsers.
// the 'urls' attribute.
checkMediaDataChannelSettings =
function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
if (typeof callback !== 'function') {
return;
}
var beOfferer = true;
var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
// Nightly version does not require MozDontOfferDataChannel for interop
var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
var isPeerFirefox = peerBrowserAgent === 'firefox';
var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
// Resends an updated version of constraints for MozDataChannel to work
// If other userAgent is firefox and user is firefox, remove MozDataChannel
if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
try {
delete constraints.mandatory.MozDontOfferDataChannel;
} catch (error) {
console.error('Failed deleting MozDontOfferDataChannel');
console.error(error);
}
} else if ((isLocalFirefox && !isPeerFirefox)) {
constraints.mandatory.MozDontOfferDataChannel = true;
}
if (!isLocalFirefox) {
// temporary measure to remove Moz* constraints in non Firefox browsers
for (var prop in constraints.mandatory) {
if (constraints.mandatory.hasOwnProperty(prop)) {
if (prop.indexOf('Moz') !== -1) {
delete constraints.mandatory[prop];
}
}
}
}
// Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
// interopability of the media stream
if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
beOfferer = false;
}
callback(beOfferer, constraints);
};
// Handles the differences for all browsers ice connection state output.
// - Tested outcomes are:
// - Chrome (offerer) : 'checking' > 'completed' > 'completed'
// - Chrome (answerer) : 'checking' > 'connected'
// - Firefox (offerer) : 'checking' > 'connected'
// - Firefox (answerer): 'checking' > 'connected'
checkIceConnectionState = function (peerId, iceConnectionState, callback) {
if (typeof callback !== 'function') {
console.warn('No callback specified in checkIceConnectionState. Aborted.');
return;
}
peerId = (peerId) ? peerId : 'peer';
if (!AdapterJS._iceConnectionFiredStates[peerId] ||
iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
iceConnectionState === AdapterJS._iceConnectionStates.failed ||
iceConnectionState === AdapterJS._iceConnectionStates.closed) {
AdapterJS._iceConnectionFiredStates[peerId] = [];
}
iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
setTimeout(function () {
AdapterJS._iceConnectionFiredStates[peerId]
.push(AdapterJS._iceConnectionStates.done);
callback(AdapterJS._iceConnectionStates.done);
}, 1000);
}
callback(iceConnectionState);
}
return;
};
// Firefox:
// - Creates iceServer from the url for Firefox.
// - Create iceServer with stun url.
// - Create iceServer with turn url.
// - Ignore the transport parameter from TURN url for FF version <=27.
// - Return null for createIceServer if transport=tcp.
// - FF 27 and above supports transport parameters in TURN url,
// - So passing in the full url to create iceServer.
// Chrome:
// - Creates iceServer from the url for Chrome M33 and earlier.
// - Create iceServer with stun url.
// - Chrome M28 & above uses below TURN format.
// Plugin:
// - Creates Ice Server for Plugin Browsers
// - If Stun - Create iceServer with stun url.
// - Else - Create iceServer with turn url
// - This is a WebRTC Function
createIceServer = null;
// Firefox:
// - Creates IceServers for Firefox
// - Use .url for FireFox.
// - Multiple Urls support
// Chrome:
// - Creates iceServers from the urls for Chrome M34 and above.
// - .urls is supported since Chrome M34.
// - Multiple Urls support
// Plugin:
// - Creates Ice Servers for Plugin Browsers
// - Multiple Urls support
// - This is a WebRTC Function
createIceServers = null;
//------------------------------------------------------------
//The RTCPeerConnection object.
RTCPeerConnection = null;
// Creates RTCSessionDescription object for Plugin Browsers
RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
RTCSessionDescription : null;
// Creates RTCIceCandidate object for Plugin Browsers
RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
RTCIceCandidate : null;
// Get UserMedia (only difference is the prefix).
// Code from Adam Barth.
getUserMedia = null;
// Attach a media stream to an element.
attachMediaStream = null;
// Re-attach a media stream to an element.
reattachMediaStream = null;
// Detected browser agent name. Types are:
// - 'firefox': Firefox browser.
// - 'chrome': Chrome browser.
// - 'opera': Opera browser.
// - 'safari': Safari browser.
// - 'IE' - Internet Explorer browser.
webrtcDetectedBrowser = null;
// Detected browser version.
webrtcDetectedVersion = null;
// Check for browser types and react accordingly
if ( navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| (navigator.mediaDevices
&& navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) ) {
///////////////////////////////////////////////////////////////////
// INJECTION OF GOOGLE'S ADAPTER.JS CONTENT
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* More information about these options at jshint.com/docs/options */
/* jshint browser: true, camelcase: true, curly: true, devel: true,
eqeqeq: true, forin: false, globalstrict: true, node: true,
quotmark: single, undef: true, unused: strict */
/* global mozRTCIceCandidate, mozRTCPeerConnection, Promise,
mozRTCSessionDescription, webkitRTCPeerConnection, MediaStreamTrack */
/* exported trace,requestUserMedia */
'use strict';
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;
var webrtcMinimumVersion = null;
var webrtcUtils = {
log: function() {
// suppress console.log output when being included as a module.
if (typeof module !== 'undefined' ||
typeof require === 'function' && typeof define === 'function') {
return;
}
console.log.apply(console, arguments);
},
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos]);
}
};
function trace(text) {
// This function is used for logging.
if (text[text.length - 1] === '\n') {
text = text.substring(0, text.length - 1);
}
if (window.performance) {
var now = (window.performance.now() / 1000).toFixed(3);
webrtcUtils.log(now + ': ' + text);
} else {
webrtcUtils.log(text);
}
}
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
// If prefixed srcObject property exists, return it.
// Otherwise use the shimmed property, _srcObject
return 'mozSrcObject' in this ? this.mozSrcObject : this._srcObject;
},
set: function(stream) {
if ('mozSrcObject' in this) {
this.mozSrcObject = stream;
} else {
// Use _srcObject as a private property for this shim
this._srcObject = stream;
// TODO: revokeObjectUrl(this.src) when !stream to release resources?
this.src = URL.createObjectURL(stream);
}
}
});
}
// Proxy existing globals
getUserMedia = window.navigator && window.navigator.getUserMedia;
}
// Attach a media stream to an element.
attachMediaStream = function(element, stream) {
element.srcObject = stream;
};
reattachMediaStream = function(to, from) {
to.srcObject = from.srcObject;
};
if (typeof window === 'undefined' || !window.navigator) {
webrtcUtils.log('This does not appear to be a browser');
webrtcDetectedBrowser = 'not a browser';
} else if (navigator.mozGetUserMedia && window.mozRTCPeerConnection) {
webrtcUtils.log('This appears to be Firefox');
webrtcDetectedBrowser = 'firefox';
// the detected firefox version.
webrtcDetectedVersion = webrtcUtils.extractVersion(navigator.userAgent,
/Firefox\/([0-9]+)\./, 1);
// the minimum firefox version still supported by adapter.
webrtcMinimumVersion = 31;
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (webrtcDetectedVersion < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors
};
// The RTCSessionDescription object.
if (!window.RTCSessionDescription) {
window.RTCSessionDescription = mozRTCSessionDescription;
}
// The RTCIceCandidate object.
if (!window.RTCIceCandidate) {
window.RTCIceCandidate = mozRTCIceCandidate;
}
// getUserMedia constraints shim.
getUserMedia = function(constraints, onSuccess, onError) {
var constraintsToFF37 = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r.min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
if (webrtcDetectedVersion < 38) {
webrtcUtils.log('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37(constraints.video);
}
webrtcUtils.log('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, onError);
};
navigator.getUserMedia = getUserMedia;
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: requestUserMedia,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (webrtcDetectedVersion < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
} else if (navigator.webkitGetUserMedia && window.webkitRTCPeerConnection) {
webrtcUtils.log('This appears to be Chrome');
webrtcDetectedBrowser = 'chrome';
// the detected chrome version.
webrtcDetectedVersion = webrtcUtils.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/([0-9]+)\./, 2);
// the minimum chrome version still supported by adapter.
webrtcMinimumVersion = 38;
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); // jscs:ignore requireCapitalizedConstructors
var origGetStats = pc.getStats.bind(pc);
pc.getStats = function(selector, successCallback, errorCallback) { // jshint ignore: line
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats(selector, successCallback);
}
var fixChromeStats = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
if (arguments.length >= 2) {
var successCallbackWrapper = function(response) {
args[1](fixChromeStats(response));
};
return origGetStats.apply(this, [successCallbackWrapper, arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
if (args.length === 1 && selector === null) {
origGetStats.apply(self, [
function(response) {
resolve.apply(null, [fixChromeStats(response)]);
}, reject]);
} else {
origGetStats.apply(self, [resolve, reject]);
}
});
};
return pc;
};
// add promise support
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof(arguments[0]) === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
} else {
return nativeMethod.apply(this, arguments);
}
};
});
['setLocalDescription', 'setRemoteDescription',
'addIceCandidate'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0],
function() {
resolve();
if (args.length >= 2) {
args[1].apply(null, []);
}
},
function(err) {
reject(err);
if (args.length >= 3) {
args[2].apply(null, [err]);
}
}]
);
});
};
});
// getUserMedia constraints shim.
var constraintsToChrome = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
getUserMedia = function(constraints, onSuccess, onError) {
if (constraints.audio) {
constraints.audio = constraintsToChrome(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToChrome(constraints.video);
}
webrtcUtils.log('chrome: ' + JSON.stringify(constraints));
return navigator.webkitGetUserMedia(constraints, onSuccess, onError);
};
navigator.getUserMedia = getUserMedia;
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: requestUserMedia,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
}};
}
// A shim for getUserMedia method on the mediaDevices object.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
return requestUserMedia(constraints);
};
} else {
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
webrtcUtils.log('spec: ' + JSON.stringify(c)); // whitespace for alignment
c.audio = constraintsToChrome(c.audio);
c.video = constraintsToChrome(c.video);
webrtcUtils.log('chrome: ' + JSON.stringify(c));
return origGetUserMedia(c);
};
}
// Dummy devicechange event methods.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
navigator.mediaDevices.addEventListener = function() {
webrtcUtils.log('Dummy mediaDevices.addEventListener called.');
};
}
if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
navigator.mediaDevices.removeEventListener = function() {
webrtcUtils.log('Dummy mediaDevices.removeEventListener called.');
};
}
// Attach a media stream to an element.
attachMediaStream = function(element, stream) {
if (webrtcDetectedVersion >= 43) {
element.srcObject = stream;
} else if (typeof element.src !== 'undefined') {
element.src = URL.createObjectURL(stream);
} else {
webrtcUtils.log('Error attaching stream to element.');
}
};
reattachMediaStream = function(to, from) {
if (webrtcDetectedVersion >= 43) {
to.srcObject = from.srcObject;
} else {
to.src = from.src;
}
};
} else if (navigator.mediaDevices && navigator.userAgent.match(
/Edge\/(\d+).(\d+)$/)) {
webrtcUtils.log('This appears to be Edge');
webrtcDetectedBrowser = 'edge';
webrtcDetectedVersion = webrtcUtils.extractVersion(navigator.userAgent,
/Edge\/(\d+).(\d+)$/, 2);
// the minimum version still supported by adapter.
webrtcMinimumVersion = 12;
} else {
webrtcUtils.log('Browser does not appear to be WebRTC-capable');
}
// Returns the result of getUserMedia as a Promise.
function requestUserMedia(constraints) {
return new Promise(function(resolve, reject) {
getUserMedia(constraints, resolve, reject);
});
}
var webrtcTesting = {};
try {
Object.defineProperty(webrtcTesting, 'version', {
set: function(version) {
webrtcDetectedVersion = version;
}
});
} catch (e) {}
/* Orginal exports removed in favor of AdapterJS custom export.
if (typeof module !== 'undefined') {
var RTCPeerConnection;
if (typeof window !== 'undefined') {
RTCPeerConnection = window.RTCPeerConnection;
}
module.exports = {
RTCPeerConnection: RTCPeerConnection,
getUserMedia: getUserMedia,
attachMediaStream: attachMediaStream,
reattachMediaStream: reattachMediaStream,
webrtcDetectedBrowser: webrtcDetectedBrowser,
webrtcDetectedVersion: webrtcDetectedVersion,
webrtcMinimumVersion: webrtcMinimumVersion,
webrtcTesting: webrtcTesting,
webrtcUtils: webrtcUtils
//requestUserMedia: not exposed on purpose.
//trace: not exposed on purpose.
};
} else if ((typeof require === 'function') && (typeof define === 'function')) {
// Expose objects and functions when RequireJS is doing the loading.
define([], function() {
return {
RTCPeerConnection: window.RTCPeerConnection,
getUserMedia: getUserMedia,
attachMediaStream: attachMediaStream,
reattachMediaStream: reattachMediaStream,
webrtcDetectedBrowser: webrtcDetectedBrowser,
webrtcDetectedVersion: webrtcDetectedVersion,
webrtcMinimumVersion: webrtcMinimumVersion,
webrtcTesting: webrtcTesting,
webrtcUtils: webrtcUtils
//requestUserMedia: not exposed on purpose.
//trace: not exposed on purpose.
};
});
}
*/
// END OF INJECTION OF GOOGLE'S ADAPTER.JS CONTENT
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// EXTENSION FOR CHROME, FIREFOX AND EDGE
// Includes legacy functions
// -- createIceServer
// -- createIceServers
// -- MediaStreamTrack.getSources
//
// and additional shims
// -- attachMediaStream
// -- reattachMediaStream
// -- requestUserMedia
// -- a call to AdapterJS.maybeThroughWebRTCReady (notifies WebRTC is ready)
// Add support for legacy functions createIceServer and createIceServers
if ( navigator.mozGetUserMedia ) {
// Shim for MediaStreamTrack.getSources.
MediaStreamTrack.getSources = function(successCb) {
setTimeout(function() {
var infos = [
{ kind: 'audio', id: 'default', label:'', facing:'' },
{ kind: 'video', id: 'default', label:'', facing:'' }
];
successCb(infos);
}, 0);
};
createIceServer = function (url, username, password) {
console.warn('createIceServer is deprecated. It should be replaced with an application level implementation.');
var iceServer = null;
var url_parts = url.split(':');
if (url_parts[0].indexOf('stun') === 0) {
iceServer = { url : url };
} else if (url_parts[0].indexOf('turn') === 0) {
if (webrtcDetectedVersion < 27) {
var turn_url_parts = url.split('?');
if (turn_url_parts.length === 1 ||
turn_url_parts[1].indexOf('transport=udp') === 0) {
iceServer = {
url : turn_url_parts[0],
credential : password,
username : username
};
}
} else {
iceServer = {
url : url,
credential : password,
username : username
};
}
}
return iceServer;
};
createIceServers = function (urls, username, password) {
console.warn('createIceServers is deprecated. It should be replaced with an application level implementation.');
var iceServers = [];
for (i = 0; i < urls.length; i++) {
var iceServer = createIceServer(urls[i], username, password);
if (iceServer !== null) {
iceServers.push(iceServer);
}
}
return iceServers;
};
} else if ( navigator.webkitGetUserMedia ) {
createIceServer = function (url, username, password) {
console.warn('createIceServer is deprecated. It should be replaced with an application level implementation.');
var iceServer = null;
var url_parts = url.split(':');
if (url_parts[0].indexOf('stun') === 0) {
iceServer = { 'url' : url };
} else if (url_parts[0].indexOf('turn') === 0) {
iceServer = {
'url' : url,
'credential' : password,
'username' : username
};
}
return iceServer;
};
createIceServers = function (urls, username, password) {
console.warn('createIceServers is deprecated. It should be replaced with an application level implementation.');
var iceServers = [];
if (webrtcDetectedVersion >= 34) {
iceServers = {
'urls' : urls,
'credential' : password,
'username' : username
};
} else {
for (i = 0; i < urls.length; i++) {
var iceServer = createIceServer(urls[i], username, password);
if (iceServer !== null) {
iceServers.push(iceServer);
}
}
}
return iceServers;
};
}
// adapter.js by Google currently doesn't suppport
// attachMediaStream and reattachMediaStream for Egde
if (navigator.mediaDevices && navigator.userAgent.match(
/Edge\/(\d+).(\d+)$/)) {
window.getUserMedia = navigator.getUserMedia.bind(navigator);
attachMediaStream = function(element, stream) {
element.srcObject = stream;
return element;
};
reattachMediaStream = function(to, from) {
to.srcObject = from.srcObject;
return to;
};
}
// Need to override attachMediaStream and reattachMediaStream
// to support the plugin's logic
attachMediaStream_base = attachMediaStream;
attachMediaStream = function (element, stream) {
attachMediaStream_base(element, stream);
return element;
};
reattachMediaStream_base = reattachMediaStream;
reattachMediaStream = function (to, from) {
reattachMediaStream_base(to, from);
return to;
};
// Removed Google defined promises when promise is not defined
if (typeof Promise === 'undefined') {
requestUserMedia = null;
}
AdapterJS.maybeThroughWebRTCReady();
// END OF EXTENSION OF CHROME, FIREFOX AND EDGE
///////////////////////////////////////////////////////////////////
} else { // TRY TO USE PLUGIN
///////////////////////////////////////////////////////////////////
// WEBRTC PLUGIN SHIM
// Will automatically check if the plugin is available and inject it
// into the DOM if it is.
// When the plugin is not available, will prompt a banner to suggest installing it
// Use AdapterJS.options.hidePluginInstallPrompt to prevent this banner from popping
//
// Shims the follwing:
// -- getUserMedia
// -- MediaStreamTrack
// -- MediaStreamTrack.getSources
// -- RTCPeerConnection
// -- RTCSessionDescription
// -- RTCIceCandidate
// -- createIceServer
// -- createIceServers
// -- attachMediaStream
// -- reattachMediaStream
// -- webrtcDetectedBrowser
// -- webrtcDetectedVersion
// IE 9 is not offering an implementation of console.log until you open a console
if (typeof console !== 'object' || typeof console.log !== 'function') {
/* jshint -W020 */
console = {} || console;
// Implemented based on console specs from MDN
// You may override these functions
console.log = function (arg) {};
console.info = function (arg) {};
console.error = function (arg) {};
console.dir = function (arg) {};
console.exception = function (arg) {};
console.trace = function (arg) {};
console.warn = function (arg) {};
console.count = function (arg) {};
console.debug = function (arg) {};
console.count = function (arg) {};
console.time = function (arg) {};
console.timeEnd = function (arg) {};
console.group = function (arg) {};
console.groupCollapsed = function (arg) {};
console.groupEnd = function (arg) {};
/* jshint +W020 */
}
webrtcDetectedType = 'plugin';
AdapterJS.parseWebrtcDetectedBrowser();
isIE = webrtcDetectedBrowser === 'IE';
/* jshint -W035 */
AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
/* empty because it needs to prevent the function from running. */
}
};
/* jshint +W035 */
AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
// Call immediately if possible
// Once the plugin is set, the code will always take this path
callback();
} else {
// otherwise start a 100ms interval
var checkPluginReadyState = setInterval(function () {
if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
clearInterval(checkPluginReadyState);
callback();
}
}, 100);
}
};
AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
});
};
AdapterJS.WebRTCPlugin.injectPlugin = function () {
// only inject once the page is ready
if (document.readyState !== 'complete') {
return;
}
// Prevent multiple injections
if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
return;
}
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
var frag = document.createDocumentFragment();
AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
'<param name="pluginId" value="' +
AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
'<param name="windowless" value="false" /> ' +
'<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
'<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
'<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
// uncomment to be able to use virtual cams
(AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
'</object>';
while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
}
document.body.appendChild(frag);
// Need to re-fetch the plugin
AdapterJS.WebRTCPlugin.plugin =
document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
} else {
// Load Plugin
AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
AdapterJS.WebRTCPlugin.plugin.id =
AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
// IE will only start the plugin if it's ACTUALLY visible
if (isIE) {
AdapterJS.WebRTCPlugin.plugin.width = '1px';
AdapterJS.WebRTCPlugin.plugin.height = '1px';
} else { // The size of the plugin on Safari should be 0x0px
// so that the autorisation prompt is at the top
AdapterJS.WebRTCPlugin.plugin.width = '0px';
AdapterJS.WebRTCPlugin.plugin.height = '0px';
}
AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
'<param name="pluginId" value="' +
AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
'<param name="windowless" value="false" /> ' +
(AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
'<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
'<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
}
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
};
AdapterJS.WebRTCPlugin.isPluginInstalled =
function (comName, plugName, installedCb, notInstalledCb) {
if (!isIE) {
var pluginArray = navigator.plugins;
for (var i = 0; i < pluginArray.length; i++) {
if (pluginArray[i].name.indexOf(plugName) >= 0) {
installedCb();
return;
}
}
notInstalledCb();
} else {
try {
var axo = new ActiveXObject(comName + '.' + plugName);
} catch (e) {
notInstalledCb();
return;
}
installedCb();
}
};
AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
if (AdapterJS.WebRTCPlugin.pluginState ===
AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
console.error("AdapterJS - WebRTC interface has already been defined");
return;
}
AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
AdapterJS.isDefined = function (variable) {
return variable !== null && variable !== undefined;
};
createIceServer = function (url, username, password) {
var iceServer = null;
var url_parts = url.split(':');
if (url_parts[0].indexOf('stun') === 0) {
iceServer = {
'url' : url,
'hasCredentials' : false
};
} else if (url_parts[0].indexOf('turn') === 0) {
iceServer = {
'url' : url,
'hasCredentials' : true,
'credential' : password,
'username' : username
};
}
return iceServer;
};
createIceServers = function (urls, username, password) {
var iceServers = [];
for (var i = 0; i < urls.length; ++i) {
iceServers.push(createIceServer(urls[i], username, password));
}
return iceServers;
};
RTCSessionDescription = function (info) {
AdapterJS.WebRTCPlugin.WaitForPluginReady();
return AdapterJS.WebRTCPlugin.plugin.
ConstructSessionDescription(info.type, info.sdp);
};
RTCPeerConnection = function (servers, constraints) {
var iceServers = null;
if (servers) {
iceServers = servers.iceServers;
for (var i = 0; i < iceServers.length; i++) {
if (iceServers[i].urls && !iceServers[i].url) {
iceServers[i].url = iceServers[i].urls;
}
iceServers[i].hasCredentials = AdapterJS.
isDefined(iceServers[i].username) &&
AdapterJS.isDefined(iceServers[i].credential);
}
}
var mandatory = (constraints && constraints.mandatory) ?
constraints.mandatory : null;
var optional = (constraints && constraints.optional) ?
constraints.optional : null;
AdapterJS.WebRTCPlugin.WaitForPluginReady();
return AdapterJS.WebRTCPlugin.plugin.
PeerConnection(AdapterJS.WebRTCPlugin.pageId,
iceServers, mandatory, optional);
};
MediaStreamTrack = {};
MediaStreamTrack.getSources = function (callback) {
AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
});
};
window.getUserMedia = function (constraints, successCallback, failureCallback) {
constraints.audio = constraints.audio || false;
constraints.video = constraints.video || false;
AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
AdapterJS.WebRTCPlugin.plugin.
getUserMedia(constraints, successCallback, failureCallback);
});
};
window.navigator.getUserMedia = window.getUserMedia;
// Defined mediaDevices when promises are available
if ( !navigator.mediaDevices
&& typeof Promise !== 'undefined') {
navigator.mediaDevices = {getUserMedia: requestUserMedia,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
}};
}
attachMediaStream = function (element, stream) {
if (!element || !element.parentNode) {
return;
}
var streamId;
if (stream === null) {
streamId = '';
} else {
if (typeof stream.enableSoundTracks !== 'undefined') {
stream.enableSoundTracks(true);
}
streamId = stream.id;
}
var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
var nodeName = element.nodeName.toLowerCase();
if (nodeName !== 'object') { // not a plugin <object> tag yet
var tag;
switch(nodeName) {
case 'audio':
tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
break;
case 'video':
tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
break;
default:
tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
}
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
var classHTML = '';
if (element.className) {
classHTML = 'class="' + element.className + '" ';
} else if (element.attributes && element.attributes['class']) {
classHTML = 'class="' + element.attributes['class'].value + '" ';
}
temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
'<param name="pluginId" value="' + elementId + '" /> ' +
'<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
'<param name="windowless" value="true" /> ' +
'<param name="streamId" value="' + streamId + '" /> ' +
'<param name="tag" value="' + tag + '" /> ' +
'</object>';
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
var height = '';
var width = '';
if (element.clientWidth || element.clientHeight) {
width = element.clientWidth;
height = element.clientHeight;
}
else if (element.width || element.height) {
width = element.width;
height = element.height;
}
element.parentNode.insertBefore(frag, element);
frag = document.getElementById(elementId);
frag.width = width;
frag.height = height;
element.parentNode.removeChild(element);
} else { // already an <object> tag, just change the stream id
var children = element.children;
for (var i = 0; i !== children.length; ++i) {
if (children[i].name === 'streamId') {
children[i].value = streamId;
break;
}
}
element.setStreamId(streamId);
}
var newElement = document.getElementById(elementId);
AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
return newElement;
};
reattachMediaStream = function (to, from) {
var stream = null;
var children = from.children;
for (var i = 0; i !== children.length; ++i) {
if (children[i].name === 'streamId') {
AdapterJS.WebRTCPlugin.WaitForPluginReady();
stream = AdapterJS.WebRTCPlugin.plugin
.getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
break;
}
}
if (stream !== null) {
return attachMediaStream(to, stream);
} else {
console.log('Could not find the stream associated with this element');
}
};
AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
properties = Object.getOwnPropertyNames( prototype );
for(prop in properties) {
propName = properties[prop];
if (typeof(propName.slice) === 'function') {
if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
if (isIE) {
destElem.attachEvent(propName,srcElem[propName]);
} else {
destElem.addEventListener(propName.slice(2), srcElem[propName], false)
}
} else {
//TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
}
}
}
var subPrototype = Object.getPrototypeOf(prototype)
if(subPrototype != null) {
AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
}
}
RTCIceCandidate = function (candidate) {
if (!candidate.sdpMid) {
candidate.sdpMid = '';
}
AdapterJS.WebRTCPlugin.WaitForPluginReady();
return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
);
};
// inject plugin
AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
AdapterJS.WebRTCPlugin.injectPlugin();
};
// This function will be called if the plugin is needed (browser different
// from Chrome or Firefox), but the plugin is not installed.
AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
function() {
AdapterJS.addEvent(document,
'readystatechange',
AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
};
AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
if (AdapterJS.options.hidePluginInstallPrompt) {
return;
}
var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
if(downloadLink) { // if download link
var popupString;
if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
popupString = 'This website requires you to install the ' +
' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
'" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
' WebRTC Plugin</a>' +
' to work on this browser.';
} else { // no portal link, just print a generic explanation
popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
}
AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
} else { // no download link, just print a generic explanation
AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
}
};
// Try to detect the plugin and act accordingly
AdapterJS.WebRTCPlugin.isPluginInstalled(
AdapterJS.WebRTCPlugin.pluginInfo.prefix,
AdapterJS.WebRTCPlugin.pluginInfo.plugName,
AdapterJS.WebRTCPlugin.defineWebRTCInterface,
AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
// END OF WEBRTC PLUGIN SHIM
///////////////////////////////////////////////////////////////////
}
(function () {
'use strict';
var baseGetUserMedia = null;
AdapterJS.TEXT.EXTENSION = {
REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
BUTTON_FF: 'Install Now',
BUTTON_CHROME: 'Go to Chrome Web Store'
};
var clone = function(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
};
if (window.navigator.mozGetUserMedia) {
baseGetUserMedia = window.navigator.getUserMedia;
navigator.getUserMedia = function (constraints, successCb, failureCb) {
if (constraints && constraints.video && !!constraints.video.mediaSource) {
// intercepting screensharing requests
// Invalid mediaSource for firefox, only "screen" and "window" are supported
if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
failureCb(new Error('GetUserMedia: Only "screen" and "window" are supported as mediaSource constraints'));
return;
}
var updatedConstraints = clone(constraints);
//constraints.video.mediaSource = constraints.video.mediaSource;
updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
// so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
// strange but this works anyway
var checkIfReady = setInterval(function () {
if (document.readyState === 'complete') {
clearInterval(checkIfReady);
baseGetUserMedia(updatedConstraints, successCb, function (error) {
if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
AdapterJS.TEXT.EXTENSION.BUTTON_FF,
'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
//window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
} else {
failureCb(error);
}
});
}
}, 1);
} else { // regular GetUserMediaRequest
baseGetUserMedia(constraints, successCb, failureCb);
}
};
getUserMedia = navigator.getUserMedia;
} else if (window.navigator.webkitGetUserMedia) {
baseGetUserMedia = window.navigator.getUserMedia;
navigator.getUserMedia = function (constraints, successCb, failureCb) {
if (constraints && constraints.video && !!constraints.video.mediaSource) {
if (window.webrtcDetectedBrowser !== 'chrome') {
// This is Opera, which does not support screensharing
failureCb(new Error('Current browser does not support screensharing'));
return;
}
// would be fine since no methods
var updatedConstraints = clone(constraints);
var chromeCallback = function(error, sourceId) {
if(!error) {
updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
if (sourceId) {
updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
}
delete updatedConstraints.video.mediaSource;
baseGetUserMedia(updatedConstraints, successCb, failureCb);
} else { // GUM failed
if (error === 'permission-denied') {
failureCb(new Error('Permission denied for screen retrieval'));
} else {
// NOTE(J-O): I don't think we ever pass in here.
// A failure to capture the screen does not lead here.
failureCb(new Error('Failed retrieving selected screen'));
}
}
};
var onIFrameCallback = function (event) {
if (!event.data) {
return;
}
if (event.data.chromeMediaSourceId) {
if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
chromeCallback('permission-denied');
} else {
chromeCallback(null, event.data.chromeMediaSourceId);
}
}
if (event.data.chromeExtensionStatus) {
if (event.data.chromeExtensionStatus === 'not-installed') {
AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
event.data.data, true, true);
} else {
chromeCallback(event.data.chromeExtensionStatus, null);
}
}
// this event listener is no more needed
window.removeEventListener('message', onIFrameCallback);
};
window.addEventListener('message', onIFrameCallback);
postFrameMessage({
captureSourceId: true
});
} else {
baseGetUserMedia(constraints, successCb, failureCb);
}
};
getUserMedia = navigator.getUserMedia;
} else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
// nothing here because edge does not support screensharing
console.warn('Edge does not support screensharing feature in getUserMedia');
} else {
baseGetUserMedia = window.navigator.getUserMedia;
navigator.getUserMedia = function (constraints, successCb, failureCb) {
if (constraints && constraints.video && !!constraints.video.mediaSource) {
// would be fine since no methods
var updatedConstraints = clone(constraints);
// wait for plugin to be ready
AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
// check if screensharing feature is available
if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
!!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
// set the constraints
updatedConstraints.video.optional = updatedConstraints.video.optional || [];
updatedConstraints.video.optional.push({
sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
});
delete updatedConstraints.video.mediaSource;
} else {
failureCb(new Error('Your version of the WebRTC plugin does not support screensharing'));
return;
}
baseGetUserMedia(updatedConstraints, successCb, failureCb);
});
} else {
baseGetUserMedia(constraints, successCb, failureCb);
}
};
getUserMedia = window.navigator.getUserMedia;
}
// For chrome, use an iframe to load the screensharing extension
// in the correct domain.
// Modify here for custom screensharing extension in chrome
if (window.webrtcDetectedBrowser === 'chrome') {
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe.isLoaded = true;
};
iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
iframe.style.display = 'none';
(document.body || document.documentElement).appendChild(iframe);
var postFrameMessage = function (object) {
object = object || {};
if (!iframe.isLoaded) {
setTimeout(function () {
iframe.contentWindow.postMessage(object, '*');
}, 100);
return;
}
iframe.contentWindow.postMessage(object, '*');
};
} else if (window.webrtcDetectedBrowser === 'opera') {
console.warn('Opera does not support screensharing feature in getUserMedia');
}
})();
|
spec/unit/startTasks.spec.js
|
mbrio/react-pipeline
|
import React from 'react';
const ReactPipeline = require('../../src/ReactPipeline').default;
const Task = require('../../src/Task').default;
const startTasks = require('../../src/startTasks').default;
describe('startTasks', () => {
describe('start', () => {
pit('ensure child properties are updated after tasks have completed', () => {
const mockCallback = jest.genMockFunction();
class ParentTask extends Task {
state = {
prevMessage: null
};
constructor(props, context) {
super(props, context);
this.handleComplete = ::this.handleComplete;
}
handleComplete(message) {
this.setState({ prevMessage: message });
}
render() {
return(
<Task>
<ChildTask onComplete={this.handleComplete} />
<ChildTask message={this.state.prevMessage} />
</Task>
);
}
}
class ChildTask extends Task {
static propTypes = {
message: React.PropTypes.string,
onComplete: React.PropTypes.func
};
componentWillExec() {
if (this.props.message) { mockCallback(this.props.message); }
}
exec() {
if(this.props.onComplete) { this.props.onComplete('a message'); }
return Promise.resolve();
}
}
return ReactPipeline.start(<ParentTask />).then(() => {
expect(mockCallback.mock.calls[0][0]).toBe('a message');
});
});
describe('when there is a component instance', () => {
pit('should update state before executing children', () => {
const mockCallback = jest.genMockFunction();
class ChildTask extends Task {
componentWillMount() { mockCallback(this.props.serverUrl); }
componentWillExec() { mockCallback(this.props.serverUrl); }
exec() {
mockCallback();
return Promise.resolve();
}
}
class ParentTask extends Task {
state = { serverUrl: null };
exec() {
this.setState({serverUrl: 'example.com'});
return Promise.resolve();
}
render() { return (<ChildTask serverUrl={this.state.serverUrl} />); }
}
return ReactPipeline.start(<ParentTask><div></div></ParentTask>).then(() => {
expect(mockCallback.mock.calls.length).toBe(3);
expect(mockCallback.mock.calls[0][0]).toBe(null);
expect(mockCallback.mock.calls[1][0]).toBe('example.com');
});
});
pit('should call componentWillExec if it exists on the instance', () => {
const mockCallback = jest.genMockFunction();
const mock = {
_instance: { componentWillExec: mockCallback }
};
return startTasks.call(mock).then(() => {
expect(mockCallback).toBeCalled();
});
});
pit('should call exec if it exists on the instance', () => {
const mockCallback = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_instance: { exec: mockCallback }
};
return startTasks.call(mock).then(() => {
expect(mockCallback).toBeCalled();
});
});
describe('when has no children', () => {
describe('when exec is defined', () => {
pit('should call componentDidExec if it exists on the instance', () => {
const mockCallback = jest.genMockFunction();
const mockExec = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_instance: {
exec: mockExec,
componentDidExec: mockCallback
}
};
return startTasks.call(mock).then(() => {
expect(mockCallback).toBeCalled();
expect(mockExec).toBeCalled();
});
});
});
describe('when exec is not defined', () => {
pit('should call componentDidExec if it exists on the instance', () => {
const mockCallback = jest.genMockFunction();
const mock = {
_instance: {
componentDidExec: mockCallback
}
};
return startTasks.call(mock).then(() => {
expect(mockCallback).toBeCalled();
});
});
});
describe('when run child tasks serially', () => {
it('should reject', done => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.reject(new Error('error')));
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: { }
}
};
startTasks.call(mock).then(() => {
fail();
}).catch(err => {
expect(err.message).toBe('error');
expect(mockStart).toBeCalled();
done();
});
});
pit('should run child tasks', () => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: { }
}
};
return startTasks.call(mock).then(() => {
expect(mockStart).toBeCalled();
});
});
pit('should call componentDidExec if it exists on the instance', () => {
const mockCallback = jest.genMockFunction();
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: {},
componentDidExec: mockCallback
}
};
return startTasks.call(mock).then(() => {
expect(mockCallback).toBeCalled();
expect(mockStart).toBeCalled();
});
});
});
describe('when run child tasks in parallel', () => {
it('should reject', done => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.reject(new Error('error')));
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: { parallelTasks: true }
}
};
startTasks.call(mock).then(() => {
fail();
}).catch(err => {
expect(err.message).toBe('error');
expect(mockStart).toBeCalled();
done();
});
});
pit('should run child tasks', () => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: { parallelTasks: true }
}
};
return startTasks.call(mock).then(() => {
expect(mockStart).toBeCalled();
});
});
pit('should run child tasks', () => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mockCallback = jest.genMockFunction();
const mock = {
_renderedComponent: {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
},
_instance: {
props: { parallelTasks: true },
componentDidExec: mockCallback
}
};
return startTasks.call(mock).then(() => {
expect(mockStart).toBeCalled();
expect(mockCallback).toBeCalled();
});
});
});
});
});
describe('when there is no component instance', () => {
describe('when has children', () => {
describe('when run child tasks serially', () => {
pit('should run child tasks', () => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
};
return startTasks.call(mock).then(() => {
expect(mockStart).toBeCalled();
});
});
});
describe('when run child tasks in parallel', () => {
pit('should run child tasks', () => {
const mockStart = jest.genMockFunction()
.mockImplementation(() => Promise.resolve());
const mock = {
_renderedChildren: {
test: {
_instance: { exec: mockStart }
}
}
};
return startTasks.call(mock).then(() => {
expect(mockStart).toBeCalled();
});
});
});
});
});
});
});
|
src/js/components/icons/base/PauseFill.js
|
odedre/grommet-final
|
/**
* @description PauseFill SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M3,21 L9,21 L9,3 L3,3 L3,21 Z M4,19 L8,19 L8,5 L4,5 L4,19 Z M5,17 L7,17 L7,7 L5,7 L5,17 Z M15,21 L21,21 L21,3 L15,3 L15,21 Z M16,19 L20,19 L20,5 L16,5 L16,19 Z M17,17 L19,17 L19,7 L17,7 L17,17 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-pause-fill`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'pause-fill');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M3,21 L9,21 L9,3 L3,3 L3,21 Z M4,19 L8,19 L8,5 L4,5 L4,19 Z M5,17 L7,17 L7,7 L5,7 L5,17 Z M15,21 L21,21 L21,3 L15,3 L15,21 Z M16,19 L20,19 L20,5 L16,5 L16,19 Z M17,17 L19,17 L19,7 L17,7 L17,17 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'PauseFill';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
ajax/libs/golden-layout/1.5.4/goldenlayout.js
|
AMoo-Miki/cdnjs
|
(function($){var lm={"config":{},"container":{},"controls":{},"errors":{},"items":{},"utils":{}};
lm.utils.F = function () {};
lm.utils.extend = function( subClass, superClass ) {
subClass.prototype = lm.utils.createObject( superClass.prototype );
subClass.prototype.contructor = subClass;
};
lm.utils.createObject = function( prototype ) {
if( typeof Object.create === 'function' ) {
return Object.create( prototype );
} else {
lm.utils.F.prototype = prototype;
return new lm.utils.F();
}
};
lm.utils.objectKeys = function( object ) {
var keys, key;
if( typeof Object.keys === 'function' ) {
return Object.keys( object );
} else {
keys = [];
for( key in object ) {
keys.push( key );
}
return keys;
}
};
lm.utils.getQueryStringParam = function( param ) {
if( !window.location.search ) {
return null;
}
var keyValuePairs = window.location.search.substr( 1 ).split( '&' ),
params = {},
pair,
i;
for( i = 0; i < keyValuePairs.length; i++ ) {
pair = keyValuePairs[ i ].split( '=' );
params[ pair[ 0 ] ] = pair[ 1 ];
}
return params[ param ] || null;
};
lm.utils.copy = function( target, source ) {
for( var key in source ) {
target[ key ] = source[ key ];
}
return target;
};
/**
* This is based on Paul Irish's shim, but looks quite odd in comparison. Why?
* Because
* a) it shouldn't affect the global requestAnimationFrame function
* b) it shouldn't pass on the time that has passed
*
* @param {Function} fn
*
* @returns {void}
*/
lm.utils.animFrame = function( fn ){
return ( window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
})(function(){
fn();
});
};
lm.utils.indexOf = function( needle, haystack ) {
if( !( haystack instanceof Array ) ) {
throw new Error( 'Haystack is not an Array' );
}
if( haystack.indexOf ) {
return haystack.indexOf( needle );
} else {
for( var i = 0; i < haystack.length; i++ ) {
if( haystack[ i ] === needle ) {
return i;
}
}
return -1;
}
};
if ( typeof /./ != 'function' && typeof Int8Array != 'object' ) {
lm.utils.isFunction = function ( obj ) {
return typeof obj == 'function' || false;
};
} else {
lm.utils.isFunction = function ( obj ) {
return toString.call(obj) === '[object Function]';
};
}
lm.utils.fnBind = function( fn, context, boundArgs ) {
if( Function.prototype.bind !== undefined ) {
return Function.prototype.bind.apply( fn, [ context ].concat( boundArgs || [] ) );
}
var bound = function () {
// Join the already applied arguments to the now called ones (after converting to an array again).
var args = ( boundArgs || [] ).concat(Array.prototype.slice.call(arguments, 0));
// If not being called as a constructor
if (!(this instanceof bound)){
// return the result of the function called bound to target and partially applied.
return fn.apply(context, args);
}
// If being called as a constructor, apply the function bound to self.
fn.apply(this, args);
};
// Attach the prototype of the function to our newly created function.
bound.prototype = fn.prototype;
return bound;
};
lm.utils.removeFromArray = function( item, array ) {
var index = lm.utils.indexOf( item, array );
if( index === -1 ) {
throw new Error( 'Can\'t remove item from array. Item is not in the array' );
}
array.splice( index, 1 );
};
lm.utils.now = function() {
if( typeof Date.now === 'function' ) {
return Date.now();
} else {
return ( new Date() ).getTime();
}
};
lm.utils.getUniqueId = function() {
return ( Math.random() * 1000000000000000 )
.toString(36)
.replace( '.', '' );
};
/**
* A basic XSS filter. It is ultimately up to the
* implementing developer to make sure their particular
* applications and usecases are save from cross site scripting attacks
*
* @param {String} input
* @param {Boolean} keepTags
*
* @returns {String} filtered input
*/
lm.utils.filterXss = function( input, keepTags ) {
var output = input
.replace( /javascript/gi, 'javascript' )
.replace( /expression/gi, 'expression' )
.replace( /onload/gi, 'onload' )
.replace( /script/gi, 'script' )
.replace( /onerror/gi, 'onerror' );
if( keepTags === true ) {
return output;
} else {
return output
.replace( />/g, '>' )
.replace( /</g, '<' );
}
};
/**
* Removes html tags from a string
*
* @param {String} input
*
* @returns {String} input without tags
*/
lm.utils.stripTags = function( input ) {
return $.trim( input.replace( /(<([^>]+)>)/ig, '' ) );
};
/**
* A generic and very fast EventEmitter
* implementation. On top of emitting the
* actual event it emits an
*
* lm.utils.EventEmitter.ALL_EVENT
*
* event for every event triggered. This allows
* to hook into it and proxy events forwards
*
* @constructor
*/
lm.utils.EventEmitter = function()
{
this._mSubscriptions = { };
this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ] = [];
/**
* Listen for events
*
* @param {String} sEvent The name of the event to listen to
* @param {Function} fCallback The callback to execute when the event occurs
* @param {[Object]} oContext The value of the this pointer within the callback function
*
* @returns {void}
*/
this.on = function( sEvent, fCallback, oContext )
{
if ( !lm.utils.isFunction(fCallback) ) {
throw new Error( 'Tried to listen to event ' + sEvent + ' with non-function callback ' + fCallback );
}
if( !this._mSubscriptions[ sEvent ] )
{
this._mSubscriptions[ sEvent ] = [];
}
this._mSubscriptions[ sEvent ].push({ fn: fCallback, ctx: oContext });
};
/**
* Emit an event and notify listeners
*
* @param {String} sEvent The name of the event
* @param {Mixed} various additional arguments that will be passed to the listener
*
* @returns {void}
*/
this.emit = function( sEvent )
{
var i, ctx, args;
args = Array.prototype.slice.call( arguments, 1 );
if( this._mSubscriptions[ sEvent ] ) {
for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ )
{
ctx = this._mSubscriptions[ sEvent ][ i ].ctx || {};
this._mSubscriptions[ sEvent ][ i ].fn.apply( ctx, args );
}
}
args.unshift( sEvent );
for( i = 0; i < this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ].length; i++ )
{
ctx = this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].ctx || {};
this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].fn.apply( ctx, args );
}
};
/**
* Removes a listener for an event, or all listeners if no callback and context is provided.
*
* @param {String} sEvent The name of the event
* @param {Function} fCallback The previously registered callback method (optional)
* @param {Object} oContext The previously registered context (optional)
*
* @returns {void}
*/
this.unbind = function( sEvent, fCallback, oContext )
{
if( !this._mSubscriptions[ sEvent ] ) {
throw new Error( 'No subscribtions to unsubscribe for event ' + sEvent );
}
var i, bUnbound = false;
for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ )
{
if
(
( !fCallback || this._mSubscriptions[ sEvent ][ i ].fn === fCallback ) &&
( !oContext || oContext === this._mSubscriptions[ sEvent ][ i ].ctx )
)
{
this._mSubscriptions[ sEvent ].splice( i, 1 );
bUnbound = true;
}
}
if( bUnbound === false )
{
throw new Error( 'Nothing to unbind for ' + sEvent );
}
};
/**
* Alias for unbind
*/
this.off = this.unbind;
/**
* Alias for emit
*/
this.trigger = this.emit;
};
/**
* The name of the event that's triggered for every other event
*
* usage
*
* myEmitter.on( lm.utils.EventEmitter.ALL_EVENT, function( eventName, argsArray ){
* //do stuff
* });
*
* @type {String}
*/
lm.utils.EventEmitter.ALL_EVENT = '__all';
lm.utils.DragListener = function(eElement, nButtonCode)
{
lm.utils.EventEmitter.call(this);
this._eElement = $(eElement);
this._oDocument = $(document);
this._eBody = $(document.body);
this._nButtonCode = nButtonCode || 0;
/**
* The delay after which to start the drag in milliseconds
*/
this._nDelay = 200;
/**
* The distance the mouse needs to be moved to qualify as a drag
*/
this._nDistance = 10;//TODO - works better with delay only
this._nX = 0;
this._nY = 0;
this._nOriginalX = 0;
this._nOriginalY = 0;
this._bDragging = false;
this._fMove = lm.utils.fnBind( this.onMouseMove, this );
this._fUp = lm.utils.fnBind( this.onMouseUp, this );
this._fDown = lm.utils.fnBind( this.onMouseDown, this );
this._eElement.on( 'mousedown touchstart', this._fDown );
};
lm.utils.DragListener.timeout = null;
lm.utils.copy( lm.utils.DragListener.prototype, {
destroy: function() {
this._eElement.unbind( 'mousedown touchstart', this._fDown );
},
onMouseDown: function(oEvent)
{
oEvent.preventDefault();
var coordinates = this._getCoordinates( oEvent );
this._nOriginalX = coordinates.x;
this._nOriginalY = coordinates.y;
this._oDocument.on('mousemove touchmove', this._fMove);
this._oDocument.one('mouseup touchend', this._fUp);
if (oEvent.button == 0) {
this._timeout = setTimeout(lm.utils.fnBind(this._startDrag, this), this._nDelay);
}
},
onMouseMove: function(oEvent)
{
if (this._timeout != null) {
oEvent.preventDefault();
var coordinates = this._getCoordinates(oEvent);
this._nX = coordinates.x - this._nOriginalX;
this._nY = coordinates.y - this._nOriginalY;
if (this._bDragging === false) {
if (
Math.abs(this._nX) > this._nDistance ||
Math.abs(this._nY) > this._nDistance
) {
clearTimeout(this._timeout);
this._startDrag();
}
}
if (this._bDragging) {
this.emit('drag', this._nX, this._nY, oEvent);
}
}
},
onMouseUp: function(oEvent)
{
if(this._timeout != null) {
clearTimeout( this._timeout );
this._eBody.removeClass( 'lm_dragging' );
this._eElement.removeClass( 'lm_dragging' );
this._oDocument.find( 'iframe' ).css( 'pointer-events', '' );
this._oDocument.unbind( 'mousemove touchmove', this._fMove );
if( this._bDragging === true ) {
this._bDragging = false;
this.emit( 'dragStop', oEvent, this._nOriginalX + this._nX );
}
}
},
_startDrag: function()
{
this._bDragging = true;
this._eBody.addClass( 'lm_dragging' );
this._eElement.addClass( 'lm_dragging' );
this._oDocument.find( 'iframe' ).css( 'pointer-events', 'none' );
this.emit('dragStart', this._nOriginalX, this._nOriginalY);
},
_getCoordinates: function( event ) {
var coordinates = {};
if( event.type.substr( 0, 5 ) === 'touch' ) {
coordinates.x = event.originalEvent.targetTouches[ 0 ].pageX;
coordinates.y = event.originalEvent.targetTouches[ 0 ].pageY;
} else {
coordinates.x = event.pageX;
coordinates.y = event.pageY;
}
return coordinates;
}
});
/**
* The main class that will be exposed as GoldenLayout.
*
* @public
* @constructor
* @param {GoldenLayout config} config
* @param {[DOM element container]} container Can be a jQuery selector string or a Dom element. Defaults to body
*
* @returns {VOID}
*/
lm.LayoutManager = function( config, container ) {
if( !$ || typeof $.noConflict !== 'function' ) {
var errorMsg = 'jQuery is missing as dependency for GoldenLayout. ';
errorMsg += 'Please either expose $ on GoldenLayout\'s scope (e.g. window) or add "jquery" to ';
errorMsg += 'your paths when using RequireJS/AMD';
throw new Error( errorMsg );
}
lm.utils.EventEmitter.call( this );
this.isInitialised = false;
this._isFullPage = false;
this._resizeTimeoutId = null;
this._components = { 'lm-react-component': lm.utils.ReactComponentHandler };
this._itemAreas = [];
this._resizeFunction = lm.utils.fnBind( this._onResize, this );
this._unloadFunction = lm.utils.fnBind( this._onUnload, this );
this._maximisedItem = null;
this._maximisePlaceholder = $( '<div class="lm_maximise_place"></div>' );
this._creationTimeoutPassed = false;
this._subWindowsCreated = false;
this.width = null;
this.height = null;
this.root = null;
this.openPopouts = [];
this.selectedItem = null;
this.isSubWindow = false;
this.eventHub = new lm.utils.EventHub( this );
this.config = this._createConfig( config );
this.container = container;
this.dropTargetIndicator = null;
this.transitionIndicator = null;
this.tabDropPlaceholder = $( '<div class="lm_drop_tab_placeholder"></div>' );
if( this.isSubWindow === true ) {
$( 'body' ).css( 'visibility', 'hidden' );
}
this._typeToItem = {
'column': lm.utils.fnBind( lm.items.RowOrColumn, this, [ true ] ),
'row': lm.utils.fnBind( lm.items.RowOrColumn, this, [ false ] ),
'stack': lm.items.Stack,
'component': lm.items.Component
};
};
/**
* Hook that allows to access private classes
*/
lm.LayoutManager.__lm = lm;
/**
* Takes a GoldenLayout configuration object and
* replaces its keys and values recoursively with
* one letter codes
*
* @static
* @public
* @param {Object} config A GoldenLayout config object
*
* @returns {Object} minified config
*/
lm.LayoutManager.minifyConfig = function( config ) {
return ( new lm.utils.ConfigMinifier() ).minifyConfig( config );
};
/**
* Takes a configuration Object that was previously minified
* using minifyConfig and returns its original version
*
* @static
* @public
* @param {Object} minifiedConfig
*
* @returns {Object} the original configuration
*/
lm.LayoutManager.unminifyConfig = function( config ) {
return ( new lm.utils.ConfigMinifier() ).unminifyConfig( config );
};
lm.utils.copy( lm.LayoutManager.prototype, {
/**
* Register a component with the layout manager. If a configuration node
* of type component is reached it will look up componentName and create the
* associated component
*
* {
* type: "component",
* componentName: "EquityNewsFeed",
* componentState: { "feedTopic": "us-bluechips" }
* }
*
* @public
* @param {String} name
* @param {Function} constructor
*
* @returns {void}
*/
registerComponent: function( name, constructor ) {
if( typeof constructor !== 'function' ) {
throw new Error( 'Please register a constructor function' );
}
if( this._components[ name ] !== undefined ) {
throw new Error( 'Component ' + name + ' is already registered' );
}
this._components[ name ] = constructor;
},
/**
* Creates a layout configuration object based on the the current state
*
* @public
* @returns {Object} GoldenLayout configuration
*/
toConfig: function( root ) {
var config, next, i;
if( this.isInitialised === false ) {
throw new Error( 'Can\'t create config, layout not yet initialised' );
}
if( root && !( root instanceof lm.items.AbstractContentItem ) ){
throw new Error( 'Root must be a ContentItem' );
}
/*
* settings & labels
*/
config = {
settings: lm.utils.copy( {}, this.config.settings ),
dimensions: lm.utils.copy( {}, this.config.dimensions ),
labels: lm.utils.copy( {}, this.config.labels )
};
/*
* Content
*/
config.content = [];
next = function( configNode, item ) {
var key, i;
for( key in item.config ) {
if( key !== 'content' ) {
configNode[ key ] = item.config[ key ];
}
}
if( item.contentItems.length ) {
configNode.content = [];
for( i = 0; i < item.contentItems.length; i++ ) {
configNode.content[ i ] = {};
next( configNode.content[ i ], item.contentItems[ i ] );
}
}
};
if( root ) {
next( config, { contentItems: [ root ] } );
} else {
next( config, this.root );
}
/*
* Retrieve config for subwindows
*/
this._$reconcilePopoutWindows();
config.openPopouts = [];
for( i = 0; i < this.openPopouts.length; i++ ) {
config.openPopouts.push( this.openPopouts[ i ].toConfig() );
}
/*
* Add maximised item
*/
config.maximisedItemId = this._maximisedItem ? '__glMaximised' : null;
return config;
},
/**
* Returns a previously registered component
*
* @public
* @param {String} name The name used
*
* @returns {Function}
*/
getComponent: function( name ) {
if( this._components[ name ] === undefined ) {
throw new lm.errors.ConfigurationError( 'Unknown component "' + name + '"' );
}
return this._components[ name ];
},
/**
* Creates the actual layout. Must be called after all initial components
* are registered. Recourses through the configuration and sets up
* the item tree.
*
* If called before the document is ready it adds itself as a listener
* to the document.ready event
*
* @public
*
* @returns {void}
*/
init: function() {
/**
* Create the popout windows straight away. If popouts are blocked
* an error is thrown on the same 'thread' rather than a timeout and can
* be caught. This also prevents any further initilisation from taking place.
*/
if( this._subWindowsCreated === false ) {
this._createSubWindows();
this._subWindowsCreated = true;
}
/**
* If the document isn't ready yet, wait for it.
*/
if( document.readyState === 'loading' || document.body === null ) {
$(document).ready( lm.utils.fnBind( this.init, this ));
return;
}
/**
* If this is a subwindow, wait a few milliseconds for the original
* page's js calls to be executed, then replace the bodies content
* with GoldenLayout
*/
if( this.isSubWindow === true && this._creationTimeoutPassed === false ) {
setTimeout( lm.utils.fnBind( this.init, this ), 7 );
this._creationTimeoutPassed = true;
return;
}
if( this.isSubWindow === true ) {
this._adjustToWindowMode();
}
this._setContainer();
this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container );
this.transitionIndicator = new lm.controls.TransitionIndicator();
this.updateSize();
this._create( this.config );
this._bindEvents();
this.isInitialised = true;
this.emit( 'initialised' );
},
/**
* Updates the layout managers size
*
* @public
* @param {[int]} width height in pixels
* @param {[int]} height width in pixels
*
* @returns {void}
*/
updateSize: function( width, height ) {
if( arguments.length === 2 ) {
this.width = width;
this.height = height;
} else {
this.width = this.container.width();
this.height = this.container.height();
}
if( this.isInitialised === true ) {
this.root.callDownwards( 'setSize' );
if( this._maximisedItem ) {
this._maximisedItem.element.width( this.container.width() );
this._maximisedItem.element.height( this.container.height() );
this._maximisedItem.callDownwards( 'setSize' );
}
}
},
/**
* Destroys the LayoutManager instance itself as well as every ContentItem
* within it. After this is called nothing should be left of the LayoutManager.
*
* @public
* @returns {void}
*/
destroy: function() {
if( this.isInitialised === false ) {
return;
}
this._onUnload();
$( window ).off( 'resize', this._resizeFunction );
$( window ).off( 'unload beforeunload', this._unloadFunction );
this.root.callDownwards( '_$destroy', [], true );
this.root.contentItems = [];
this.tabDropPlaceholder.remove();
this.dropTargetIndicator.destroy();
this.transitionIndicator.destroy();
this.eventHub.destroy();
},
/**
* Recoursively creates new item tree structures based on a provided
* ItemConfiguration object
*
* @public
* @param {Object} config ItemConfig
* @param {[ContentItem]} parent The item the newly created item should be a child of
*
* @returns {lm.items.ContentItem}
*/
createContentItem: function( config, parent ) {
var typeErrorMsg, contentItem;
if( typeof config.type !== 'string' ) {
throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config );
}
if (config.type === 'react-component') {
config.type = 'component';
config.componentName = 'lm-react-component';
}
if( !this._typeToItem[ config.type ] ) {
typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' +
'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' );
throw new lm.errors.ConfigurationError( typeErrorMsg );
}
/**
* We add an additional stack around every component that's not within a stack anyways.
*/
if(
// If this is a component
config.type === 'component' &&
// and it's not already within a stack
!( parent instanceof lm.items.Stack ) &&
// and we have a parent
!!parent &&
// and it's not the topmost item in a new window
!( this.isSubWindow === true && parent instanceof lm.items.Root )
) {
config = {
type: 'stack',
width: config.width,
height: config.height,
content: [ config ]
};
}
contentItem = new this._typeToItem[ config.type ]( this, config, parent );
return contentItem;
},
/**
* Creates a popout window with the specified content and dimensions
*
* @param {Object|lm.itemsAbstractContentItem} configOrContentItem
* @param {[Object]} dimensions A map with width, height, left and top
* @param {[String]} parentId the id of the element this item will be appended to
* when popIn is called
* @param {[Number]} indexInParent The position of this item within its parent element
* @returns {lm.controls.BrowserPopout}
*/
createPopout: function( configOrContentItem, dimensions, parentId, indexInParent ) {
var config = configOrContentItem,
isItem = configOrContentItem instanceof lm.items.AbstractContentItem,
self = this,
windowLeft,
windowTop,
offset,
parent,
child,
browserPopout;
parentId = parentId || null;
if( isItem ) {
config = this.toConfig( configOrContentItem ).content;
parentId = lm.utils.getUniqueId();
/**
* If the item is the only component within a stack or for some
* other reason the only child of its parent the parent will be destroyed
* when the child is removed.
*
* In order to support this we move up the tree until we find something
* that will remain after the item is being popped out
*/
parent = configOrContentItem.parent;
child = configOrContentItem;
while( parent.contentItems.length === 1 && !parent.isRoot ) {
parent = parent.parent;
child = child.parent;
}
parent.addId( parentId );
if( isNaN( indexInParent ) ) {
indexInParent = lm.utils.indexOf( child, parent.contentItems );
}
} else {
if( !( config instanceof Array ) ) {
config = [ config ];
}
}
if( !dimensions && isItem ) {
windowLeft = window.screenX || window.screenLeft;
windowTop = window.screenY || window.screenTop;
offset = configOrContentItem.element.offset();
dimensions = {
left: windowLeft + offset.left,
top: windowTop + offset.top,
width: configOrContentItem.element.width(),
height: configOrContentItem.element.height()
};
}
if( !dimensions && !isItem ) {
dimensions = {
left: window.screenX || window.screenLeft + 20,
top: window.screenY || window.screenTop + 20,
width: 500,
height: 309
};
}
if( isItem ) {
configOrContentItem.remove();
}
browserPopout = new lm.controls.BrowserPopout( config, dimensions, parentId, indexInParent, this );
browserPopout.on( 'initialised', function(){
self.emit( 'windowOpened', browserPopout );
});
browserPopout.on( 'closed', function(){
self._$reconcilePopoutWindows();
});
this.openPopouts.push( browserPopout );
return browserPopout;
},
/**
* Attaches DragListener to any given DOM element
* and turns it into a way of creating new ContentItems
* by 'dragging' the DOM element into the layout
*
* @param {jQuery DOM element} element
* @param {Object} itemConfig for the new item to be created
*
* @returns {void}
*/
createDragSource: function( element, itemConfig ) {
this.config.settings.constrainDragToContainer = false;
new lm.controls.DragSource( $( element ), itemConfig, this );
},
/**
* Programmatically selects an item. This deselects
* the currently selected item, selects the specified item
* and emits a selectionChanged event
*
* @param {lm.item.AbstractContentItem} item#
* @param {[Boolean]} _$silent Wheather to notify the item of its selection
* @event selectionChanged
*
* @returns {VOID}
*/
selectItem: function( item, _$silent ) {
if( this.config.settings.selectionEnabled !== true ) {
throw new Error( 'Please set selectionEnabled to true to use this feature' );
}
if( item === this.selectedItem ) {
return;
}
if( this.selectedItem !== null ) {
this.selectedItem.deselect();
}
if( item && _$silent !== true ) {
item.select();
}
this.selectedItem = item;
this.emit( 'selectionChanged', item );
},
/*************************
* PACKAGE PRIVATE
*************************/
_$maximiseItem: function( contentItem ) {
if( this._maximisedItem !== null ) {
this._$minimiseItem( this._maximisedItem );
}
this._maximisedItem = contentItem;
this._maximisedItem.addId( '__glMaximised' );
contentItem.element.addClass( 'lm_maximised' );
contentItem.element.after( this._maximisePlaceholder );
this.root.element.prepend( contentItem.element );
contentItem.element.width( this.container.width() );
contentItem.element.height( this.container.height() );
contentItem.callDownwards( 'setSize' );
this._maximisedItem.emit( 'maximised' );
this.emit( 'stateChanged' );
},
_$minimiseItem: function( contentItem ) {
contentItem.element.removeClass( 'lm_maximised' );
contentItem.removeId( '__glMaximised' );
this._maximisePlaceholder.after( contentItem.element );
this._maximisePlaceholder.remove();
contentItem.parent.callDownwards( 'setSize' );
this._maximisedItem = null;
contentItem.emit( 'minimised' );
this.emit( 'stateChanged' );
},
/**
* This method is used to get around sandboxed iframe restrictions.
* If 'allow-top-navigation' is not specified in the iframe's 'sandbox' attribute
* (as is the case with codepens) the parent window is forbidden from calling certain
* methods on the child, such as window.close() or setting document.location.href.
*
* This prevented GoldenLayout popouts from popping in in codepens. The fix is to call
* _$closeWindow on the child window's gl instance which (after a timeout to disconnect
* the invoking method from the close call) closes itself.
*
* @packagePrivate
*
* @returns {void}
*/
_$closeWindow: function() {
window.setTimeout(function(){
window.close();
}, 1);
},
_$getArea: function( x, y ) {
var i, area, smallestSurface = Infinity, mathingArea = null;
for( i = 0; i < this._itemAreas.length; i++ ) {
area = this._itemAreas[ i ];
if(
x > area.x1 &&
x < area.x2 &&
y > area.y1 &&
y < area.y2 &&
smallestSurface > area.surface
){
smallestSurface = area.surface;
mathingArea = area;
}
}
return mathingArea;
},
_$calculateItemAreas: function() {
var i, area, allContentItems = this._getAllContentItems();
this._itemAreas = [];
/**
* If the last item is dragged out, highlight the entire container size to
* allow to re-drop it. allContentItems[ 0 ] === this.root at this point
*
* Don't include root into the possible drop areas though otherwise since it
* will used for every gap in the layout, e.g. splitters
*/
if( allContentItems.length === 1 ) {
this._itemAreas.push( this.root._$getArea() );
return;
}
for( i = 0; i < allContentItems.length; i++ ) {
if( !( allContentItems[ i ].isStack ) ) {
continue;
}
area = allContentItems[ i ]._$getArea();
if( area === null ) {
continue;
} else if( area instanceof Array ) {
this._itemAreas = this._itemAreas.concat( area );
} else {
this._itemAreas.push( area );
}
}
},
/**
* Takes a contentItem or a configuration and optionally a parent
* item and returns an initialised instance of the contentItem
*
* @packagePrivate
*
* @param {lm.items.AbtractContentItem|Object} contentItemOrConfig
* @param {lm.items.AbtractContentItem} parent Only necessary when passing in config
*
* @returns {lm.items.AbtractContentItem}
*/
_$normalizeContentItem: function( contentItemOrConfig, parent ) {
if( !contentItemOrConfig ) {
throw new Error( 'No content item defined' );
}
if( contentItemOrConfig instanceof lm.items.AbstractContentItem ) {
return contentItemOrConfig;
}
if( $.isPlainObject( contentItemOrConfig ) && contentItemOrConfig.type ) {
var newContentItem = this.createContentItem( contentItemOrConfig, parent );
newContentItem.callDownwards( '_$init' );
return newContentItem;
} else {
throw new Error( 'Invalid contentItem' );
}
},
/**
* Iterates through the array of open popout windows and removes the ones
* that are effectively closed. This is necessary due to the lack of reliably
* listening for window.close / unload events in a cross browser compatible fashion.
*
* @packagePrivate
*
* @returns {void}
*/
_$reconcilePopoutWindows: function() {
var openPopouts = [], i;
for( i = 0; i < this.openPopouts.length; i++ ) {
if( this.openPopouts[ i ].getWindow().closed === false ) {
openPopouts.push( this.openPopouts[ i ] );
} else {
this.emit( 'windowClosed', this.openPopouts[ i ] );
}
}
if( this.openPopouts.length !== openPopouts.length ) {
this.emit( 'stateChanged' );
this.openPopouts = openPopouts;
}
},
/***************************
* PRIVATE
***************************/
/**
* Returns a flattened array of all content items,
* regardles of level or type
*
* @private
*
* @returns {void}
*/
_getAllContentItems: function() {
var allContentItems = [];
var addChildren = function( contentItem ) {
allContentItems.push( contentItem );
if( contentItem.contentItems instanceof Array ) {
for( var i = 0; i < contentItem.contentItems.length; i++ ) {
addChildren( contentItem.contentItems[ i ] );
}
}
};
addChildren( this.root );
return allContentItems;
},
/**
* Binds to DOM/BOM events on init
*
* @private
*
* @returns {void}
*/
_bindEvents: function() {
if( this._isFullPage ) {
$(window).resize( this._resizeFunction );
}
$(window).on( 'unload beforeunload', this._unloadFunction );
},
/**
* Debounces resize events
*
* @private
*
* @returns {void}
*/
_onResize: function() {
clearTimeout( this._resizeTimeoutId );
this._resizeTimeoutId = setTimeout(lm.utils.fnBind( this.updateSize, this ), 100 );
},
/**
* Extends the default config with the user specific settings and applies
* derivations. Please note that there's a seperate method (AbstractContentItem._extendItemNode)
* that deals with the extension of item configs
*
* @param {Object} config
* @static
* @returns {Object} config
*/
_createConfig: function( config ) {
var windowConfigKey = lm.utils.getQueryStringParam( 'gl-window' );
if( windowConfigKey ) {
this.isSubWindow = true;
config = localStorage.getItem( windowConfigKey );
config = JSON.parse( config );
config = ( new lm.utils.ConfigMinifier() ).unminifyConfig( config );
localStorage.removeItem( windowConfigKey );
}
config = $.extend( true, {}, lm.config.defaultConfig, config );
var nextNode = function( node ) {
for( var key in node ) {
if( key !== 'props' && typeof node[ key ] === 'object' ) {
nextNode( node[ key ] );
}
else if( key === 'type' && node[ key ] === 'react-component' ) {
node.type = 'component';
node.componentName = 'lm-react-component';
}
}
}
nextNode( config );
if( config.settings.hasHeaders === false ) {
config.dimensions.headerHeight = 0;
}
return config;
},
/**
* This is executed when GoldenLayout detects that it is run
* within a previously opened popout window.
*
* @private
*
* @returns {void}
*/
_adjustToWindowMode: function() {
var popInButton = $( '<div class="lm_popin" title="' + this.config.labels.popin + '">' +
'<div class="lm_icon"></div>' +
'<div class="lm_bg"></div>' +
'</div>');
popInButton.click(lm.utils.fnBind(function(){
this.emit( 'popIn' );
}, this));
document.title = lm.utils.stripTags( this.config.content[ 0 ].title );
$( 'head' ).append( $( 'body link, body style, template, .gl_keep' ) );
this.container = $( 'body' )
.html( '' )
.css( 'visibility', 'visible' )
.append( popInButton );
/*
* This seems a bit pointless, but actually causes a reflow/re-evaluation getting around
* slickgrid's "Cannot find stylesheet." bug in chrome
*/
var x = document.body.offsetHeight; // jshint ignore:line
/*
* Expose this instance on the window object
* to allow the opening window to interact with
* it
*/
window.__glInstance = this;
},
/**
* Creates Subwindows (if there are any). Throws an error
* if popouts are blocked.
*
* @returns {void}
*/
_createSubWindows: function() {
var i, popout;
for( i = 0; i < this.config.openPopouts.length; i++ ) {
popout = this.config.openPopouts[ i ];
this.createPopout(
popout.content,
popout.dimensions,
popout.parentId,
popout.indexInParent
);
}
},
/**
* Determines what element the layout will be created in
*
* @private
*
* @returns {void}
*/
_setContainer: function() {
var container = $( this.container || 'body' );
if( container.length === 0 ) {
throw new Error( 'GoldenLayout container not found' );
}
if( container.length > 1 ) {
throw new Error( 'GoldenLayout more than one container element specified' );
}
if( container[ 0 ] === document.body ) {
this._isFullPage = true;
$( 'html, body' ).css({
height: '100%',
margin:0,
padding: 0,
overflow: 'hidden'
});
}
this.container = container;
},
/**
* Kicks of the initial, recoursive creation chain
*
* @param {Object} config GoldenLayout Config
*
* @returns {void}
*/
_create: function( config ) {
var errorMsg;
if( !( config.content instanceof Array ) ) {
if( config.content === undefined ) {
errorMsg = 'Missing setting \'content\' on top level of configuration';
} else {
errorMsg = 'Configuration parameter \'content\' must be an array';
}
throw new lm.errors.ConfigurationError( errorMsg, config );
}
if( config.content.length > 1 ) {
errorMsg = 'Top level content can\'t contain more then one element.';
throw new lm.errors.ConfigurationError( errorMsg, config );
}
this.root = new lm.items.Root( this, { content: config.content }, this.container );
this.root.callDownwards( '_$init' );
if( config.maximisedItemId === '__glMaximised' ) {
this.root.getItemsById( config.maximisedItemId )[ 0 ].toggleMaximise();
}
},
/**
* Called when the window is closed or the user navigates away
* from the page
*
* @returns {void}
*/
_onUnload: function() {
if( this.config.settings.closePopoutsOnUnload === true ) {
for( var i = 0; i < this.openPopouts.length; i++ ) {
this.openPopouts[ i ].close();
}
}
}
});
/**
* Expose the Layoutmanager as the single entrypoint using UMD
*/
(function () {
/* global define */
if ( typeof define === 'function' && define.amd) {
define([ 'jquery' ], function( jquery ){ $ = jquery; return lm.LayoutManager; }); // jshint ignore:line
} else if (typeof exports === 'object') {
module.exports = lm.LayoutManager;
} else {
window.GoldenLayout = lm.LayoutManager;
}
})();
lm.config.itemDefaultConfig = {
isClosable: true,
reorderEnabled: true,
title: ''
};
lm.config.defaultConfig = {
openPopouts:[],
settings:{
hasHeaders: true,
constrainDragToContainer: true,
reorderEnabled: true,
selectionEnabled: false,
popoutWholeStack: false,
blockedPopoutsThrowError: true,
closePopoutsOnUnload: true,
showPopoutIcon: true,
showMaximiseIcon: true,
showCloseIcon: true
},
dimensions: {
borderWidth: 5,
minItemHeight: 10,
minItemWidth: 10,
headerHeight: 20,
dragProxyWidth: 300,
dragProxyHeight: 200
},
labels: {
close: 'close',
maximise: 'maximise',
minimise: 'minimise',
popout: 'open in new window',
popin: 'pop in'
}
};
lm.container.ItemContainer = function( config, parent, layoutManager ) {
lm.utils.EventEmitter.call( this );
this.width = null;
this.height = null;
this.title = config.componentName;
this.parent = parent;
this.layoutManager = layoutManager;
this.isHidden = false;
this._config = config;
this._element = $([
'<div class="lm_item_container">',
'<div class="lm_content"></div>',
'</div>'
].join( '' ));
this._contentElement = this._element.find( '.lm_content' );
};
lm.utils.copy( lm.container.ItemContainer.prototype, {
/**
* Get the inner DOM element the container's content
* is intended to live in
*
* @returns {DOM element}
*/
getElement: function() {
return this._contentElement;
},
/**
* Hide the container. Notifies the containers content first
* and then hides the DOM node. If the container is already hidden
* this should have no effect
*
* @returns {void}
*/
hide: function() {
this.emit( 'hide' );
this.isHidden = true;
this._element.hide();
},
/**
* Shows a previously hidden container. Notifies the
* containers content first and then shows the DOM element.
* If the container is already visible this has no effect.
*
* @returns {void}
*/
show: function() {
this.emit( 'show' );
this.isHidden = false;
this._element.show();
// call shown only if the container has a valid size
if(this.height != 0 || this.width != 0) {
this.emit( 'shown' );
}
},
/**
* Set the size from within the container. Traverses up
* the item tree until it finds a row or column element
* and resizes its items accordingly.
*
* If this container isn't a descendant of a row or column
* it returns false
* @todo Rework!!!
* @param {Number} width The new width in pixel
* @param {Number} height The new height in pixel
*
* @returns {Boolean} resizeSuccesful
*/
setSize: function( width, height ) {
var rowOrColumn = this.parent,
rowOrColumnChild = this,
totalPixel,
percentage,
direction,
newSize,
delta,
i;
while( !rowOrColumn.isColumn && !rowOrColumn.isRow ) {
rowOrColumnChild = rowOrColumn;
rowOrColumn = rowOrColumn.parent;
/**
* No row or column has been found
*/
if( rowOrColumn.isRoot ) {
return false;
}
}
direction = rowOrColumn.isColumn ? "height" : "width";
newSize = direction === "height" ? height : width;
totalPixel = this[direction] * ( 1 / ( rowOrColumnChild.config[direction] / 100 ) );
percentage = ( newSize / totalPixel ) * 100;
delta = ( rowOrColumnChild.config[direction] - percentage ) / rowOrColumn.contentItems.length;
for( i = 0; i < rowOrColumn.contentItems.length; i++ ) {
if( rowOrColumn.contentItems[ i ] === rowOrColumnChild ) {
rowOrColumn.contentItems[ i ].config[direction] = percentage;
} else {
rowOrColumn.contentItems[ i ].config[direction] += delta;
}
}
rowOrColumn.callDownwards( 'setSize' );
return true;
},
/**
* Closes the container if it is closable. Can be called by
* both the component within at as well as the contentItem containing
* it. Emits a close event before the container itself is closed.
*
* @returns {void}
*/
close: function() {
if( this._config.isClosable ) {
this.emit( 'close' );
this.parent.close();
}
},
/**
* Returns the current state object
*
* @returns {Object} state
*/
getState: function() {
return this._config.componentState;
},
/**
* Merges the provided state into the current one
*
* @param {Object} state
*
* @returns {void}
*/
extendState: function( state ) {
this.setState( $.extend( true, this.getState(), state ) );
},
/**
* Notifies the layout manager of a stateupdate
*
* @param {serialisable} state
*/
setState: function( state ) {
this._config.componentState = state;
this.parent.emitBubblingEvent( 'stateChanged' );
},
/**
* Set's the components title
*
* @param {String} title
*/
setTitle: function( title ) {
this.parent.setTitle( title );
},
/**
* Set's the containers size. Called by the container's component.
* To set the size programmatically from within the container please
* use the public setSize method
*
* @param {[Int]} width in px
* @param {[Int]} height in px
*
* @returns {void}
*/
_$setSize: function( width, height ) {
if( width !== this.width || height !== this.height ) {
this.width = width;
this.height = height;
this._contentElement.width( this.width ).height( this.height );
this.emit( 'resize' );
}
}
});
/**
* Pops a content item out into a new browser window.
* This is achieved by
*
* - Creating a new configuration with the content item as root element
* - Serializing and minifying the configuration
* - Opening the current window's URL with the configuration as a GET parameter
* - GoldenLayout when opened in the new window will look for the GET parameter
* and use it instead of the provided configuration
*
* @param {Object} config GoldenLayout item config
* @param {Object} dimensions A map with width, height, top and left
* @param {String} parentId The id of the element the item will be appended to on popIn
* @param {Number} indexInParent The position of this element within its parent
* @param {lm.LayoutManager} layoutManager
*/
lm.controls.BrowserPopout = function( config, dimensions, parentId, indexInParent, layoutManager ) {
lm.utils.EventEmitter.call( this );
this.isInitialised = false;
this._config = config;
this._dimensions = dimensions;
this._parentId = parentId;
this._indexInParent = indexInParent;
this._layoutManager = layoutManager;
this._popoutWindow = null;
this._id = null;
this._createWindow();
};
lm.utils.copy( lm.controls.BrowserPopout.prototype, {
toConfig: function() {
return {
dimensions:{
width: this.getGlInstance().width,
height: this.getGlInstance().height,
left: this._popoutWindow.screenX || this._popoutWindow.screenLeft,
top: this._popoutWindow.screenY || this._popoutWindow.screenTop
},
content: this.getGlInstance().toConfig().content,
parentId: this._parentId,
indexInParent: this._indexInParent
};
},
getGlInstance: function() {
return this._popoutWindow.__glInstance;
},
getWindow: function() {
return this._popoutWindow;
},
close: function() {
if( this.getGlInstance() ) {
this.getGlInstance()._$closeWindow();
} else {
try{
this.getWindow().close();
} catch( e ){}
}
},
/**
* Returns the popped out item to its original position. If the original
* parent isn't available anymore it falls back to the layout's topmost element
*/
popIn: function() {
var childConfig,
parentItem,
index = this._indexInParent;
if( this._parentId ) {
/*
* The $.extend call seems a bit pointless, but it's crucial to
* copy the config returned by this.getGlInstance().toConfig()
* onto a new object. Internet Explorer keeps the references
* to objects on the child window, resulting in the following error
* once the child window is closed:
*
* The callee (server [not server application]) is not available and disappeared
*/
childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ];
parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ];
/*
* Fallback if parentItem is not available. Either add it to the topmost
* item or make it the topmost item if the layout is empty
*/
if( !parentItem ) {
if( this._layoutManager.root.contentItems.length > 0 ) {
parentItem = this._layoutManager.root.contentItems[ 0 ];
} else {
parentItem = this._layoutManager.root;
}
index = 0;
}
}
parentItem.addChild( childConfig, this._indexInParent );
this.close();
},
/**
* Creates the URL and window parameter
* and opens a new window
*
* @private
*
* @returns {void}
*/
_createWindow: function() {
var checkReadyInterval,
url = this._createUrl(),
/**
* Bogus title to prevent re-usage of existing window with the
* same title. The actual title will be set by the new window's
* GoldenLayout instance if it detects that it is in subWindowMode
*/
title = Math.floor( Math.random() * 1000000 ).toString( 36 ),
/**
* The options as used in the window.open string
*/
options = this._serializeWindowOptions({
width: this._dimensions.width,
height: this._dimensions.height,
innerWidth: this._dimensions.width,
innerHeight: this._dimensions.height,
menubar: 'no',
toolbar: 'no',
location: 'no',
personalbar: 'no',
resizable: 'yes',
scrollbars: 'no',
status: 'no'
});
this._popoutWindow = window.open( url, title, options );
if( !this._popoutWindow ) {
if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) {
var error = new Error( 'Popout blocked' );
error.type = 'popoutBlocked';
throw error;
} else {
return;
}
}
$( this._popoutWindow )
.on( 'load', lm.utils.fnBind( this._positionWindow, this ) )
.on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) );
/**
* Polling the childwindow to find out if GoldenLayout has been initialised
* doesn't seem optimal, but the alternatives - adding a callback to the parent
* window or raising an event on the window object - both would introduce knowledge
* about the parent to the child window which we'd rather avoid
*/
checkReadyInterval = setInterval(lm.utils.fnBind(function(){
if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) {
this._onInitialised();
clearInterval( checkReadyInterval );
}
}, this ), 10 );
},
/**
* Serialises a map of key:values to a window options string
*
* @param {Object} windowOptions
*
* @returns {String} serialised window options
*/
_serializeWindowOptions: function( windowOptions ) {
var windowOptionsString = [], key;
for( key in windowOptions ) {
windowOptionsString.push( key + '=' + windowOptions[ key ] );
}
return windowOptionsString.join( ',' );
},
/**
* Creates the URL for the new window, including the
* config GET parameter
*
* @returns {String} URL
*/
_createUrl: function() {
var config = { content: this._config },
storageKey = 'gl-window-config-' + lm.utils.getUniqueId(),
urlParts;
config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config );
try{
localStorage.setItem( storageKey, JSON.stringify( config ) );
} catch( e ) {
throw new Error( 'Error while writing to localStorage ' + e.toString() );
}
urlParts = document.location.href.split( '?' );
// URL doesn't contain GET-parameters
if( urlParts.length === 1 ) {
return urlParts[ 0 ] + '?gl-window=' + storageKey;
// URL contains GET-parameters
} else {
return document.location.href + '&gl-window=' + storageKey;
}
},
/**
* Move the newly created window roughly to
* where the component used to be.
*
* @private
*
* @returns {void}
*/
_positionWindow: function() {
this._popoutWindow.moveTo( this._dimensions.left, this._dimensions.top );
this._popoutWindow.focus();
},
/**
* Callback when the new window is opened and the GoldenLayout instance
* within it is initialised
*
* @returns {void}
*/
_onInitialised: function() {
this.isInitialised = true;
this.getGlInstance().on( 'popIn', this.popIn, this );
this.emit( 'initialised' );
},
/**
* Invoked 50ms after the window unload event
*
* @private
*
* @returns {void}
*/
_onClose: function() {
setTimeout( lm.utils.fnBind( this.emit, this, [ 'closed' ] ), 50 );
}
});
/**
* This class creates a temporary container
* for the component whilst it is being dragged
* and handles drag events
*
* @constructor
* @private
*
* @param {Number} x The initial x position
* @param {Number} y The initial y position
* @param {lm.utils.DragListener} dragListener
* @param {lm.LayoutManager} layoutManager
* @param {lm.item.AbstractContentItem} contentItem
* @param {lm.item.AbstractContentItem} originalParent
*/
lm.controls.DragProxy = function( x, y, dragListener, layoutManager, contentItem, originalParent ) {
lm.utils.EventEmitter.call( this );
this._dragListener = dragListener;
this._layoutManager = layoutManager;
this._contentItem = contentItem;
this._originalParent = originalParent;
this._area = null;
this._lastValidArea = null;
this._dragListener.on( 'drag', this._onDrag, this );
this._dragListener.on( 'dragStop', this._onDrop, this );
this.element = $( lm.controls.DragProxy._template );
this.element.css({ left: x, top: y });
this.element.find( '.lm_tab' ).attr( 'title', lm.utils.stripTags( this._contentItem.config.title ) );
this.element.find( '.lm_title' ).html( this._contentItem.config.title );
this.childElementContainer = this.element.find( '.lm_content' );
this.childElementContainer.append( contentItem.element );
this._updateTree();
this._layoutManager._$calculateItemAreas();
this._setDimensions();
$( document.body ).append( this.element );
var offset = this._layoutManager.container.offset();
this._minX = offset.left;
this._minY = offset.top;
this._maxX = this._layoutManager.container.width() + this._minX;
this._maxY = this._layoutManager.container.height() + this._minY;
this._width = this.element.width();
this._height = this.element.height();
};
lm.controls.DragProxy._template = '<div class="lm_dragProxy">' +
'<div class="lm_header">' +
'<ul class="lm_tabs">' +
'<li class="lm_tab lm_active"><i class="lm_left"></i>' +
'<span class="lm_title"></span>' +
'<i class="lm_right"></i></li>' +
'</ul>' +
'</div>' +
'<div class="lm_content"></div>' +
'</div>';
lm.utils.copy( lm.controls.DragProxy.prototype, {
/**
* Callback on every mouseMove event during a drag. Determines if the drag is
* still within the valid drag area and calls the layoutManager to highlight the
* current drop area
*
* @param {Number} offsetX The difference from the original x position in px
* @param {Number} offsetY The difference from the original y position in px
* @param {jQuery DOM event} event
*
* @private
*
* @returns {void}
*/
_onDrag: function( offsetX, offsetY, event ) {
var x = event.pageX,
y = event.pageY,
isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY;
if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) {
return;
}
this.element.css({ left: x, top: y });
this._area = this._layoutManager._$getArea( x, y );
if( this._area !== null ) {
this._lastValidArea = this._area;
this._area.contentItem._$highlightDropZone( x, y, this._area );
}
},
/**
* Callback when the drag has finished. Determines the drop area
* and adds the child to it
*
* @private
*
* @returns {void}
*/
_onDrop: function() {
this._layoutManager.dropTargetIndicator.hide();
/*
* Valid drop area found
*/
if( this._area !== null ) {
this._area.contentItem._$onDrop( this._contentItem );
/**
* No valid drop area available at present, but one has been found before.
* Use it
*/
} else if( this._lastValidArea !== null ) {
this._lastValidArea.contentItem._$onDrop( this._contentItem );
/**
* No valid drop area found during the duration of the drag. Return
* content item to its original position if a original parent is provided.
* (Which is not the case if the drag had been initiated by createDragSource)
*/
} else if ( this._originalParent ){
this._originalParent.addChild( this._contentItem );
/**
* The drag didn't ultimately end up with adding the content item to
* any container. In order to ensure clean up happens, destroy the
* content item.
*/
} else {
this._contentItem._$destroy();
}
this.element.remove();
this._layoutManager.emit( 'itemDropped', this._contentItem );
},
/**
* Removes the item from it's original position within the tree
*
* @private
*
* @returns {void}
*/
_updateTree: function() {
/**
* parent is null if the drag had been initiated by a external drag source
*/
if( this._contentItem.parent ) {
this._contentItem.parent.removeChild( this._contentItem, true );
}
this._contentItem._$setParent( this );
},
/**
* Updates the Drag Proxie's dimensions
*
* @private
*
* @returns {void}
*/
_setDimensions: function() {
var dimensions = this._layoutManager.config.dimensions,
width = dimensions.dragProxyWidth,
height = dimensions.dragProxyHeight - dimensions.headerHeight;
this.childElementContainer.width( width );
this.childElementContainer.height( height );
this._contentItem.element.width( width );
this._contentItem.element.height( height );
this._contentItem.callDownwards( '_$show' );
this._contentItem.callDownwards( 'setSize' );
}
});
/**
* Allows for any DOM item to create a component on drag
* start tobe dragged into the Layout
*
* @param {jQuery element} element
* @param {Object} itemConfig the configuration for the contentItem that will be created
* @param {LayoutManager} layoutManager
*
* @constructor
*/
lm.controls.DragSource = function( element, itemConfig, layoutManager ) {
this._element = element;
this._itemConfig = itemConfig;
this._layoutManager = layoutManager;
this._dragListener = null;
this._createDragListener();
};
lm.utils.copy( lm.controls.DragSource.prototype, {
/**
* Called initially and after every drag
*
* @returns {void}
*/
_createDragListener: function() {
if( this._dragListener !== null ) {
this._dragListener.destroy();
}
this._dragListener = new lm.utils.DragListener( this._element );
this._dragListener.on( 'dragStart', this._onDragStart, this );
this._dragListener.on( 'dragStop', this._createDragListener, this );
},
/**
* Callback for the DragListener's dragStart event
*
* @param {int} x the x position of the mouse on dragStart
* @param {int} y the x position of the mouse on dragStart
*
* @returns {void}
*/
_onDragStart: function( x, y ) {
var contentItem = this._layoutManager._$normalizeContentItem( this._itemConfig ),
dragProxy = new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, contentItem, null );
this._layoutManager.transitionIndicator.transitionElements( this._element, dragProxy.element );
}
});
lm.controls.DropTargetIndicator = function() {
this.element = $( lm.controls.DropTargetIndicator._template );
$(document.body).append( this.element );
};
lm.controls.DropTargetIndicator._template = '<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>';
lm.utils.copy( lm.controls.DropTargetIndicator.prototype, {
destroy: function() {
this.element.remove();
},
highlight: function( x1, y1, x2, y2 ) {
this.highlightArea({ x1:x1, y1:y1, x2:x2, y2:y2 });
},
highlightArea: function( area ) {
this.element.css({
left: area.x1,
top: area.y1,
width: area.x2 - area.x1,
height: area.y2 - area.y1
}).show();
},
hide: function() {
this.element.hide();
}
});
/**
* This class represents a header above a Stack ContentItem.
*
* @param {lm.LayoutManager} layoutManager
* @param {lm.item.AbstractContentItem} parent
*/
lm.controls.Header = function( layoutManager, parent ) {
lm.utils.EventEmitter.call( this );
this.layoutManager = layoutManager;
this.element = $( lm.controls.Header._template );
if( this.layoutManager.config.settings.selectionEnabled === true ) {
this.element.addClass( 'lm_selectable' );
this.element.click( lm.utils.fnBind( this._onHeaderClick, this ) );
}
this.element.height( layoutManager.config.dimensions.headerHeight );
this.tabsContainer = this.element.find( '.lm_tabs' );
this.controlsContainer = this.element.find( '.lm_controls' );
this.parent = parent;
this.parent.on( 'resize', this._updateTabSizes, this );
this.tabs = [];
this.activeContentItem = null;
this.closeButton = null;
this._createControls();
};
lm.controls.Header._template = [
'<div class="lm_header">',
'<ul class="lm_tabs"></ul>',
'<ul class="lm_controls"></ul>',
'</div>'
].join( '' );
lm.utils.copy( lm.controls.Header.prototype, {
/**
* Creates a new tab and associates it with a contentItem
*
* @param {lm.item.AbstractContentItem} contentItem
* @param {Integer} index The position of the tab
*
* @returns {void}
*/
createTab: function( contentItem, index ) {
var tab, i;
//If there's already a tab relating to the
//content item, don't do anything
for( i = 0; i < this.tabs.length; i++ ) {
if( this.tabs[ i ].contentItem === contentItem ) {
return;
}
}
tab = new lm.controls.Tab( this, contentItem );
if( this.tabs.length === 0 ) {
this.tabs.push( tab );
this.tabsContainer.append( tab.element );
return;
}
if( index === undefined ) {
index = this.tabs.length;
}
if( index > 0 ) {
this.tabs[ index - 1 ].element.after( tab.element );
} else {
this.tabs[ 0 ].element.before( tab.element );
}
this.tabs.splice( index, 0, tab );
this._updateTabSizes();
},
/**
* Finds a tab based on the contentItem its associated with and removes it.
*
* @param {lm.item.AbstractContentItem} contentItem
*
* @returns {void}
*/
removeTab: function( contentItem ) {
for( var i = 0; i < this.tabs.length; i++ ) {
if( this.tabs[ i ].contentItem === contentItem ) {
this.tabs[ i ]._$destroy();
this.tabs.splice( i, 1 );
return;
}
}
throw new Error( 'contentItem is not controlled by this header' );
},
/**
* The programmatical equivalent of clicking a Tab.
*
* @param {lm.item.AbstractContentItem} contentItem
*/
setActiveContentItem: function( contentItem ) {
var i, isActive;
for( i = 0; i < this.tabs.length; i++ ) {
isActive = this.tabs[ i ].contentItem === contentItem;
this.tabs[ i ].setActive( isActive );
if( isActive === true ) {
this.activeContentItem = contentItem;
this.parent.config.activeItemIndex = i;
}
}
this._updateTabSizes();
this.parent.emitBubblingEvent( 'stateChanged' );
},
/**
* Programmatically set closability.
*
* @package private
* @param {Boolean} isClosable Whether to enable/disable closability.
*
* @returns {Boolean} Whether the action was successful
*/
_$setClosable: function( isClosable ) {
if ( this.closeButton && this._isClosable() ) {
this.closeButton.element[ isClosable ? "show" : "hide" ]();
return true;
}
return false;
},
/**
* Destroys the entire header
*
* @package private
*
* @returns {void}
*/
_$destroy: function() {
this.emit( 'destroy' );
for( var i = 0; i < this.tabs.length; i++ ) {
this.tabs[ i ]._$destroy();
}
this.element.remove();
},
/**
* Creates the popout, maximise and close buttons in the header's top right corner
*
* @returns {void}
*/
_createControls: function() {
var closeStack,
popout,
label,
maximiseLabel,
minimiseLabel,
maximise,
maximiseButton;
/**
* Popout control to launch component in new window.
*/
if( this.layoutManager.config.settings.showPopoutIcon ) {
popout = lm.utils.fnBind( this._onPopoutClick, this );
label = this.layoutManager.config.labels.popout;
new lm.controls.HeaderButton( this, label, 'lm_popout', popout );
}
/**
* Maximise control - set the component to the full size of the layout
*/
if( this.layoutManager.config.settings.showMaximiseIcon ) {
maximise = lm.utils.fnBind( this.parent.toggleMaximise, this.parent );
maximiseLabel = this.layoutManager.config.labels.maximise;
minimiseLabel = this.layoutManager.config.labels.minimise;
maximiseButton = new lm.controls.HeaderButton( this, maximiseLabel, 'lm_maximise', maximise );
this.parent.on( 'maximised', function(){
maximiseButton.element.attr( 'title', minimiseLabel );
});
this.parent.on( 'minimised', function(){
maximiseButton.element.attr( 'title', maximiseLabel );
});
}
/**
* Close button
*/
if( this._isClosable() ) {
closeStack = lm.utils.fnBind( this.parent.remove, this.parent );
label = this.layoutManager.config.labels.close;
this.closeButton = new lm.controls.HeaderButton( this, label, 'lm_close', closeStack );
}
},
/**
* Checks whether the header is closable based on the parent config and
* the global config.
*
* @returns {Boolean} Whether the header is closable.
*/
_isClosable: function() {
return this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon;
},
_onPopoutClick: function() {
if( this.layoutManager.config.settings.popoutWholeStack === true ) {
this.parent.popout();
} else {
this.activeContentItem.popout();
}
},
/**
* Invoked when the header's background is clicked (not it's tabs or controls)
*
* @param {jQuery DOM event} event
*
* @returns {void}
*/
_onHeaderClick: function( event ) {
if( event.target === this.element[ 0 ] ) {
this.parent.select();
}
},
/**
* Shrinks the tabs if the available space is not sufficient
*
* @returns {void}
*/
_updateTabSizes: function() {
if( this.tabs.length === 0 ) {
return;
}
var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth(),
totalTabWidth = 0,
tabElement,
i,
marginLeft,
gap;
for( i = 0; i < this.tabs.length; i++ ) {
tabElement = this.tabs[ i ].element;
/*
* In order to show every tab's close icon, decrement the z-index from left to right
*/
tabElement.css( 'z-index', this.tabs.length - i );
totalTabWidth += tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 );
}
gap = ( totalTabWidth - availableWidth ) / ( this.tabs.length - 1 );
for( i = 0; i < this.tabs.length; i++ ) {
/*
* The active tab keeps it's original width
*/
if( !this.tabs[ i ].isActive && gap > 0 ) {
marginLeft = '-' + Math.floor( gap )+ 'px';
} else {
marginLeft = '';
}
this.tabs[ i ].element.css( 'margin-left', marginLeft );
}
if( availableWidth < totalTabWidth ) {
this.element.css( 'overflow', 'hidden' );
} else {
this.element.css( 'overflow', 'visible' );
}
}
});
lm.controls.HeaderButton = function( header, label, cssClass, action ) {
this._header = header;
this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' );
this._header.on( 'destroy', this._$destroy, this );
this._action = action;
this.element.click( this._action );
this._header.controlsContainer.append( this.element );
};
lm.utils.copy( lm.controls.HeaderButton.prototype, {
_$destroy: function() {
this.element.off();
this.element.remove();
}
});
lm.controls.Splitter = function( isVertical, size ) {
this._isVertical = isVertical;
this._size = size;
this.element = this._createElement();
this._dragListener = new lm.utils.DragListener( this.element );
};
lm.utils.copy( lm.controls.Splitter.prototype, {
on: function( event, callback, context ) {
this._dragListener.on( event, callback, context );
},
_$destroy: function() {
this.element.remove();
},
_createElement: function() {
var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' );
element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) );
element[ this._isVertical ? 'height' : 'width' ]( this._size );
return element;
}
});
/**
* Represents an individual tab within a Stack's header
*
* @param {lm.controls.Header} header
* @param {lm.items.AbstractContentItem} contentItem
*
* @constructor
*/
lm.controls.Tab = function( header, contentItem ) {
this.header = header;
this.contentItem = contentItem;
this.element = $( lm.controls.Tab._template );
this.titleElement = this.element.find( '.lm_title' );
this.closeElement = this.element.find( '.lm_close_tab' );
this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ]();
this.isActive = false;
this.setTitle( contentItem.config.title );
this.contentItem.on( 'titleChanged', this.setTitle, this );
this._layoutManager = this.contentItem.layoutManager;
if(
this._layoutManager.config.settings.reorderEnabled === true &&
contentItem.config.reorderEnabled === true
) {
this._dragListener = new lm.utils.DragListener( this.element );
this._dragListener.on( 'dragStart', this._onDragStart, this );
}
this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this );
this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this );
this.element.click( this._onTabClickFn );
if( this.contentItem.config.isClosable ) {
this.closeElement.click( this._onCloseClickFn );
} else {
this.closeElement.remove();
}
this.contentItem.tab = this;
this.contentItem.emit( 'tab', this );
this.contentItem.layoutManager.emit( 'tabCreated', this );
if( this.contentItem.isComponent ) {
this.contentItem.container.tab = this;
this.contentItem.container.emit( 'tab', this );
}
};
/**
* The tab's html template
*
* @type {String}
*/
lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' +
'<span class="lm_title"></span><div class="lm_close_tab"></div>' +
'<i class="lm_right"></i></li>';
lm.utils.copy( lm.controls.Tab.prototype,{
/**
* Sets the tab's title to the provided string and sets
* its title attribute to a pure text representation (without
* html tags) of the same string.
*
* @public
* @param {String} title can contain html
*/
setTitle: function( title ) {
this.element.attr( 'title', lm.utils.stripTags( title ) );
this.titleElement.html( title );
},
/**
* Sets this tab's active state. To programmatically
* switch tabs, use header.setActiveContentItem( item ) instead.
*
* @public
* @param {Boolean} isActive
*/
setActive: function( isActive ) {
if( isActive === this.isActive ) {
return;
}
this.isActive = isActive;
if( isActive ) {
this.element.addClass( 'lm_active' );
} else {
this.element.removeClass( 'lm_active');
}
},
/**
* Destroys the tab
*
* @private
* @returns {void}
*/
_$destroy: function() {
this.element.off( 'click', this._onTabClickFn );
this.closeElement.off( 'click', this._onCloseClickFn );
if( this._dragListener ) {
this._dragListener.off( 'dragStart', this._onDragStart );
this._dragListener = null;
}
this.element.remove();
},
/**
* Callback for the DragListener
*
* @param {Number} x The tabs absolute x position
* @param {Number} y The tabs absolute y position
*
* @private
* @returns {void}
*/
_onDragStart: function( x, y ) {
if( this.contentItem.parent.isMaximised === true ) {
this.contentItem.parent.toggleMaximise();
}
new lm.controls.DragProxy(
x,
y,
this._dragListener,
this._layoutManager,
this.contentItem,
this.header.parent
);
},
/**
* Callback when the tab is clicked
*
* @param {jQuery DOM event} event
*
* @private
* @returns {void}
*/
_onTabClick: function( event ) {
// left mouse button
if( event.button === 0 ) {
var activeContentItem = this.header.parent.getActiveContentItem();
if (this.contentItem !== activeContentItem) {
this.header.parent.setActiveContentItem( this.contentItem );
}
// middle mouse button
} else if( event.button === 1 && this.contentItem.config.isClosable ) {
this._onCloseClick( event );
}
},
/**
* Callback when the tab's close button is
* clicked
*
* @param {jQuery DOM event} event
*
* @private
* @returns {void}
*/
_onCloseClick: function( event ) {
event.stopPropagation();
this.header.parent.removeChild( this.contentItem );
}
});
lm.controls.TransitionIndicator = function() {
this._element = $( '<div class="lm_transition_indicator"></div>' );
$( document.body ).append( this._element );
this._toElement = null;
this._fromDimensions = null;
this._totalAnimationDuration = 200;
this._animationStartTime = null;
};
lm.utils.copy( lm.controls.TransitionIndicator.prototype, {
destroy: function() {
this._element.remove();
},
transitionElements: function( fromElement, toElement ) {
/**
* TODO - This is not quite as cool as expected. Review.
*/
return;
this._toElement = toElement;
this._animationStartTime = lm.utils.now();
this._fromDimensions = this._measure( fromElement );
this._fromDimensions.opacity = 0.8;
this._element.show().css( this._fromDimensions );
lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
},
_nextAnimationFrame: function() {
var toDimensions = this._measure( this._toElement ),
animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration,
currentFrameStyles = {},
cssProperty;
if( animationProgress >= 1 ) {
this._element.hide();
return;
}
toDimensions.opacity = 0;
for( cssProperty in this._fromDimensions ) {
currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] +
( toDimensions[ cssProperty] - this._fromDimensions[ cssProperty ] ) *
animationProgress;
}
this._element.css( currentFrameStyles );
lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) );
},
_measure: function( element ) {
var offset = element.offset();
return {
left: offset.left,
top: offset.top,
width: element.outerWidth(),
height: element.outerHeight()
};
}
});
lm.errors.ConfigurationError = function( message, node ) {
Error.call( this );
this.name = 'Configuration Error';
this.message = message;
this.node = node;
};
lm.errors.ConfigurationError.prototype = new Error();
/**
* This is the baseclass that all content items inherit from.
* Most methods provide a subset of what the sub-classes do.
*
* It also provides a number of functions for tree traversal
*
* @param {lm.LayoutManager} layoutManager
* @param {item node configuration} config
* @param {lm.item} parent
*
* @event stateChanged
* @event beforeItemDestroyed
* @event itemDestroyed
* @event itemCreated
* @event componentCreated
* @event rowCreated
* @event columnCreated
* @event stackCreated
*
* @constructor
*/
lm.items.AbstractContentItem = function( layoutManager, config, parent ) {
lm.utils.EventEmitter.call( this );
this.config = this._extendItemNode( config );
this.type = config.type;
this.contentItems = [];
this.parent = parent;
this.isInitialised = false;
this.isMaximised = false;
this.isRoot = false;
this.isRow = false;
this.isColumn = false;
this.isStack = false;
this.isComponent = false;
this.layoutManager = layoutManager;
this._pendingEventPropagations = {};
this._throttledEvents = [ 'stateChanged' ];
this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this );
if( config.content ) {
this._createContentItems( config );
}
};
lm.utils.copy( lm.items.AbstractContentItem.prototype, {
/**
* Set the size of the component and its children, called recoursively
*
* @abstract
* @returns void
*/
setSize: function() {
throw new Error( 'Abstract Method' );
},
/**
* Calls a method recoursively downwards on the tree
*
* @param {String} functionName the name of the function to be called
* @param {[Array]}functionArguments optional arguments that are passed to every function
* @param {[bool]} bottomUp Call methods from bottom to top, defaults to false
* @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false
*
* @returns {void}
*/
callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) {
var i;
if( bottomUp !== true && skipSelf !== true ) {
this[ functionName ].apply( this, functionArguments || [] );
}
for( i = 0; i < this.contentItems.length; i++ ) {
this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp );
}
if( bottomUp === true && skipSelf !== true ) {
this[ functionName ].apply( this, functionArguments || [] );
}
},
/**
* Removes a child node (and its children) from the tree
*
* @param {lm.items.ContentItem} contentItem
*
* @returns {void}
*/
removeChild: function( contentItem, keepChild ) {
/*
* Get the position of the item that's to be removed within all content items this node contains
*/
var index = lm.utils.indexOf( contentItem, this.contentItems );
/*
* Make sure the content item to be removed is actually a child of this item
*/
if( index === -1 ) {
throw new Error( 'Can\'t remove child item. Unknown content item' );
}
/**
* Call ._$destroy on the content item. This also calls ._$destroy on all its children
*/
if( keepChild !== true ) {
this.contentItems[ index ]._$destroy();
}
/**
* Remove the content item from this nodes array of children
*/
this.contentItems.splice( index, 1 );
/**
* Remove the item from the configuration
*/
this.config.content.splice( index, 1 );
/**
* If this node still contains other content items, adjust their size
*/
if( this.contentItems.length > 0 ) {
this.callDownwards( 'setSize' );
/**
* If this was the last content item, remove this node as well
*/
} else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) {
this.parent.removeChild( this );
}
},
/**
* Sets up the tree structure for the newly added child
* The responsibility for the actual DOM manipulations lies
* with the concrete item
*
* @param {lm.items.AbstractContentItem} contentItem
* @param {[Int]} index If omitted item will be appended
*/
addChild: function( contentItem, index ) {
if ( index === undefined ) {
index = this.contentItems.length;
}
this.contentItems.splice( index, 0, contentItem );
if( this.config.content === undefined ) {
this.config.content = [];
}
this.config.content.splice( index, 0, contentItem.config );
contentItem.parent = this;
if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) {
contentItem._$init();
}
},
/**
* Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for
* some reason removes all event listeners, so isn't really an option.
*
* @param {lm.item.AbstractContentItem} oldChild
* @param {lm.item.AbstractContentItem} newChild
*
* @returns {void}
*/
replaceChild: function( oldChild, newChild, _$destroyOldChild ) {
newChild = this.layoutManager._$normalizeContentItem( newChild );
var index = lm.utils.indexOf( oldChild, this.contentItems ),
parentNode = oldChild.element[ 0 ].parentNode;
if( index === -1 ) {
throw new Error( 'Can\'t replace child. oldChild is not child of this' );
}
parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] );
/*
* Optionally destroy the old content item
*/
if( _$destroyOldChild === true ) {
oldChild.parent = null;
oldChild._$destroy();
}
/*
* Wire the new contentItem into the tree
*/
this.contentItems[ index ] = newChild;
newChild.parent = this;
/*
* Update tab reference
*/
if ( this.isStack ) {
this.header.tabs[ index ].contentItem = newChild;
}
//TODO This doesn't update the config... refactor to leave item nodes untouched after creation
if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) {
newChild._$init();
}
this.callDownwards( 'setSize' );
},
/**
* Convenience method.
* Shorthand for this.parent.removeChild( this )
*
* @returns {void}
*/
remove: function() {
this.parent.removeChild( this );
},
/**
* Removes the component from the layout and creates a new
* browser window with the component and its children inside
*
* @returns {lm.controls.BrowserPopout}
*/
popout: function() {
var browserPopout = this.layoutManager.createPopout( this );
this.emitBubblingEvent( 'stateChanged' );
return browserPopout;
},
/**
* Maximises the Item or minimises it if it is already maximised
*
* @returns {void}
*/
toggleMaximise: function() {
if( this.isMaximised === true ) {
this.layoutManager._$minimiseItem( this );
} else {
this.layoutManager._$maximiseItem( this );
}
this.isMaximised = !this.isMaximised;
this.emitBubblingEvent( 'stateChanged' );
},
/**
* Selects the item if it is not already selected
*
* @returns {void}
*/
select: function() {
if( this.layoutManager.selectedItem !== this ) {
this.layoutManager.selectItem( this, true );
this.element.addClass( 'lm_selected' );
}
},
/**
* De-selects the item if it is selected
*
* @returns {void}
*/
deselect: function() {
if( this.layoutManager.selectedItem === this ) {
this.layoutManager.selectedItem = null;
this.element.removeClass( 'lm_selected' );
}
},
/**
* Set this component's title
*
* @public
* @param {String} title
*
* @returns {void}
*/
setTitle: function( title ) {
this.config.title = title;
this.emit( 'titleChanged', title );
this.emit( 'stateChanged' );
},
/**
* Checks whether a provided id is present
*
* @public
* @param {String} id
*
* @returns {Boolean} isPresent
*/
hasId: function( id ) {
if( !this.config.id ) {
return false;
} else if( typeof this.config.id === 'string' ) {
return this.config.id === id;
} else if( this.config.id instanceof Array ) {
return lm.utils.indexOf( id, this.config.id ) !== -1;
}
},
/**
* Adds an id. Adds it as a string if the component doesn't
* have an id yet or creates/uses an array
*
* @public
* @param {String} id
*
* @returns {void}
*/
addId: function( id ) {
if( this.hasId( id ) ) {
return;
}
if( !this.config.id ) {
this.config.id = id;
} else if( typeof this.config.id === 'string' ) {
this.config.id = [ this.config.id, id ];
} else if( this.config.id instanceof Array ) {
this.config.id.push( id );
}
},
/**
* Removes an existing id. Throws an error
* if the id is not present
*
* @public
* @param {String} id
*
* @returns {void}
*/
removeId: function( id ) {
if( !this.hasId( id ) ) {
throw new Error( 'Id not found' );
}
if( typeof this.config.id === 'string' ) {
delete this.config.id;
} else if( this.config.id instanceof Array ) {
var index = lm.utils.indexOf( id, this.config.id );
this.config.id.splice( index, 1 );
}
},
/****************************************
* SELECTOR
****************************************/
getItemsByFilter: function( filter ) {
var result = [],
next = function( contentItem ) {
for( var i = 0; i < contentItem.contentItems.length; i++ ) {
if( filter( contentItem.contentItems[ i ] ) === true ) {
result.push( contentItem.contentItems[ i ] );
}
next( contentItem.contentItems[ i ] );
}
};
next( this );
return result;
},
getItemsById: function( id ) {
return this.getItemsByFilter( function( item ){
if( item.config.id instanceof Array ) {
return lm.utils.indexOf( id, item.config.id ) !== -1;
} else {
return item.config.id === id;
}
});
},
getItemsByType: function( type ) {
return this._$getItemsByProperty( 'type', type );
},
getComponentsByName: function( componentName ) {
var components = this._$getItemsByProperty( 'componentName', componentName ),
instances = [],
i;
for( i = 0; i < components.length; i++ ) {
instances.push( components[ i ].instance );
}
return instances;
},
/****************************************
* PACKAGE PRIVATE
****************************************/
_$getItemsByProperty: function( key, value ) {
return this.getItemsByFilter( function( item ){
return item[ key ] === value;
});
},
_$setParent: function( parent ) {
this.parent = parent;
},
_$highlightDropZone: function( x, y, area ) {
this.layoutManager.dropTargetIndicator.highlightArea( area );
},
_$onDrop: function( contentItem ) {
this.addChild( contentItem );
},
_$hide: function() {
this._callOnActiveComponents( 'hide' );
this.element.hide();
this.layoutManager.updateSize();
},
_$show: function() {
this._callOnActiveComponents( 'show' );
this.element.show();
this.layoutManager.updateSize();
this._callOnActiveComponents( 'shown' );
},
_callOnActiveComponents: function( methodName ) {
var stacks = this.getItemsByType( 'stack' ),
activeContentItem,
i;
for( i = 0; i < stacks.length; i++ ) {
activeContentItem = stacks[ i ].getActiveContentItem();
if( activeContentItem && activeContentItem.isComponent ) {
activeContentItem.container[ methodName ]();
}
}
},
/**
* Destroys this item ands its children
*
* @returns {void}
*/
_$destroy: function() {
this.emitBubblingEvent( 'beforeItemDestroyed' );
this.callDownwards( '_$destroy', [], true, true );
this.element.remove();
this.emitBubblingEvent( 'itemDestroyed' );
},
/**
* Returns the area the component currently occupies in the format
*
* {
* x1: int
* xy: int
* y1: int
* y2: int
* contentItem: contentItem
* }
*/
_$getArea: function( element ) {
element = element || this.element;
var offset = element.offset(),
width = element.width(),
height = element.height();
return {
x1: offset.left,
y1: offset.top,
x2: offset.left + width,
y2: offset.top + height,
surface: width * height,
contentItem: this
};
},
/**
* The tree of content items is created in two steps: First all content items are instantiated,
* then init is called recoursively from top to bottem. This is the basic init function,
* it can be used, extended or overwritten by the content items
*
* Its behaviour depends on the content item
*
* @package private
*
* @returns {void}
*/
_$init: function() {
var i;
this.setSize();
for( i = 0; i < this.contentItems.length; i++ ) {
this.childElementContainer.append( this.contentItems[ i ].element );
}
this.isInitialised = true;
this.emitBubblingEvent( 'itemCreated' );
this.emitBubblingEvent( this.type + 'Created' );
},
/**
* Emit an event that bubbles up the item tree.
*
* @param {String} name The name of the event
*
* @returns {void}
*/
emitBubblingEvent: function( name ) {
var event = new lm.utils.BubblingEvent( name, this );
this.emit( name, event );
},
/**
* Private method, creates all content items for this node at initialisation time
* PLEASE NOTE, please see addChild for adding contentItems add runtime
* @private
* @param {configuration item node} config
*
* @returns {void}
*/
_createContentItems: function( config ) {
var oContentItem, i;
if( !( config.content instanceof Array ) ) {
throw new lm.errors.ConfigurationError( 'content must be an Array', config );
}
for( i = 0; i < config.content.length; i++ ) {
oContentItem = this.layoutManager.createContentItem( config.content[ i ], this );
this.contentItems.push( oContentItem );
}
},
/**
* Extends an item configuration node with default settings
* @private
* @param {configuration item node} config
*
* @returns {configuration item node} extended config
*/
_extendItemNode: function( config ) {
for( var key in lm.config.itemDefaultConfig ) {
if( config[ key ] === undefined ) {
config[ key ] = lm.config.itemDefaultConfig[ key ];
}
}
return config;
},
/**
* Called for every event on the item tree. Decides whether the event is a bubbling
* event and propagates it to its parent
*
* @param {String} name the name of the event
* @param {lm.utils.BubblingEvent} event
*
* @returns {void}
*/
_propagateEvent: function( name, event ) {
if( event instanceof lm.utils.BubblingEvent &&
event.isPropagationStopped === false &&
this.isInitialised === true ) {
/**
* In some cases (e.g. if an element is created from a DragSource) it
* doesn't have a parent and is not below root. If that's the case
* propagate the bubbling event from the top level of the substree directly
* to the layoutManager
*/
if( this.isRoot === false && this.parent ) {
this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) );
} else {
this._scheduleEventPropagationToLayoutManager( name, event );
}
}
},
/**
* All raw events bubble up to the root element. Some events that
* are propagated to - and emitted by - the layoutManager however are
* only string-based, batched and sanitized to make them more usable
*
* @param {String} name the name of the event
*
* @private
* @returns {void}
*/
_scheduleEventPropagationToLayoutManager: function( name, event ) {
if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) {
this.layoutManager.emit( name, event.origin );
} else {
if( this._pendingEventPropagations[ name ] !== true ) {
this._pendingEventPropagations[ name ] = true;
lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) );
}
}
},
/**
* Callback for events scheduled by _scheduleEventPropagationToLayoutManager
*
* @param {String} name the name of the event
*
* @private
* @returns {void}
*/
_propagateEventToLayoutManager: function( name, event ) {
this._pendingEventPropagations[ name ] = false;
this.layoutManager.emit( name, event );
}
});
/**
* @param {[type]} layoutManager [description]
* @param {[type]} config [description]
* @param {[type]} parent [description]
*/
lm.items.Component = function( layoutManager, config, parent ) {
lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
var ComponentConstructor = layoutManager.getComponent( this.config.componentName ),
componentConfig = $.extend( true, {}, this.config.componentState || {} );
componentConfig.componentName = this.config.componentName;
this.componentName = this.config.componentName;
if( this.config.title === '' ) {
this.config.title = this.config.componentName;
}
this.isComponent = true;
this.container = new lm.container.ItemContainer( this.config, this, layoutManager );
this.instance = new ComponentConstructor( this.container, componentConfig );
this.element = this.container._element;
};
lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem );
lm.utils.copy( lm.items.Component.prototype, {
close: function() {
this.parent.removeChild( this );
},
setSize: function() {
this.container._$setSize( this.element.width(), this.element.height() );
},
_$init: function() {
lm.items.AbstractContentItem.prototype._$init.call( this );
this.container.emit( 'open' );
},
_$hide: function() {
this.container.hide();
lm.items.AbstractContentItem.prototype._$hide.call( this );
},
_$show: function() {
this.container.show();
lm.items.AbstractContentItem.prototype._$show.call( this );
},
_$shown: function() {
this.container.shown();
lm.items.AbstractContentItem.prototype._$shown.call( this );
},
_$destroy: function() {
this.container.emit( 'destroy' );
lm.items.AbstractContentItem.prototype._$destroy.call( this );
},
/**
* Dragging onto a component directly is not an option
*
* @returns null
*/
_$getArea: function() {
return null;
}
});
lm.items.Root = function( layoutManager, config, containerElement ) {
lm.items.AbstractContentItem.call( this, layoutManager, config, null );
this.isRoot = true;
this.type = 'root';
this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' );
this.childElementContainer = this.element;
this._containerElement = containerElement;
this._containerElement.append( this.element );
};
lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem );
lm.utils.copy( lm.items.Root.prototype, {
addChild: function( contentItem ) {
if( this.contentItems.length > 0 ) {
throw new Error( 'Root node can only have a single child' );
}
contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
this.childElementContainer.append( contentItem.element );
lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem );
this.callDownwards( 'setSize' );
this.emitBubblingEvent( 'stateChanged' );
},
setSize: function() {
var width = this._containerElement.width(),
height = this._containerElement.height();
this.element.width( width );
this.element.height( height );
/*
* Root can be empty
*/
if( this.contentItems[ 0 ] ) {
this.contentItems[ 0 ].element.width( width );
this.contentItems[ 0 ].element.height( height );
}
},
_$onDrop: function( contentItem ) {
var stack;
if( contentItem.isComponent === true ) {
stack = this.layoutManager.createContentItem( {type: 'stack' }, this );
stack.addChild( contentItem );
this.addChild( stack );
} else {
this.addChild( contentItem );
}
}
});
lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) {
lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
this.isRow = !isColumn;
this.isColumn = isColumn;
this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' );
this.childElementContainer = this.element;
this._splitterSize = layoutManager.config.dimensions.borderWidth;
this._isColumn = isColumn;
this._dimension = isColumn ? 'height' : 'width';
this._splitter = [];
this._splitterPosition = null;
this._splitterMinPosition = null;
this._splitterMaxPosition = null;
};
lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem );
lm.utils.copy( lm.items.RowOrColumn.prototype, {
/**
* Add a new contentItem to the Row or Column
*
* @param {lm.item.AbstractContentItem} contentItem
* @param {[int]} index The position of the new item within the Row or Column.
* If no index is provided the item will be added to the end
* @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in
* an inconsistent state and is only intended to be used if multiple
* children need to be added in one go and resize is called afterwards
*
* @returns {void}
*/
addChild: function( contentItem, index, _$suspendResize ) {
var newItemSize, itemSize, i, splitterElement;
contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
if( index === undefined ) {
index = this.contentItems.length;
}
if( this.contentItems.length > 0 ) {
splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element;
if( index > 0 ) {
this.contentItems[ index - 1 ].element.after( splitterElement );
splitterElement.after( contentItem.element );
} else {
this.contentItems[ 0 ].element.before( splitterElement );
splitterElement.before( contentItem.element );
}
} else {
this.childElementContainer.append( contentItem.element );
}
lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
newItemSize = ( 1 / this.contentItems.length ) * 100;
if( _$suspendResize === true ) {
this.emitBubblingEvent( 'stateChanged' );
return;
}
for( i = 0; i < this.contentItems.length; i++ ) {
if( this.contentItems[ i ] === contentItem ) {
contentItem.config[ this._dimension ] = newItemSize;
} else {
itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100;
this.contentItems[ i ].config[ this._dimension ] = itemSize;
}
}
this.callDownwards( 'setSize' );
this.emitBubblingEvent( 'stateChanged' );
},
/**
* Removes a child of this element
*
* @param {lm.items.AbstractContentItem} contentItem
* @param {boolean} keepChild If true the child will be removed, but not destroyed
*
* @returns {void}
*/
removeChild: function( contentItem, keepChild ) {
var removedItemSize = contentItem.config[ this._dimension ],
index = lm.utils.indexOf( contentItem, this.contentItems ),
splitterIndex = Math.max( index - 1, 0 ),
i,
childItem;
if( index === -1 ) {
throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' );
}
/**
* Remove the splitter before the item or after if the item happens
* to be the first in the row/column
*/
if( this._splitter[ splitterIndex ] ) {
this._splitter[ splitterIndex ]._$destroy();
this._splitter.splice( splitterIndex, 1 );
}
/**
* Allocate the space that the removed item occupied to the remaining items
*/
for( i = 0; i < this.contentItems.length; i++ ) {
if( this.contentItems[ i ] !== contentItem ) {
this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 );
}
}
lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
if( this.contentItems.length === 1 && this.config.isClosable === true ) {
childItem = this.contentItems[ 0 ];
this.contentItems = [];
this.parent.replaceChild( this, childItem, true );
} else {
this.callDownwards( 'setSize' );
this.emitBubblingEvent( 'stateChanged' );
}
},
/**
* Replaces a child of this Row or Column with another contentItem
*
* @param {lm.items.AbstractContentItem} oldChild
* @param {lm.items.AbstractContentItem} newChild
*
* @returns {void}
*/
replaceChild: function( oldChild, newChild ) {
var size = oldChild.config[ this._dimension ];
lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild );
newChild.config[ this._dimension ] = size;
this.callDownwards( 'setSize' );
this.emitBubblingEvent( 'stateChanged' );
},
/**
* Called whenever the dimensions of this item or one of its parents change
*
* @returns {void}
*/
setSize: function() {
if( this.contentItems.length > 0 ) {
this._calculateRelativeSizes();
this._setAbsoluteSizes();
}
this.emitBubblingEvent( 'stateChanged' );
this.emit( 'resize' );
},
/**
* Invoked recoursively by the layout manager. AbstractContentItem.init appends
* the contentItem's DOM elements to the container, RowOrColumn init adds splitters
* in between them
*
* @package private
* @override AbstractContentItem._$init
* @returns {void}
*/
_$init: function() {
if( this.isInitialised === true ) return;
var i;
lm.items.AbstractContentItem.prototype._$init.call( this );
for( i = 0; i < this.contentItems.length - 1; i++ ) {
this.contentItems[ i ].element.after( this._createSplitter( i ).element );
}
},
/**
* Turns the relative sizes calculated by _calculateRelativeSizes into
* absolute pixel values and applies them to the children's DOM elements
*
* Assigns additional pixels to counteract Math.floor
*
* @private
* @returns {void}
*/
_setAbsoluteSizes: function() {
var i,
totalSplitterSize = ( this.contentItems.length - 1 ) * this._splitterSize,
totalWidth = this.element.width(),
totalHeight = this.element.height(),
totalAssigned = 0,
additionalPixel,
itemSize,
itemSizes = [];
if( this._isColumn ) {
totalHeight -= totalSplitterSize;
} else {
totalWidth -= totalSplitterSize;
}
for( i = 0; i < this.contentItems.length; i++ ) {
if( this._isColumn ) {
itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) );
} else {
itemSize = Math.floor( totalWidth * ( this.contentItems[ i ].config.width / 100 ) );
}
totalAssigned += itemSize;
itemSizes.push( itemSize );
}
additionalPixel = Math.floor( ( this._isColumn ? totalHeight : totalWidth ) - totalAssigned );
for( i = 0; i < this.contentItems.length; i++ ) {
if( additionalPixel - i > 0 ) {
itemSizes[ i ]++;
}
if( this._isColumn ) {
this.contentItems[ i ].element.width( totalWidth );
this.contentItems[ i ].element.height( itemSizes[ i ] );
} else {
this.contentItems[ i ].element.width( itemSizes[ i ] );
this.contentItems[ i ].element.height( totalHeight );
}
}
},
/**
* Calculates the relative sizes of all children of this Item. The logic
* is as follows:
*
* - Add up the total size of all items that have a configured size
*
* - If the total == 100 (check for floating point errors)
* Excellent, job done
*
* - If the total is > 100,
* set the size of items without set dimensions to 1/3 and add this to the total
* set the size off all items so that the total is hundred relative to their original size
*
* - If the total is < 100
* If there are items without set dimensions, distribute the remainder to 100 evenly between them
* If there are no items without set dimensions, increase all items sizes relative to
* their original size so that they add up to 100
*
* @private
* @returns {void}
*/
_calculateRelativeSizes: function() {
var i,
total = 0,
itemsWithoutSetDimension = [],
dimension = this._isColumn ? 'height' : 'width';
for( i = 0; i < this.contentItems.length; i++ ) {
if( this.contentItems[ i ].config[ dimension ] !== undefined ) {
total += this.contentItems[ i ].config[ dimension ];
} else {
itemsWithoutSetDimension.push( this.contentItems[ i ] );
}
}
/**
* Everything adds up to hundred, all good :-)
*/
if( Math.round( total ) === 100 ) {
return;
}
/**
* Allocate the remaining size to the items without a set dimension
*/
if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) {
for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length;
}
return;
}
/**
* If the total is > 100, but there are also items without a set dimension left, assing 50
* as their dimension and add it to the total
*
* This will be reset in the next step
*/
if( Math.round( total ) > 100 ) {
for( i = 0; i < itemsWithoutSetDimension.length; i++ ) {
itemsWithoutSetDimension[ i ].config[ dimension ] = 50;
total += 50;
}
}
/**
* Set every items size relative to 100 relative to its size to total
*/
for( i = 0; i < this.contentItems.length; i++ ) {
this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100;
}
},
/**
* Instantiates a new lm.controls.Splitter, binds events to it and adds
* it to the array of splitters at the position specified as the index argument
*
* What it doesn't do though is append the splitter to the DOM
*
* @param {Int} index The position of the splitter
*
* @returns {lm.controls.Splitter}
*/
_createSplitter: function( index ) {
var splitter;
splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize );
splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this );
splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this );
splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this );
this._splitter.splice( index, 0, splitter );
return splitter;
},
/**
* Locates the instance of lm.controls.Splitter in the array of
* registered splitters and returns a map containing the contentItem
* before and after the splitters, both of which are affected if the
* splitter is moved
*
* @param {lm.controls.Splitter} splitter
*
* @returns {Object} A map of contentItems that the splitter affects
*/
_getItemsForSplitter: function( splitter ) {
var index = lm.utils.indexOf( splitter, this._splitter );
return {
before: this.contentItems[ index ],
after: this.contentItems[ index + 1 ]
};
},
/**
* Gets the minimum dimensions for the given item configuration array
* @param item
* @private
*/
_getMinimumDimensions: function (arr) {
var minWidth = 0, minHeight = 0;
for (var i = 0; i < arr.length; ++i) {
minWidth = Math.max(arr[i].minWidth || 0, minWidth);
minHeight = Math.max(arr[i].minHeight || 0, minHeight);
}
return { horizontal: minWidth, vertical: minHeight };
},
/**
* Invoked when a splitter's dragListener fires dragStart. Calculates the splitters
* movement area once (so that it doesn't need calculating on every mousemove event)
*
* @param {lm.controls.Splitter} splitter
*
* @returns {void}
*/
_onSplitterDragStart: function( splitter ) {
var items = this._getItemsForSplitter( splitter ),
minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ];
var beforeMinDim = this._getMinimumDimensions(items.before.config.content);
var beforeMinSize = this._isColumn ? beforeMinDim.vertical : beforeMinDim.horizontal;
var afterMinDim = this._getMinimumDimensions(items.after.config.content);
var afterMinSize = this._isColumn ? afterMinDim.vertical : afterMinDim.horizontal;
this._splitterPosition = 0;
this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - (beforeMinSize || minSize) );
this._splitterMaxPosition = items.after.element[ this._dimension ]() - (afterMinSize || minSize);
},
/**
* Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position,
* but not the sizes of the elements the splitter controls in order to minimize resize events
*
* @param {lm.controls.Splitter} splitter
* @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative
* @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative
*
* @returns {void}
*/
_onSplitterDrag: function( splitter, offsetX, offsetY ) {
var offset = this._isColumn ? offsetY : offsetX;
if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) {
this._splitterPosition = offset;
splitter.element.css( this._isColumn ? 'top' : 'left', offset );
}
},
/**
* Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position,
* and applies the new sizes to the elements before and after the splitter and their children
* on the next animation frame
*
* @param {lm.controls.Splitter} splitter
*
* @returns {void}
*/
_onSplitterDragStop: function( splitter ) {
var items = this._getItemsForSplitter( splitter ),
sizeBefore = items.before.element[ this._dimension ](),
sizeAfter = items.after.element[ this._dimension ](),
splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ),
totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ];
items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize;
items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize;
splitter.element.css({
'top': 0,
'left': 0
});
lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) );
}
});
lm.items.Stack = function( layoutManager, config, parent ) {
lm.items.AbstractContentItem.call( this, layoutManager, config, parent );
this.element = $( '<div class="lm_item lm_stack"></div>' );
this._activeContentItem = null;
this._dropZones = {};
this._dropSegment = null;
this._contentAreaDimensions = null;
this._dropIndex = null;
this.isStack = true;
this.childElementContainer = $( '<div class="lm_items"></div>' );
this.header = new lm.controls.Header( layoutManager, this );
if( layoutManager.config.settings.hasHeaders === true ) {
this.element.append( this.header.element );
}
this.element.append( this.childElementContainer );
this._$validateClosability();
};
lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem );
lm.utils.copy( lm.items.Stack.prototype, {
setSize: function() {
var i,
contentWidth = this.element.width(),
contentHeight = this.element.height() - this.layoutManager.config.dimensions.headerHeight;
this.childElementContainer.width( contentWidth );
this.childElementContainer.height( contentHeight );
for( i = 0; i < this.contentItems.length; i++ ) {
this.contentItems[ i ].element.width( contentWidth ).height( contentHeight );
}
this.emit( 'resize' );
this.emitBubblingEvent( 'stateChanged' );
},
_$init: function() {
var i, initialItem;
if( this.isInitialised === true ) return;
lm.items.AbstractContentItem.prototype._$init.call( this );
for( i = 0; i < this.contentItems.length; i++ ) {
this.header.createTab( this.contentItems[ i ] );
this.contentItems[ i ]._$hide();
}
if( this.contentItems.length > 0 ) {
initialItem = this.contentItems[ this.config.activeItemIndex || 0 ];
if( !initialItem ) {
throw new Error( 'Configured activeItemIndex out of bounds' );
}
this.setActiveContentItem( initialItem );
}
},
setActiveContentItem: function( contentItem ) {
if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) {
throw new Error( 'contentItem is not a child of this stack' );
}
if( this._activeContentItem !== null ) {
this._activeContentItem._$hide();
}
this._activeContentItem = contentItem;
this.header.setActiveContentItem( contentItem );
contentItem._$show();
this.emit( 'activeContentItemChanged', contentItem );
this.emitBubblingEvent( 'stateChanged' );
},
getActiveContentItem: function() {
return this.header.activeContentItem;
},
addChild: function( contentItem, index ) {
contentItem = this.layoutManager._$normalizeContentItem( contentItem, this );
lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index );
this.childElementContainer.append( contentItem.element );
this.header.createTab( contentItem, index );
this.setActiveContentItem( contentItem );
this.callDownwards( 'setSize' );
this._$validateClosability();
this.emitBubblingEvent( 'stateChanged' );
},
removeChild: function( contentItem, keepChild ) {
var index = lm.utils.indexOf( contentItem, this.contentItems );
lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild );
this.header.removeTab( contentItem );
if( this.contentItems.length > 0 ) {
this.setActiveContentItem( this.contentItems[ Math.max( index -1 , 0 ) ] );
} else {
this._activeContentItem = null;
}
this._$validateClosability();
this.emitBubblingEvent( 'stateChanged' );
},
/**
* Validates that the stack is still closable or not. If a stack is able
* to close, but has a non closable component added to it, the stack is no
* longer closable until all components are closable.
*
* @returns {void}
*/
_$validateClosability: function() {
var contentItem,
isClosable,
len,
i;
isClosable = this.header._isClosable();
for ( i = 0, len = this.contentItems.length; i < len; i++ ) {
if (!isClosable) {
break;
}
isClosable = this.contentItems[ i ].config.isClosable;
}
this.header._$setClosable( isClosable );
},
_$destroy: function() {
lm.items.AbstractContentItem.prototype._$destroy.call( this );
this.header._$destroy();
},
/**
* Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack.
*
* It was dropped on either the stacks header or the top, right, bottom or left bit of the content area
* (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case
* is relatively clear: We add the item to the existing stack... job done (might be good to have
* tab reordering at some point, but lets not sweat it right now)
*
* If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the
* top or bottom region we need to create a new column and place the items accordingly.
* Unless, of course if the stack is already within a column... in which case we want
* to add the newly created item to the existing column...
* either prepend or append it, depending on wether its top or bottom.
*
* Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen
* (left, top, right, bottom) * is child of the right parent (row, column) + header drop
*
* @param {lm.item} contentItem
*
* @returns {void}
*/
_$onDrop: function( contentItem ) {
/*
* The item was dropped on the header area. Just add it as a child of this stack and
* get the hell out of this logic
*/
if( this._dropSegment === 'header' ) {
this._resetHeaderDropZone();
this.addChild( contentItem, this._dropIndex );
return;
}
/*
* The stack is empty. Let's just add the element.
*/
if( this._dropSegment === 'body' ) {
this.addChild( contentItem );
return;
}
/*
* The item was dropped on the top-, left-, bottom- or right- part of the content. Let's
* aggregate some conditions to make the if statements later on more readable
*/
var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom',
isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right',
insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left',
hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ),
type = isVertical ? 'column' : 'row',
dimension = isVertical ? 'height' : 'width',
index,
stack,
rowOrColumn;
/*
* The content item can be either a component or a stack. If it is a component, wrap it into a stack
*/
if( contentItem.isComponent ) {
stack = this.layoutManager.createContentItem({ type: 'stack' }, this );
stack._$init();
stack.addChild( contentItem );
contentItem = stack;
}
/*
* If the item is dropped on top or bottom of a column or left and right of a row, it's already
* layd out in the correct way. Just add it as a child
*/
if( hasCorrectParent ) {
index = lm.utils.indexOf( this, this.parent.contentItems );
this.parent.addChild( contentItem, insertBefore ? index : index + 1, true );
this.config[ dimension ] *= 0.5;
contentItem.config[ dimension ] = this.config[ dimension ];
this.parent.callDownwards( 'setSize' );
/*
* This handles items that are dropped on top or bottom of a row or left / right of a column. We need
* to create the appropriate contentItem for them to life in
*/
} else {
type = isVertical ? 'column' : 'row';
rowOrColumn = this.layoutManager.createContentItem({ type: type }, this );
this.parent.replaceChild( this, rowOrColumn );
rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true );
rowOrColumn.addChild( this, insertBefore ? undefined : 0, true );
this.config[ dimension ] = 50;
contentItem.config[ dimension ] = 50;
rowOrColumn.callDownwards( 'setSize' );
}
},
/**
* If the user hovers above the header part of the stack, indicate drop positions for tabs.
* otherwise indicate which segment of the body the dragged item would be dropped on
*
* @param {Int} x Absolute Screen X
* @param {Int} y Absolute Screen Y
*
* @returns {void}
*/
_$highlightDropZone: function( x, y ) {
var segment, area;
for( segment in this._contentAreaDimensions ) {
area = this._contentAreaDimensions[ segment ].hoverArea;
if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) {
if( segment === 'header' ) {
this._dropSegment = 'header';
this._highlightHeaderDropZone( x );
} else {
this._resetHeaderDropZone();
this._highlightBodyDropZone( segment );
}
return;
}
}
},
_$getArea: function() {
if( this.element.is( ':visible' ) === false ) {
return null;
}
var getArea = lm.items.AbstractContentItem.prototype._$getArea,
headerArea = getArea.call( this, this.header.element ),
contentArea = getArea.call( this, this.childElementContainer ),
contentWidth = contentArea.x2 - contentArea.x1,
contentHeight = contentArea.y2 - contentArea.y1;
this._contentAreaDimensions = {
header: {
hoverArea: {
x1: headerArea.x1,
y1: headerArea.y1,
x2: headerArea.x2,
y2: headerArea.y2
},
highlightArea: {
x1: headerArea.x1,
y1: headerArea.y1,
x2: headerArea.x2,
y2: headerArea.y2
}
}
};
/**
* If this Stack is a parent to rows, columns or other stacks only its
* header is a valid dropzone.
*/
if( this._activeContentItem && this._activeContentItem.isComponent === false ) {
return headerArea;
}
/**
* Highlight the entire body if the stack is empty
*/
if( this.contentItems.length === 0 ) {
this._contentAreaDimensions.body = {
hoverArea: {
x1: contentArea.x1,
y1: contentArea.y1,
x2: contentArea.x2,
y2: contentArea.y2
},
highlightArea: {
x1: contentArea.x1,
y1: contentArea.y1,
x2: contentArea.x2,
y2: contentArea.y2
}
};
return getArea.call( this, this.element );
}
this._contentAreaDimensions.left = {
hoverArea: {
x1: contentArea.x1,
y1: contentArea.y1,
x2: contentArea.x1 + contentWidth * 0.25,
y2: contentArea.y2
},
highlightArea: {
x1: contentArea.x1,
y1: contentArea.y1,
x2: contentArea.x1 + contentWidth * 0.5,
y2: contentArea.y2
}
};
this._contentAreaDimensions.top = {
hoverArea: {
x1: contentArea.x1 + contentWidth * 0.25,
y1: contentArea.y1,
x2: contentArea.x1 + contentWidth * 0.75,
y2: contentArea.y1 + contentHeight * 0.5
},
highlightArea: {
x1: contentArea.x1,
y1: contentArea.y1,
x2: contentArea.x2,
y2: contentArea.y1 + contentHeight * 0.5
}
};
this._contentAreaDimensions.right = {
hoverArea: {
x1: contentArea.x1 + contentWidth * 0.75,
y1: contentArea.y1,
x2: contentArea.x2,
y2: contentArea.y2
},
highlightArea: {
x1: contentArea.x1 + contentWidth * 0.5,
y1: contentArea.y1,
x2: contentArea.x2,
y2: contentArea.y2
}
};
this._contentAreaDimensions.bottom = {
hoverArea: {
x1: contentArea.x1 + contentWidth * 0.25,
y1: contentArea.y1 + contentHeight * 0.5,
x2: contentArea.x1 + contentWidth * 0.75,
y2: contentArea.y2
},
highlightArea: {
x1: contentArea.x1,
y1: contentArea.y1 + contentHeight * 0.5,
x2: contentArea.x2,
y2: contentArea.y2
}
};
return getArea.call( this, this.element );
},
_highlightHeaderDropZone: function( x ) {
var i,
tabElement,
tabsLength = this.header.tabs.length,
isAboveTab = false,
tabTop,
tabLeft,
offset,
placeHolderLeft,
headerOffset,
tabWidth,
halfX;
// Empty stack
if( tabsLength === 0 ) {
headerOffset = this.header.element.offset();
this.layoutManager.dropTargetIndicator.highlightArea({
x1: headerOffset.left,
x2: headerOffset.left + 100,
y1: headerOffset.top + this.header.element.height() - 20,
y2: headerOffset.top + this.header.element.height()
});
return;
}
for( i = 0; i < tabsLength; i++ ) {
tabElement = this.header.tabs[ i ].element;
offset = tabElement.offset();
tabLeft = offset.left;
tabTop = offset.top;
tabWidth = tabElement.width();
if( x > tabLeft && x < tabLeft + tabWidth ) {
isAboveTab = true;
break;
}
}
if( isAboveTab === false && x < tabLeft ) {
return;
}
halfX = tabLeft + tabWidth / 2;
if( x < halfX ) {
this._dropIndex = i;
tabElement.before( this.layoutManager.tabDropPlaceholder );
} else {
this._dropIndex = Math.min( i + 1, tabsLength );
tabElement.after( this.layoutManager.tabDropPlaceholder );
}
placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left;
this.layoutManager.dropTargetIndicator.highlightArea({
x1: placeHolderLeft,
x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(),
y1: tabTop,
y2: tabTop + tabElement.innerHeight()
});
},
_resetHeaderDropZone: function() {
this.layoutManager.tabDropPlaceholder.remove();
},
_highlightBodyDropZone: function( segment ) {
var highlightArea = this._contentAreaDimensions[ segment ].highlightArea;
this.layoutManager.dropTargetIndicator.highlightArea( highlightArea );
this._dropSegment = segment;
}
});
lm.utils.BubblingEvent = function( name, origin ) {
this.name = name;
this.origin = origin;
this.isPropagationStopped = false;
};
lm.utils.BubblingEvent.prototype.stopPropagation = function() {
this.isPropagationStopped = true;
};
/**
* Minifies and unminifies configs by replacing frequent keys
* and values with one letter substitutes
*
* @constructor
*/
lm.utils.ConfigMinifier = function(){
this._keys = [
'settings',
'hasHeaders',
'constrainDragToContainer',
'selectionEnabled',
'dimensions',
'borderWidth',
'minItemHeight',
'minItemWidth',
'headerHeight',
'dragProxyWidth',
'dragProxyHeight',
'labels',
'close',
'maximise',
'minimise',
'popout',
'content',
'componentName',
'componentState',
'id',
'width',
'type',
'height',
'isClosable',
'title',
'popoutWholeStack',
'openPopouts',
'parentId',
'activeItemIndex',
'reorderEnabled'
//Maximum 36 entries, do not cross this line!
];
this._values = [
true,
false,
'row',
'column',
'stack',
'component',
'close',
'maximise',
'minimise',
'open in new window'
];
};
lm.utils.copy( lm.utils.ConfigMinifier.prototype, {
/**
* Takes a GoldenLayout configuration object and
* replaces its keys and values recoursively with
* one letter counterparts
*
* @param {Object} config A GoldenLayout config object
*
* @returns {Object} minified config
*/
minifyConfig: function( config ) {
var min = {};
this._nextLevel( config, min, '_min' );
return min;
},
/**
* Takes a configuration Object that was previously minified
* using minifyConfig and returns its original version
*
* @param {Object} minifiedConfig
*
* @returns {Object} the original configuration
*/
unminifyConfig: function( minifiedConfig ) {
var orig = {};
this._nextLevel( minifiedConfig, orig, '_max' );
return orig;
},
/**
* Recoursive function, called for every level of the config structure
*
* @param {Array|Object} orig
* @param {Array|Object} min
* @param {String} translationFn
*
* @returns {void}
*/
_nextLevel: function( from, to, translationFn ) {
var key, minKey;
for( key in from ) {
/**
* For in returns array indices as keys, so let's cast them to numbers
*/
if( from instanceof Array ) key = parseInt( key, 10 );
/**
* In case something has extended Object prototypes
*/
if( !from.hasOwnProperty( key ) ) continue;
/**
* Translate the key to a one letter substitute
*/
minKey = this[ translationFn ]( key, this._keys );
/**
* For Arrays and Objects, create a new Array/Object
* on the minified object and recourse into it
*/
if( typeof from[ key ] === 'object' ) {
to[ minKey ] = from[ key ] instanceof Array ? [] : {};
this._nextLevel( from[ key ], to[ minKey ], translationFn );
/**
* For primitive values (Strings, Numbers, Boolean etc.)
* minify the value
*/
} else {
to[ minKey ] = this[ translationFn ]( from[ key ], this._values );
}
}
},
/**
* Minifies value based on a dictionary
*
* @param {String|Boolean} value
* @param {Array<String|Boolean>} dictionary
*
* @returns {String} The minified version
*/
_min: function( value, dictionary ) {
/**
* If a value actually is a single character, prefix it
* with ___ to avoid mistaking it for a minification code
*/
if( typeof value === 'string' && value.length === 1 ) {
return '___' + value;
}
var index = lm.utils.indexOf( value, dictionary );
/**
* value not found in the dictionary, return it unmodified
*/
if( index === -1 ) {
return value;
/**
* value found in dictionary, return its base36 counterpart
*/
} else {
return index.toString( 36 );
}
},
_max: function( value, dictionary ) {
/**
* value is a single character. Assume that it's a translation
* and return the original value from the dictionary
*/
if( typeof value === 'string' && value.length === 1 ) {
return dictionary[ parseInt( value, 36 ) ];
}
/**
* value originally was a single character and was prefixed with ___
* to avoid mistaking it for a translation. Remove the prefix
* and return the original character
*/
if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) {
return value[ 3 ];
}
/**
* value was not minified
*/
return value;
}
});
/**
* An EventEmitter singleton that propagates events
* across multiple windows. This is a little bit trickier since
* windows are allowed to open childWindows in their own right
*
* This means that we deal with a tree of windows. Hence the rules for event propagation are:
*
* - Propagate events from this layout to both parents and children
* - Propagate events from parent to this and children
* - Propagate events from children to the other children (but not the emitting one) and the parent
*
* @constructor
*
* @param {lm.LayoutManager} layoutManager
*/
lm.utils.EventHub = function( layoutManager ) {
lm.utils.EventEmitter.call( this );
this._layoutManager = layoutManager;
this._dontPropagateToParent = null;
this._childEventSource = null;
this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) );
this._boundOnEventFromChild = lm.utils.fnBind( this._onEventFromChild, this );
$(window).on( 'gl_child_event', this._boundOnEventFromChild );
};
/**
* Called on every event emitted on this eventHub, regardles of origin.
*
* @private
*
* @param {Mixed}
*
* @returns {void}
*/
lm.utils.EventHub.prototype._onEventFromThis = function() {
var args = Array.prototype.slice.call( arguments );
if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) {
this._propagateToParent( args );
}
this._propagateToChildren( args );
//Reset
this._dontPropagateToParent = null;
this._childEventSource = null;
};
/**
* Called by the parent layout.
*
* @param {Array} args Event name + arguments
*
* @returns {void}
*/
lm.utils.EventHub.prototype._$onEventFromParent = function( args ) {
this._dontPropagateToParent = args[ 0 ];
this.emit.apply( this, args );
};
/**
* Callback for child events raised on the window
*
* @param {DOMEvent} event
* @private
*
* @returns {void}
*/
lm.utils.EventHub.prototype._onEventFromChild = function( event ) {
this._childEventSource = event.originalEvent.__gl;
this.emit.apply( this, event.originalEvent.__glArgs );
};
/**
* Propagates the event to the parent by emitting
* it on the parent's DOM window
*
* @param {Array} args Event name + arguments
* @private
*
* @returns {void}
*/
lm.utils.EventHub.prototype._propagateToParent = function( args ) {
var event,
eventName = 'gl_child_event';
if (document.createEvent) {
event = window.opener.document.createEvent( 'HTMLEvents' );
event.initEvent( eventName, true, true);
} else {
event = window.opener.document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.__glArgs = args;
event.__gl = this._layoutManager;
if (document.createEvent) {
window.opener.dispatchEvent(event);
} else {
window.opener.fireEvent( 'on' + event.eventType, event );
}
};
/**
* Propagate events to children
*
* @param {Array} args Event name + arguments
* @private
*
* @returns {void}
*/
lm.utils.EventHub.prototype._propagateToChildren = function( args ) {
var childGl, i;
for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) {
childGl = this._layoutManager.openPopouts[ i ].getGlInstance();
if( childGl !== this._childEventSource ) {
childGl.eventHub._$onEventFromParent( args );
}
}
};
/**
* Destroys the EventHub
*
* @public
* @returns {void}
*/
lm.utils.EventHub.prototype.destroy = function() {
$(window).off( 'gl_child_event', this._boundOnEventFromChild );
};
/**
* A specialised GoldenLayout component that binds GoldenLayout container
* lifecycle events to react components
*
* @constructor
*
* @param {lm.container.ItemContainer} container
* @param {Object} state state is not required for react components
*/
lm.utils.ReactComponentHandler = function( container, state ) {
this._reactComponent = null;
this._originalComponentWillUpdate = null;
this._container = container;
this._initialState = state;
this._reactClass = this._getReactClass();
this._container.on( 'open', this._render, this );
this._container.on( 'destroy', this._destroy, this );
};
lm.utils.copy( lm.utils.ReactComponentHandler.prototype, {
/**
* Creates the react class and component and hydrates it with
* the initial state - if one is present
*
* By default, react's getInitialState will be used
*
* @private
* @returns {void}
*/
_render: function() {
this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ]);
this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function(){};
this._reactComponent.componentWillUpdate = this._onUpdate.bind( this );
if( this._container.getState() ) {
this._reactComponent.setState( this._container.getState() );
}
},
/**
* Removes the component from the DOM and thus invokes React's unmount lifecycle
*
* @private
* @returns {void}
*/
_destroy: function() {
ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ]);
this._container.off( 'open', this._render, this );
this._container.off( 'destroy', this._destroy, this );
},
/**
* Hooks into React's state management and applies the componentstate
* to GoldenLayout
*
* @private
* @returns {void}
*/
_onUpdate: function( nextProps, nextState ) {
this._container.setState( nextState );
this._originalComponentWillUpdate.call( this._reactComponent, nextProps, nextState );
},
/**
* Retrieves the react class from GoldenLayout's registry
*
* @private
* @returns {React.Class}
*/
_getReactClass: function() {
var componentName = this._container._config.component;
var reactClass;
if( !componentName ) {
throw new Error( 'No react component name. type: react-component needs a field `component`' );
}
reactClass = this._container.layoutManager.getComponent( componentName );
if( !reactClass ) {
throw new Error( 'React component "' + componentName + '" not found. ' +
'Please register all components with GoldenLayout using `registerComponent(name, component)`' );
}
return reactClass;
},
/**
* Copies and extends the properties array and returns the React element
*
* @private
* @returns {React.Element}
*/
_getReactComponent: function() {
var defaultProps = {
glEventHub: this._container.layoutManager.eventHub,
glContainer: this._container,
};
var props = $.extend( defaultProps, this._container._config.props );
return React.createElement( this._reactClass, props );
}
});})(window.$);
|
src/NewDrink.js
|
martonbognar/bali-react
|
import React, { Component } from 'react';
import DRINKS from './data/drinkList';
class NewDrink extends Component {
constructor(props) {
super(props);
this.state = {name: '', amount: '', strength: '', startTime: new Date().getTime(), selectedDrink: ''};
this.resetState = this.resetState.bind(this);
this.refreshStartTime = this.refreshStartTime.bind(this);
this.handlePresetChanged = this.handlePresetChanged.bind(this);
this.handleNameChanged = this.handleNameChanged.bind(this);
this.handleAmountChanged = this.handleAmountChanged.bind(this);
this.handleStrengthChanged = this.handleStrengthChanged.bind(this);
this.handleStartTimeChanged = this.handleStartTimeChanged.bind(this);
this.submitData = this.submitData.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentWillMount() {
this.setState({
drinkList: DRINKS
});
}
resetState() {
this.setState({name: '', amount: '', strength: '', startTime: new Date().getTime(), selectedDrink: ''});
}
refreshStartTime(event) {
event.preventDefault();
this.setState({startTime: new Date().getTime()});
}
handlePresetChanged(event) {
this.state.drinkList.forEach(function (category) {
category.values.forEach(function (drink) {
if (drink.key === event.target.value) {
this.setState({name: drink.name, amount: drink.amount, strength: drink.strength});
}
}, this);
}, this);
this.setState({selectedDrink: event.target.value});
}
handleNameChanged(event) {
this.setState({name: event.target.value});
}
handleAmountChanged(event) {
let input = event.target.value.replace(',', '.');
if (isNaN(input)) {
this.setState({amount: ''});
} else {
this.setState({amount: input});
}
}
handleStrengthChanged(event) {
let input = event.target.value.replace(',', '.');
if (isNaN(input)) {
this.setState({strength: ''});
} else {
this.setState({strength: input});
}
}
handleStartTimeChanged(event) {
this.setState({startTime: new Date(event.target.value).getTime()});
}
submitData() {
this.props.onChange(this.state);
this.resetState();
}
handleSubmit(event) {
event.preventDefault();
this.setState({amount: parseFloat(this.state.amount), strength: parseFloat(this.state.strength)}, this.submitData);
}
render() {
let startTime = new Date(this.state.startTime);
let startString = startTime.getFullYear() + '-' + ('0' + (startTime.getMonth() + 1)).slice(-2) + '-' + ('0' + startTime.getDate()).slice(-2) + 'T' + ('0' + startTime.getHours()).slice(-2) + ':' + ('0' + startTime.getMinutes()).slice(-2);
let drinks = [];
this.state.drinkList.forEach(function (category) {
let values = [];
category.values.forEach(function (drink) {
values.push(<option value={drink.key} key={drink.key}>{drink.name}</option>);
});
drinks.push(<optgroup label={category.categoryName}>{values}</optgroup>);
});
return (
<form onSubmit={this.handleSubmit} id='new-drink'>
<select onChange={this.handlePresetChanged} value={this.state.selectedDrink}>
<option value='' disabled>Choose from a preset</option>
{drinks}
</select>
<br />
Or define your own:
<br />
<input type='text' onChange={this.handleNameChanged} value={this.state.name} placeholder='Drink Name' required />
<br />
<input type='text' onChange={this.handleAmountChanged} value={this.state.amount} placeholder='Amount (cl)' required />
<br />
<input type='text' onChange={this.handleStrengthChanged} value={this.state.strength} placeholder='Strength (%)' required />
<br />
<input type='datetime-local' onChange={this.handleStartTimeChanged} required value={startString} />
<br />
<a href='#' onClick={this.refreshStartTime}>Set to now</a>
<br />
<button className='submit'>Submit</button>
</form>
);
}
}
export default NewDrink;
|
ajax/libs/jquery/1.11.0-beta3/jquery.js
|
BobbieBel/cdnjs
|
/*!
* jQuery JavaScript Library v1.11.0-beta3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-12-20T22:44Z
*/
(function( global, factory ) {
if ( 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 inherently posses a window with a document
// (such as Node.js), expose a jQuery-making 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 ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this, window may not be defined yet
}(this, function( window ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var trim = "".trim;
var support = {};
var
version = "1.11.0-beta3",
// Define a local copy of jQuery
jQuery = function( 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 );
},
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
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( num ) {
return num != null ?
// Return a 'clean' array
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return just the object
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( 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;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, 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 !== "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 = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.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( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: trim && !trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( 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( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( 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( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
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( fn, context ) {
var args, proxy, tmp;
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() {
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: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.15
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-12-20
*/
(function( window ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[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
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
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( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"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 = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// 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 );
};
// 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 match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
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 div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = 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 = attrs.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 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// 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 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 !== strundefined && 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,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
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 !== strundefined && 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 http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// 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
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select t=''><option selected=''></option></select>";
// Support: IE8, Opera 10-12
// Nothing should be selected when empty strings follow ^= or $= or *=
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// 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 ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.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 ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[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 does not implement inclusive descendent
// 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 === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( 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 === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( 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 doc;
};
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 &&
( !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.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( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( 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( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// 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( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( 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 !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( 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 + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( 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, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
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
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && 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 ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// 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 ) {
(node[ expando ] || (node[ expando ] = {}))[ 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, 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.call( 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 );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
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( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( 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( 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( 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( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( 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();
function tokenize( 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,
checkNonElements = base && dir === "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 );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir 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 ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
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 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.call( 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.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
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 ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( 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;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// 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;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// 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 );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
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, group /* 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 ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && 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;
}
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
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
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
// 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( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.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( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.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( div ) {
return div.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;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
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 ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
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;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( 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,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// 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 <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( 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;
// 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] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).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.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
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.extend({
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.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.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( 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 jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], 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" ?
( optionsCache[ options ] || 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,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
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( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
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( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
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,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// 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 ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
jQuery(function() {
// We need to execute this one support test ASAP because we need to know
// if body.style.zoom needs to be set.
var container, div,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
container = document.createElement( "div" );
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
div = document.createElement( "div" );
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1";
if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = null;
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
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 intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( 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( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( 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( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( 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 cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.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( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = document.createElement("div"),
input = document.createElement("input");
input.type = "checkbox";
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
fragment.appendChild( input );
support.appendChecked = input.checked;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
fragment = div = input = null;
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* 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( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( 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;
}
// 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 !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + 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;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
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 the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
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(".") >= 0 ) {
// 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 === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = 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 = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.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) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && 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;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( 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;
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.namespace_re || event.namespace_re.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( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
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() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
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() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, 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: IE < 9
src.returnValue === false ||
// Support: Android < 4.0
src.getPreventDefault && src.getPreventDefault() ) ?
returnTrue :
returnFalse;
// 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
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/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;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
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( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
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 this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( 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 this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( 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 === "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 );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "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;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, 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; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
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 || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.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 );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
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 );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( 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() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
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() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
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 this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
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 ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[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 || "" ) &&
!jQuery._data( 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 {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var a, shrinkWrapBlocksVal,
div = document.createElement( "div" ),
divReset =
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" +
"display:block;padding:0;margin:0;border:0";
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
a.style.cssText = "float:left;opacity:.5";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Null elements to avoid leaks in IE.
a = div = null;
support.shrinkWrapBlocks = function() {
var body, container, div, containerStyles;
if ( shrinkWrapBlocksVal == null ) {
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px";
container = document.createElement( "div" );
div = document.createElement( "div" );
body.appendChild( container ).appendChild( div );
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.cssText = divReset + ";width:1px;padding:1px;zoom:1";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
// Null elements to avoid leaks in IE.
body = container = div = null;
}
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( 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;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var a, reliableHiddenOffsetsVal, boxSizingVal, boxSizingReliableVal,
pixelPositionVal, reliableMarginRightVal,
div = document.createElement( "div" ),
containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px",
divReset =
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" +
"display:block;padding:0;margin:0;border:0";
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
a.style.cssText = "float:left;opacity:.5";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Null elements to avoid leaks in IE.
a = div = null;
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal != null ) {
return reliableHiddenOffsetsVal;
}
var container, tds, isSupported,
div = document.createElement( "div" ),
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
container = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
reliableHiddenOffsetsVal = isSupported && ( tds[ 0 ].offsetHeight === 0 );
body.removeChild( container );
// Null elements to avoid leaks in IE.
div = body = null;
return reliableHiddenOffsetsVal;
},
boxSizing: function() {
if ( boxSizingVal == null ) {
computeStyleTests();
}
return boxSizingVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
reliableMarginRight: function() {
var body, container, div, marginDiv;
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( reliableMarginRightVal == null && window.getComputedStyle ) {
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
container = document.createElement( "div" );
div = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement( "div" ) );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
body.removeChild( container );
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
var container, div,
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
container = document.createElement( "div" );
div = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
div.style.cssText =
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" +
"position:absolute;display:block;padding:1px;border:1px;width:4px;" +
"margin-top:1%;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
boxSizingVal = div.offsetWidth === 4;
});
// Will be changed later if needed.
boxSizingReliableVal = true;
pixelPositionVal = false;
reliableMarginRightVal = true;
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
}
body.removeChild( container );
// Null elements to avoid leaks in IE.
div = body = null;
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( 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;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// 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]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 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 offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the 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 ] );
// 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( 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: {
"columnCount": true,
"fillOpacity": 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: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( 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 ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
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 ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
// Support: Chrome, Safari
// Setting style to blank string required to delete "style: x !important;"
style[ name ] = "";
style[ name ] = value;
} catch(e) {}
}
} 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( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
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 ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( 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( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.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 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
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( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( 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( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || 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
// so, 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( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( 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
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, 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 = ( tweeners[ prop ] || [] ).concat( 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 ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, dDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
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() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
dDisplay = defaultDisplay( elem.nodeName );
if ( display === "none" ) {
display = dDisplay;
}
if ( display === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || dDisplay === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 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 ( jQuery.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 wont overwrite keys already present.
// also - reusing 'index' from above 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 = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// 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 ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( 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( 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.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 = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ 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( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// 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 || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( 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 = jQuery._data( 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( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( 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,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// 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 = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var a, input, select, opt,
div = document.createElement("div" );
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// Null elements to avoid leaks in IE.
a = input = select = opt = div = null;
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( 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;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
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 ( jQuery.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( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE 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
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.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( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// 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( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// 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" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = 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, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
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 ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.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.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error 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( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// 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( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 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 deep, key,
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 firstDataType, ct, finalDataType, type,
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: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
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: /xml/,
html: /html/,
json: /json/
},
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": jQuery.parseJSON,
// 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( 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( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// 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 = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
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() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// 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 || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// 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 ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = 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
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// 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 || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// 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 ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
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 {
// We extract error from statusText
// then normalize statusText and status 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( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( 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;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// 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._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var 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.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( 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( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
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 ( jQuery.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 === "object" ? 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( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.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( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
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();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
// XHR cannot access local files, always use ActiveX for that case
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
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 ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
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") && 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() {
// Restore preexisting value
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";
}
});
// data: 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 ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
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 === "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
type: type,
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 );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( 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" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -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 ) ) {
options = options.call( elem, i, 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( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 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" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we 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 ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return 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
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
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, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
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)
window.jQuery = window.$ = jQuery;
return jQuery;
}));
|
src/components/TeamNode.js
|
cessien/buzzer
|
// src/components/TeamNode.js
import React from 'react';
export default class TeamNode extends React.Component {
render() {
return (
<div style={this.props.styles}>{this.props.name}</div>
);
}
}
|
src/DropdownToggle.js
|
thealjey/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const CARET = <span> <span className="caret" /></span>;
export default class DropdownToggle extends React.Component {
render() {
const caret = this.props.noCaret ? null : CARET;
const classes = {
'dropdown-toggle': true
};
const Component = this.props.useAnchor ? SafeAnchor : Button;
return (
<Component
{...this.props}
className={classNames(classes, this.props.className)}
type="button"
aria-haspopup
aria-expanded={this.props.open}>
{this.props.title || this.props.children}{caret}
</Component>
);
}
}
const titleAndChildrenValidation = CustomPropTypes.singlePropFrom([
'title',
'children'
]);
DropdownToggle.defaultProps = {
open: false,
useAnchor: false,
bsRole: 'toggle'
};
DropdownToggle.propTypes = {
bsRole: React.PropTypes.string,
children: titleAndChildrenValidation,
noCaret: React.PropTypes.bool,
open: React.PropTypes.bool,
title: titleAndChildrenValidation,
useAnchor: React.PropTypes.bool
};
DropdownToggle.isToggle = true;
DropdownToggle.titleProp = 'title';
DropdownToggle.onClickProp = 'onClick';
|
components/articleTemplate.js
|
halfatheist/halfatheist.github.io
|
import _ from 'lodash';
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import DocumentTitle from 'react-document-title'
import { config } from 'config'
import moment from 'moment';
import Header from './header';
import Footer from './footer';
import Social from './social';
export default class Template extends React.Component {
render () {
let { title, bodyHtml, bodyText, date, headerImage } = this.props.data,
url = `${config.baseUrl}${this.props.path}`;
let when = moment(date).fromNow();
return (
<DocumentTitle title={`${title} | ${config.siteTitle}`}>
<div className="page article">
<Header activeNav="articles" />
<main>
<section className="header">
<img src={`/img/${headerImage}`} />
<h1 className="title">{title}</h1>
<div className="date">{when}</div>
</section>
<section className="post-header">
<div className="body" dangerouslySetInnerHTML={{ __html: bodyHtml }} />
<div className="meta">
<Social
title={title}
description={_.truncate(bodyText, 100)}
url={url} />
<Link className="read-more-articles" to="/articles/">Read more articles</Link>
</div>
</section>
</main>
<Footer />
</div>
</DocumentTitle>
);
}
}
Template.propTypes = {
data: React.PropTypes.object,
path: React.PropTypes.string,
};
|
src/components/NoteWrap.js
|
gorand/redux_test
|
import React, { Component, PropTypes } from 'react';
import NoteItem from './NoteItem';
class NoteWrap extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.interval = setInterval(() => {
this.props.actions.updateTime(new Date());
}, 10000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
const { notes, actions, time } = this.props;
return (
<section className="note__wrap">
<ul className="note__list">
{notes.map(item =>
<NoteItem key={item.id} note={item} {...actions} current={time.current} />
)}
</ul>
</section>
);
}
}
NoteWrap.propTypes = {
notes: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
time: PropTypes.object.isRequired
};
export default NoteWrap;
|
app/javascript/tagging/components/InnerComponents/TagCategory.js
|
ManageIQ/manageiq-ui-classic
|
/* eslint-disable react/destructuring-assignment */
import React from 'react';
import PropTypes from 'prop-types';
import Tag from './Tag';
import TaggingPropTypes from '../TaggingPropTypes';
class TagCategory extends React.Component {
generateTag = (tagValue) => (
<Tag
key={tagValue.id}
tagCategory={this.props.tagCategory}
tagValue={tagValue}
onTagDeleteClick={this.props.onTagDeleteClick}
truncate={this.props.valueTruncate}
showCloseButton={this.props.showCloseButton}
/>
);
render() {
const values = [...this.props.values];
return (
<ul className="tag-category list-inline">
<li key={this.props.tagCategory.id} id={`tag_category_${this.props.tagCategory.id}`}>
<div className="category-label" title={this.props.tagCategory.description}>
{this.props.categoryTruncate(this.props.tagCategory.description)}
</div>
</li>
{values
.sort((a, b) => (a.description < b.description ? -1 : 1))
.map((tagValue) => this.generateTag(tagValue))}
</ul>
);
}
}
TagCategory.propTypes = {
onTagDeleteClick: PropTypes.func.isRequired,
tagCategory: TaggingPropTypes.category,
values: PropTypes.arrayOf(TaggingPropTypes.category).isRequired,
categoryTruncate: PropTypes.func,
valueTruncate: PropTypes.func,
showCloseButton: PropTypes.bool,
};
TagCategory.defaultProps = {
tagCategory: undefined,
categoryTruncate: (str) =>
(str.length > 18 ? `${str.substring(0, 18)}...` : str),
valueTruncate: (str) => (str.length > 18 ? `${str.substring(0, 18)}...` : str),
showCloseButton: true,
};
export default TagCategory;
|
js/vendor/jquery-1.11.3.min.js
|
ethanabowen/StockProject
|
/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
//# sourceMappingURL=jquery.min.map
|
src/Parser/Warlock/Demonology/Modules/Talents/ImprovedDreadstalkers.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import PETS from 'common/PETS';
import { formatNumber, formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import DemoPets from '../WarlockCore/Pets';
class ImprovedDreadstalkers extends Analyzer {
static dependencies = {
demoPets: DemoPets,
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.IMPROVED_DREADSTALKERS_TALENT.id);
}
statistic() {
const wildImpDamage = this.demoPets.getTotalPetDamage(PETS.WILDIMP_ON_DREADSTALKER.id); // fortunately, Wild Imps summoned by this talent have different guid than regular Wild Imps, making this rather easy
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.IMPROVED_DREADSTALKERS_TALENT.id} />}
value={`${formatNumber(wildImpDamage / this.owner.fightDuration * 1000)} DPS`}
label="Bonus Wild Imp damage"
tooltip={`Your Wild Imps summoned with Dreadstalkers did ${formatNumber(wildImpDamage)} damage (${formatPercentage(this.owner.getPercentageOfTotalDamageDone(wildImpDamage))} %).`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(1);
}
export default ImprovedDreadstalkers;
|
docs/app/Examples/elements/Container/Types/index.js
|
shengnian/shengnian-ui-react
|
/* eslint-disable max-len */
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import { Message } from 'shengnian-ui-react'
const ContainerTypesExamples = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Container'
description='A standard container.'
examplePath='elements/Container/Types/ContainerExampleContainer'
/>
<ComponentExample
title='Text Container'
description='A container can reduce its maximum width to more naturally accommodate a single column of text.'
examplePath='elements/Container/Types/ContainerExampleText'
>
<Message info>
<p>A text container is a simpler markup alternative to using a grid with a single column, and is designed to have a reasonable maximum width for displaying flowing text</p>
</Message>
</ComponentExample>
</ExampleSection>
)
export default ContainerTypesExamples
|
ajax/libs/react-bootstrap-table/2.0.1/react-bootstrap-table.min.js
|
sufuf3/cdnjs
|
!function(Q,F){"object"==typeof exports&&"object"==typeof module?module.exports=F(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],F):"object"==typeof exports?exports.ReactBootstrapTable=F(require("react"),require("react-dom")):Q.ReactBootstrapTable=F(Q.React,Q.ReactDOM)}(this,function(__WEBPACK_EXTERNAL_MODULE_2__,__WEBPACK_EXTERNAL_MODULE_6__){return function(Q){function F(e){if(U[e])return U[e].exports;var B=U[e]={exports:{},id:e,loaded:!1};return Q[e].call(B.exports,B,B.exports,F),B.loaded=!0,B.exports}var U={};return F.m=Q,F.c=U,F.p="",F(0)}([function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nvar _BootstrapTable = __webpack_require__(1);\n\nvar _BootstrapTable2 = _interopRequireDefault(_BootstrapTable);\n\nvar _TableHeaderColumn = __webpack_require__(41);\n\nvar _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn);\n\nvar _storeTableDataStore = __webpack_require__(34);\n\nif (typeof window !== 'undefined') {\n window.BootstrapTable = _BootstrapTable2['default'];\n window.TableHeaderColumn = _TableHeaderColumn2['default'];\n window.TableDataSet = _storeTableDataStore.TableDataSet;\n}\nexports['default'] = {\n BootstrapTable: _BootstrapTable2['default'],\n TableHeaderColumn: _TableHeaderColumn2['default'],\n TableDataSet: _storeTableDataStore.TableDataSet\n};\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvaW5kZXguanM/OTU1MiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7OzswQ0FBMkIsQ0FBa0I7Ozs7NkNBQ2YsRUFBcUI7Ozs7K0NBQ3hCLEVBQXdCOztBQUVuRCxJQUFHLE9BQU8sTUFBTSxLQUFLLFdBQVcsRUFBQztBQUMvQixRQUFNLENBQUMsY0FBYyw4QkFBaUIsQ0FBQztBQUN2QyxRQUFNLENBQUMsaUJBQWlCLGlDQUFvQixDQUFDO0FBQzdDLFFBQU0sQ0FBQyxZQUFZLG9DQUFlLENBQUM7Q0FDcEM7cUJBQ2M7QUFDYixnQkFBYztBQUNkLG1CQUFpQjtBQUNqQixjQUFZO0NBQ2IiLCJmaWxlIjoiMC5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBCb290c3RyYXBUYWJsZSBmcm9tICcuL0Jvb3RzdHJhcFRhYmxlJztcbmltcG9ydCBUYWJsZUhlYWRlckNvbHVtbiBmcm9tICcuL1RhYmxlSGVhZGVyQ29sdW1uJztcbmltcG9ydCB7VGFibGVEYXRhU2V0fSBmcm9tICcuL3N0b3JlL1RhYmxlRGF0YVN0b3JlJztcblxuaWYodHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcpe1xuICB3aW5kb3cuQm9vdHN0cmFwVGFibGUgPSBCb290c3RyYXBUYWJsZTtcbiAgd2luZG93LlRhYmxlSGVhZGVyQ29sdW1uID0gVGFibGVIZWFkZXJDb2x1bW47XG4gIHdpbmRvdy5UYWJsZURhdGFTZXQgPSBUYWJsZURhdGFTZXQ7XG59XG5leHBvcnQgZGVmYXVsdCB7XG4gIEJvb3RzdHJhcFRhYmxlLFxuICBUYWJsZUhlYWRlckNvbHVtbixcbiAgVGFibGVEYXRhU2V0XG59O1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvaW5kZXguanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _TableHeader = __webpack_require__(5);\n\nvar _TableHeader2 = _interopRequireDefault(_TableHeader);\n\nvar _TableBody = __webpack_require__(9);\n\nvar _TableBody2 = _interopRequireDefault(_TableBody);\n\nvar _paginationPaginationList = __webpack_require__(30);\n\nvar _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList);\n\nvar _toolbarToolBar = __webpack_require__(32);\n\nvar _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar);\n\nvar _TableFilter = __webpack_require__(33);\n\nvar _TableFilter2 = _interopRequireDefault(_TableFilter);\n\nvar _storeTableDataStore = __webpack_require__(34);\n\nvar _util = __webpack_require__(7);\n\nvar _util2 = _interopRequireDefault(_util);\n\nvar _csv_export_util = __webpack_require__(36);\n\nvar _csv_export_util2 = _interopRequireDefault(_csv_export_util);\n\nvar _Filter = __webpack_require__(40);\n\nvar BootstrapTable = (function (_React$Component) {\n _inherits(BootstrapTable, _React$Component);\n\n function BootstrapTable(props) {\n var _this = this;\n\n _classCallCheck(this, BootstrapTable);\n\n _get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props);\n\n this._scrollHeader = function (e) {\n _this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft;\n };\n\n this._adjustTable = function () {\n _this._adjustHeaderWidth();\n _this._adjustHeight();\n };\n\n this._adjustHeaderWidth = function () {\n var header = _this.refs.header.refs.header;\n var headerContainer = _this.refs.header.refs.container;\n var tbody = _this.refs.body.refs.tbody;\n var firstRow = tbody.childNodes[0];\n var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth;\n var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0;\n if (firstRow && _this.store.getDataNum()) {\n var cells = firstRow.childNodes;\n for (var i = 0; i < cells.length; i++) {\n var cell = cells[i];\n var computedStyle = getComputedStyle(cell);\n var width = parseFloat(computedStyle.width.replace(\"px\", \"\"));\n if (_this.isIE) {\n var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace(\"px\", \"\"));\n var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace(\"px\", \"\"));\n var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace(\"px\", \"\"));\n var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace(\"px\", \"\"));\n width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth;\n }\n var lastPadding = cells.length - 1 == i ? scrollBarWidth : 0;\n if (width <= 0) {\n width = 120;\n cell.width = width + lastPadding + \"px\";\n }\n var result = width + lastPadding + \"px\";\n header.childNodes[i].style.width = result;\n header.childNodes[i].style.minWidth = result;\n }\n }\n };\n\n this._adjustHeight = function () {\n if (_this.props.height.indexOf('%') === -1) {\n _this.refs.body.refs.container.style.height = parseFloat(_this.props.height) - _this.refs.header.refs.container.offsetHeight + \"px\";\n }\n };\n\n this.isIE = false;\n this._attachCellEditFunc();\n if (document) {\n this.isIE = document.documentMode;\n }\n if (!Array.isArray(this.props.data)) {\n this.store = new _storeTableDataStore.TableDataStore(this.props.data.getData());\n this.props.data.clear();\n this.props.data.on('change', function (data) {\n _this.store.setData(data);\n _this.setState({\n data: _this.getTableData()\n });\n });\n } else {\n var copy = this.props.data.slice();\n this.store = new _storeTableDataStore.TableDataStore(copy);\n }\n\n this.initTable(this.props);\n\n if (this.filter) {\n (function () {\n var self = _this;\n _this.filter.on('onFilterChange', function (currentFilter) {\n self.handleFilterData(currentFilter);\n });\n })();\n }\n\n if (this.props.selectRow && this.props.selectRow.selected) {\n var copy = this.props.selectRow.selected.slice();\n this.store.setSelectedRowKey(copy);\n }\n\n this.state = {\n data: this.getTableData(),\n currPage: this.props.options.page || 1,\n sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0],\n selectedRowKeys: this.store.getSelectedRowKeys()\n };\n }\n\n _createClass(BootstrapTable, [{\n key: 'initTable',\n value: function initTable(props) {\n var _this2 = this;\n\n var keyField = props.keyField;\n\n var isKeyFieldDefined = typeof keyField === 'string' && keyField.length;\n _react2['default'].Children.forEach(props.children, function (column) {\n if (column.props.isKey) {\n if (keyField) {\n throw \"Error. Multiple key column be detected in TableHeaderColumn.\";\n }\n keyField = column.props.dataField;\n }\n if (column.props.filter) {\n // a column contains a filter\n if (!_this2.filter) {\n // first time create the filter on the BootstrapTable\n _this2.filter = new _Filter.Filter();\n }\n // pass the filter to column with filter\n column.props.filter.emitter = _this2.filter;\n }\n }, this);\n\n var colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) {\n prev[curr.name] = curr;\n return prev;\n }, {});\n\n if (!isKeyFieldDefined && !keyField) throw 'Error. No any key column defined in TableHeaderColumn.\\n Use \\'isKey={true}\\' to specify a unique column after version 0.5.4.';\n\n this.store.setProps({\n isPagination: props.pagination,\n keyField: keyField,\n colInfos: colInfos,\n multiColumnSearch: props.multiColumnSearch,\n remote: this.isRemoteDataSource()\n });\n }\n }, {\n key: 'getTableData',\n value: function getTableData() {\n var result = [];\n\n if (this.props.options.sortName && this.props.options.sortOrder) this.store.sort(this.props.options.sortOrder, this.props.options.sortName);\n\n if (this.props.pagination) {\n var page = undefined,\n sizePerPage = undefined;\n if (this.store.isChangedPage()) {\n sizePerPage = this.state.sizePerPage;\n page = this.state.currPage;\n } else {\n sizePerPage = this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0];\n page = this.props.options.page || 1;\n }\n result = this.store.page(page, sizePerPage).get();\n } else {\n result = this.store.get();\n }\n return result;\n }\n }, {\n key: 'getColumnsDescription',\n value: function getColumnsDescription(_ref) {\n var children = _ref.children;\n\n return _react2['default'].Children.map(children, function (column, i) {\n return {\n name: column.props.dataField,\n align: column.props.dataAlign,\n sort: column.props.dataSort,\n format: column.props.dataFormat,\n formatExtraData: column.props.formatExtraData,\n filterFormatted: column.props.filterFormatted,\n editable: column.props.editable,\n hidden: column.props.hidden,\n searchable: column.props.searchable,\n className: column.props.columnClassName,\n width: column.props.width,\n text: column.props.children,\n sortFunc: column.props.sortFunc,\n index: i\n };\n });\n }\n }, {\n key: 'componentWillReceiveProps',\n value: function componentWillReceiveProps(nextProps) {\n this.initTable(nextProps);\n if (Array.isArray(nextProps.data)) {\n this.store.setData(nextProps.data.slice());\n var page = nextProps.options.page || this.state.currPage;\n var sizePerPage = nextProps.options.sizePerPage || this.state.sizePerPage;\n\n // #125\n if (!nextProps.options.page && page >= Math.ceil(nextProps.data.length / sizePerPage)) {\n page = 1;\n }\n var sortInfo = this.store.getSortInfo();\n var sortField = nextProps.options.sortName || (sortInfo ? sortInfo.sortField : undefined);\n var sortOrder = nextProps.options.sortOrder || (sortInfo ? sortInfo.order : undefined);\n if (sortField && sortOrder) this.store.sort(sortOrder, sortField);\n var data = this.store.page(page, sizePerPage).get();\n this.setState({\n data: data,\n currPage: page,\n sizePerPage: sizePerPage\n });\n }\n if (nextProps.selectRow && nextProps.selectRow.selected) {\n //set default select rows to store.\n var copy = nextProps.selectRow.selected.slice();\n this.store.setSelectedRowKey(copy);\n this.setState({\n selectedRowKeys: copy\n });\n }\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n this._adjustTable();\n window.addEventListener('resize', this._adjustTable);\n this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader);\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n window.removeEventListener('resize', this._adjustTable);\n this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader);\n if (this.filter) {\n this.filter.removeAllListeners(\"onFilterChange\");\n }\n }\n }, {\n key: 'componentDidUpdate',\n value: function componentDidUpdate() {\n this._adjustTable();\n this._attachCellEditFunc();\n if (this.props.options.afterTableComplete) this.props.options.afterTableComplete();\n }\n }, {\n key: '_attachCellEditFunc',\n value: function _attachCellEditFunc() {\n if (this.props.cellEdit) {\n this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this);\n if (this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) this.props.selectRow.clickToSelect = false;\n }\n }\n\n /**\n * Returns true if in the current configuration,\n * the datagrid should load its data remotely.\n *\n * @param {Object} [props] Optional. If not given, this.props will be used\n * @return {Boolean}\n */\n }, {\n key: 'isRemoteDataSource',\n value: function isRemoteDataSource(props) {\n return (props || this.props).remote;\n }\n }, {\n key: 'render',\n value: function render() {\n var childrens = this.props.children;\n var style = {\n height: this.props.height,\n maxHeight: this.props.maxHeight\n };\n if (!Array.isArray(this.props.children)) {\n childrens = [this.props.children];\n }\n var columns = this.getColumnsDescription(this.props);\n var sortInfo = this.store.getSortInfo();\n var pagination = this.renderPagination();\n var toolBar = this.renderToolBar();\n var tableFilter = this.renderTableFilter(columns);\n var isSelectAll = this.isSelectAll();\n var sortIndicator = this.props.options.sortIndicator;\n if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true;\n return _react2['default'].createElement(\n 'div',\n { className: 'react-bs-table-container' },\n toolBar,\n _react2['default'].createElement(\n 'div',\n { className: 'react-bs-table', ref: 'table', style: style,\n onMouseEnter: this.handleMouseEnter.bind(this),\n onMouseLeave: this.handleMouseLeave.bind(this) },\n _react2['default'].createElement(\n _TableHeader2['default'],\n {\n ref: 'header',\n rowSelectType: this.props.selectRow.mode,\n hideSelectColumn: this.props.selectRow.hideSelectColumn,\n sortName: sortInfo ? sortInfo.sortField : undefined,\n sortOrder: sortInfo ? sortInfo.order : undefined,\n sortIndicator: sortIndicator,\n onSort: this.handleSort.bind(this),\n onSelectAllRow: this.handleSelectAllRow.bind(this),\n bordered: this.props.bordered,\n condensed: this.props.condensed,\n isFiltered: this.filter ? true : false,\n isSelectAll: isSelectAll },\n this.props.children\n ),\n _react2['default'].createElement(_TableBody2['default'], {\n ref: 'body',\n style: style,\n data: this.state.data,\n columns: columns,\n trClassName: this.props.trClassName,\n striped: this.props.striped,\n bordered: this.props.bordered,\n hover: this.props.hover,\n keyField: this.store.getKeyField(),\n condensed: this.props.condensed,\n selectRow: this.props.selectRow,\n cellEdit: this.props.cellEdit,\n selectedRowKeys: this.state.selectedRowKeys,\n onRowClick: this.handleRowClick.bind(this),\n onRowMouseOver: this.handleRowMouseOver.bind(this),\n onRowMouseOut: this.handleRowMouseOut.bind(this),\n onSelectRow: this.handleSelectRow.bind(this),\n noDataText: this.props.options.noDataText\n })\n ),\n tableFilter,\n pagination\n );\n }\n }, {\n key: 'isSelectAll',\n value: function isSelectAll() {\n var defaultSelectRowKeys = this.store.getSelectedRowKeys();\n var allRowKeys = this.store.getAllRowkey();\n if (defaultSelectRowKeys.length !== allRowKeys.length) {\n return defaultSelectRowKeys.length === 0 ? false : 'indeterminate';\n } else {\n return true;\n }\n }\n }, {\n key: 'cleanSelected',\n value: function cleanSelected() {\n this.store.setSelectedRowKey([]);\n this.setState({\n selectedRowKeys: []\n });\n }\n }, {\n key: 'handleSort',\n value: function handleSort(order, sortField) {\n if (this.props.options.onSortChange) {\n this.props.options.onSortChange(sortField, order, this.props);\n }\n\n var result = this.store.sort(order, sortField).get();\n this.setState({\n data: result\n });\n }\n }, {\n key: 'handlePaginationData',\n value: function handlePaginationData(page, sizePerPage) {\n var onPageChange = this.props.options.onPageChange;\n\n if (onPageChange) {\n onPageChange(page, sizePerPage);\n }\n\n if (this.isRemoteDataSource()) {\n return;\n }\n\n var result = this.store.page(page, sizePerPage).get();\n this.setState({\n data: result,\n currPage: page,\n sizePerPage: sizePerPage\n });\n }\n }, {\n key: 'handleMouseLeave',\n value: function handleMouseLeave() {\n if (this.props.options.onMouseLeave) {\n this.props.options.onMouseLeave();\n }\n }\n }, {\n key: 'handleMouseEnter',\n value: function handleMouseEnter() {\n if (this.props.options.onMouseEnter) {\n this.props.options.onMouseEnter();\n }\n }\n }, {\n key: 'handleRowMouseOut',\n value: function handleRowMouseOut(row) {\n if (this.props.options.onRowMouseOut) {\n this.props.options.onRowMouseOut(row);\n }\n }\n }, {\n key: 'handleRowMouseOver',\n value: function handleRowMouseOver(row) {\n if (this.props.options.onRowMouseOver) {\n this.props.options.onRowMouseOver(row);\n }\n }\n }, {\n key: 'handleRowClick',\n value: function handleRowClick(row) {\n if (this.props.options.onRowClick) {\n this.props.options.onRowClick(row);\n }\n }\n }, {\n key: 'handleSelectAllRow',\n value: function handleSelectAllRow(e) {\n var isSelected = e.currentTarget.checked;\n var selectedRowKeys = [];\n var result = true;\n if (this.props.selectRow.onSelectAll) {\n result = this.props.selectRow.onSelectAll(isSelected, isSelected ? this.store.get() : []);\n }\n\n if (typeof result === 'undefined' || result !== false) {\n if (isSelected) {\n selectedRowKeys = this.store.getAllRowkey();\n }\n\n this.store.setSelectedRowKey(selectedRowKeys);\n this.setState({\n selectedRowKeys: selectedRowKeys\n });\n }\n }\n }, {\n key: 'handleShowOnlySelected',\n value: function handleShowOnlySelected() {\n this.store.ignoreNonSelected();\n var result = undefined;\n if (this.props.pagination) {\n result = this.store.page(1, this.state.sizePerPage).get();\n } else {\n result = this.store.get();\n }\n this.setState({\n data: result,\n currPage: 1\n });\n }\n }, {\n key: 'handleSelectRow',\n value: function handleSelectRow(row, isSelected) {\n var currSelected = this.store.getSelectedRowKeys();\n var rowKey = row[this.store.getKeyField()];\n var result = true;\n if (this.props.selectRow.onSelect) {\n result = this.props.selectRow.onSelect(row, isSelected);\n }\n\n if (typeof result === 'undefined' || result !== false) {\n if (this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {\n currSelected = isSelected ? [rowKey] : [];\n } else {\n if (isSelected) {\n currSelected.push(rowKey);\n } else {\n currSelected = currSelected.filter(function (key) {\n return rowKey !== key;\n });\n }\n }\n\n this.store.setSelectedRowKey(currSelected);\n this.setState({\n selectedRowKeys: currSelected\n });\n }\n }\n }, {\n key: 'handleEditCell',\n value: function handleEditCell(newVal, rowIndex, colIndex) {\n var fieldName = undefined;\n _react2['default'].Children.forEach(this.props.children, function (column, i) {\n if (i == colIndex) {\n fieldName = column.props.dataField;\n return false;\n }\n });\n\n var result = this.store.edit(newVal, rowIndex, fieldName).get();\n this.setState({\n data: result\n });\n\n if (this.props.cellEdit.afterSaveCell) {\n this.props.cellEdit.afterSaveCell(this.state.data[rowIndex], fieldName, newVal);\n }\n }\n }, {\n key: 'handleAddRowBegin',\n value: function handleAddRowBegin() {\n if (this.refs.body) {\n // this.refs.body.cancelEdit();\n }\n }\n }, {\n key: 'handleAddRowAtBegin',\n value: function handleAddRowAtBegin(newObj) {\n var result = undefined;\n try {\n this.store.addAtBegin(newObj);\n } catch (e) {\n return e;\n }\n this._handleAfterAddingRow(newObj);\n }\n }, {\n key: 'handleAddRow',\n value: function handleAddRow(newObj) {\n var result = undefined;\n try {\n this.store.add(newObj);\n } catch (e) {\n return e;\n }\n this._handleAfterAddingRow(newObj);\n }\n }, {\n key: 'getSizePerPage',\n value: function getSizePerPage() {\n return this.state.sizePerPage;\n }\n }, {\n key: 'getCurrentPage',\n value: function getCurrentPage() {\n return this.state.currPage;\n }\n }, {\n key: 'handleDropRow',\n value: function handleDropRow(rowKeys) {\n var that = this;\n var dropRowKeys = rowKeys ? rowKeys : this.store.getSelectedRowKeys();\n //add confirm before the delete action if that option is set.\n if (dropRowKeys && dropRowKeys.length > 0) {\n if (this.props.options.handleConfirmDeleteRow) {\n this.props.options.handleConfirmDeleteRow(function () {\n that.deleteRow(dropRowKeys);\n });\n } else if (confirm('Are you sure want delete?')) {\n this.deleteRow(dropRowKeys);\n }\n }\n }\n }, {\n key: 'deleteRow',\n value: function deleteRow(dropRowKeys) {\n\n var result = undefined;\n this.store.remove(dropRowKeys); //remove selected Row\n this.store.setSelectedRowKey([]); //clear selected row key\n\n if (this.props.pagination) {\n var sizePerPage = this.state.sizePerPage;\n var currPage = this.state.currPage;\n\n var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);\n if (currPage > currLastPage) currPage = currLastPage;\n result = this.store.page(currPage, sizePerPage).get();\n this.setState({\n data: result,\n selectedRowKeys: this.store.getSelectedRowKeys(),\n currPage: currPage\n });\n } else {\n result = this.store.get();\n this.setState({\n data: result,\n selectedRowKeys: this.store.getSelectedRowKeys()\n });\n }\n if (this.props.options.afterDeleteRow) {\n this.props.options.afterDeleteRow(dropRowKeys);\n }\n }\n }, {\n key: 'handleFilterData',\n value: function handleFilterData(filterObj) {\n this.store.filter(filterObj);\n var result = undefined;\n if (this.props.pagination) {\n var sizePerPage = this.state.sizePerPage;\n\n result = this.store.page(1, sizePerPage).get();\n } else {\n result = this.store.get();\n }\n if (this.props.options.afterColumnFilter) this.props.options.afterColumnFilter(filterObj, this.store.getDataIgnoringPagination());\n this.setState({\n data: result,\n currPage: 1\n });\n }\n }, {\n key: 'handleExportCSV',\n value: function handleExportCSV() {\n var result = this.store.getDataIgnoringPagination();\n var keys = [];\n this.props.children.map(function (column) {\n if (column.props.hidden === false) {\n keys.push(column.props.dataField);\n }\n });\n (0, _csv_export_util2['default'])(result, keys, this.props.csvFileName);\n }\n }, {\n key: 'handleSearch',\n value: function handleSearch(searchText) {\n this.store.search(searchText);\n var result = undefined;\n if (this.props.pagination) {\n var sizePerPage = this.state.sizePerPage;\n\n result = this.store.page(1, sizePerPage).get();\n } else {\n result = this.store.get();\n }\n if (this.props.options.afterSearch) this.props.options.afterSearch(searchText, this.store.getDataIgnoringPagination());\n this.setState({\n data: result,\n currPage: 1\n });\n }\n }, {\n key: 'renderPagination',\n value: function renderPagination() {\n if (this.props.pagination) {\n var dataSize = undefined;\n if (this.isRemoteDataSource()) {\n dataSize = this.props.fetchInfo.dataTotalSize;\n } else {\n dataSize = this.store.getDataNum();\n }\n return _react2['default'].createElement(\n 'div',\n { className: 'react-bs-table-pagination' },\n _react2['default'].createElement(_paginationPaginationList2['default'], {\n ref: 'pagination',\n currPage: this.state.currPage,\n changePage: this.handlePaginationData.bind(this),\n sizePerPage: this.state.sizePerPage,\n sizePerPageList: this.props.options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST,\n paginationSize: this.props.options.paginationSize || _Const2['default'].PAGINATION_SIZE,\n remote: this.isRemoteDataSource(),\n dataSize: dataSize,\n onSizePerPageList: this.props.options.onSizePerPageList,\n prePage: this.props.options.prePage || _Const2['default'].PRE_PAGE,\n nextPage: this.props.options.nextPage || _Const2['default'].NEXT_PAGE,\n firstPage: this.props.options.firstPage || _Const2['default'].FIRST_PAGE,\n lastPage: this.props.options.lastPage || _Const2['default'].LAST_PAGE\n })\n );\n }\n return null;\n }\n }, {\n key: 'renderToolBar',\n value: function renderToolBar() {\n var enableShowOnlySelected = this.props.selectRow && this.props.selectRow.showOnlySelected;\n if (enableShowOnlySelected || this.props.insertRow || this.props.deleteRow || this.props.search || this.props.exportCSV) {\n var columns = undefined;\n if (Array.isArray(this.props.children)) {\n columns = this.props.children.map(function (column) {\n var props = column.props;\n return {\n name: props.children,\n field: props.dataField,\n //when you want same auto generate value and not allow edit, example ID field\n autoValue: props.autoValue || false,\n //for create editor, no params for column.editable() indicate that editor for new row\n editable: props.editable && typeof props.editable === \"function\" ? props.editable() : props.editable,\n format: props.dataFormat ? function (value) {\n return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, '');\n } : false\n };\n });\n } else {\n columns = [{\n name: this.props.children.props.children,\n field: this.props.children.props.dataField,\n editable: this.props.children.props.editable\n }];\n }\n return _react2['default'].createElement(\n 'div',\n { className: 'react-bs-table-tool-bar' },\n _react2['default'].createElement(_toolbarToolBar2['default'], {\n clearSearch: this.props.options.clearSearch,\n enableInsert: this.props.insertRow,\n enableDelete: this.props.deleteRow,\n enableSearch: this.props.search,\n enableExportCSV: this.props.exportCSV,\n enableShowOnlySelected: enableShowOnlySelected,\n columns: columns,\n searchPlaceholder: this.props.searchPlaceholder,\n onAddRow: this.handleAddRow.bind(this),\n onAddRowBegin: this.handleAddRowBegin.bind(this),\n onDropRow: this.handleDropRow.bind(this),\n onSearch: this.handleSearch.bind(this),\n onExportCSV: this.handleExportCSV.bind(this),\n onShowOnlySelected: this.handleShowOnlySelected.bind(this)\n })\n );\n } else {\n return null;\n }\n }\n }, {\n key: 'renderTableFilter',\n value: function renderTableFilter(columns) {\n if (this.props.columnFilter) {\n return _react2['default'].createElement(_TableFilter2['default'], { columns: columns,\n rowSelectType: this.props.selectRow.mode,\n onFilter: this.handleFilterData.bind(this) });\n } else {\n return null;\n }\n }\n }, {\n key: '_handleAfterAddingRow',\n value: function _handleAfterAddingRow(newObj) {\n var result = undefined;\n if (this.props.pagination) {\n //if pagination is enabled and insert row be trigger, change to last page\n var sizePerPage = this.state.sizePerPage;\n\n var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);\n result = this.store.page(currLastPage, sizePerPage).get();\n this.setState({\n data: result,\n currPage: currLastPage\n });\n } else {\n result = this.store.get();\n this.setState({\n data: result\n });\n }\n\n if (this.props.options.afterInsertRow) {\n this.props.options.afterInsertRow(newObj);\n }\n }\n }]);\n\n return BootstrapTable;\n})(_react2['default'].Component);\n\nBootstrapTable.propTypes = {\n keyField: _react2['default'].PropTypes.string,\n height: _react2['default'].PropTypes.string,\n maxHeight: _react2['default'].PropTypes.string,\n data: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.array, _react2['default'].PropTypes.object]),\n remote: _react2['default'].PropTypes.bool, // remote data, default is false\n striped: _react2['default'].PropTypes.bool,\n bordered: _react2['default'].PropTypes.bool,\n hover: _react2['default'].PropTypes.bool,\n condensed: _react2['default'].PropTypes.bool,\n pagination: _react2['default'].PropTypes.bool,\n searchPlaceholder: _react2['default'].PropTypes.string,\n selectRow: _react2['default'].PropTypes.shape({\n mode: _react2['default'].PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]),\n bgColor: _react2['default'].PropTypes.string,\n selected: _react2['default'].PropTypes.array,\n onSelect: _react2['default'].PropTypes.func,\n onSelectAll: _react2['default'].PropTypes.func,\n clickToSelect: _react2['default'].PropTypes.bool,\n hideSelectColumn: _react2['default'].PropTypes.bool,\n clickToSelectAndEditCell: _react2['default'].PropTypes.bool,\n showOnlySelected: _react2['default'].PropTypes.bool\n }),\n cellEdit: _react2['default'].PropTypes.shape({\n mode: _react2['default'].PropTypes.string,\n blurToSave: _react2['default'].PropTypes.bool,\n afterSaveCell: _react2['default'].PropTypes.func\n }),\n insertRow: _react2['default'].PropTypes.bool,\n deleteRow: _react2['default'].PropTypes.bool,\n search: _react2['default'].PropTypes.bool,\n columnFilter: _react2['default'].PropTypes.bool,\n trClassName: _react2['default'].PropTypes.any,\n options: _react2['default'].PropTypes.shape({\n clearSearch: _react2['default'].PropTypes.bool,\n sortName: _react2['default'].PropTypes.string,\n sortOrder: _react2['default'].PropTypes.string,\n sortIndicator: _react2['default'].PropTypes.bool,\n afterTableComplete: _react2['default'].PropTypes.func,\n afterDeleteRow: _react2['default'].PropTypes.func,\n afterInsertRow: _react2['default'].PropTypes.func,\n afterSearch: _react2['default'].PropTypes.func,\n afterColumnFilter: _react2['default'].PropTypes.func,\n onRowClick: _react2['default'].PropTypes.func,\n page: _react2['default'].PropTypes.number,\n sizePerPageList: _react2['default'].PropTypes.array,\n sizePerPage: _react2['default'].PropTypes.number,\n paginationSize: _react2['default'].PropTypes.number,\n onSortChange: _react2['default'].PropTypes.func,\n onPageChange: _react2['default'].PropTypes.func,\n onSizePerPageList: _react2['default'].PropTypes.func,\n noDataText: _react2['default'].PropTypes.string,\n handleConfirmDeleteRow: _react2['default'].PropTypes.func,\n prePage: _react2['default'].PropTypes.string,\n nextPage: _react2['default'].PropTypes.string,\n firstPage: _react2['default'].PropTypes.string,\n lastPage: _react2['default'].PropTypes.string\n }),\n fetchInfo: _react2['default'].PropTypes.shape({\n dataTotalSize: _react2['default'].PropTypes.number\n }),\n exportCSV: _react2['default'].PropTypes.bool,\n csvFileName: _react2['default'].PropTypes.string\n};\nBootstrapTable.defaultProps = {\n height: \"100%\",\n maxHeight: undefined,\n striped: false,\n bordered: true,\n hover: false,\n condensed: false,\n pagination: false,\n searchPlaceholder: undefined,\n selectRow: {\n mode: _Const2['default'].ROW_SELECT_NONE,\n bgColor: _Const2['default'].ROW_SELECT_BG_COLOR,\n selected: [],\n onSelect: undefined,\n onSelectAll: undefined,\n clickToSelect: false,\n hideSelectColumn: false,\n clickToSelectAndEditCell: false,\n showOnlySelected: false\n },\n cellEdit: {\n mode: _Const2['default'].CELL_EDIT_NONE,\n blurToSave: false,\n afterSaveCell: undefined\n },\n insertRow: false,\n deleteRow: false,\n search: false,\n multiColumnSearch: false,\n columnFilter: false,\n trClassName: '',\n options: {\n clearSearch: false,\n sortName: undefined,\n sortOrder: undefined,\n sortIndicator: true,\n afterTableComplete: undefined,\n afterDeleteRow: undefined,\n afterInsertRow: undefined,\n afterSearch: undefined,\n afterColumnFilter: undefined,\n onRowClick: undefined,\n onMouseLeave: undefined,\n onMouseEnter: undefined,\n onRowMouseOut: undefined,\n onRowMouseOver: undefined,\n page: undefined,\n sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST,\n sizePerPage: undefined,\n paginationSize: _Const2['default'].PAGINATION_SIZE,\n onSizePerPageList: undefined,\n noDataText: undefined,\n handleConfirmDeleteRow: undefined,\n prePage: _Const2['default'].PRE_PAGE,\n nextPage: _Const2['default'].NEXT_PAGE,\n firstPage: _Const2['default'].FIRST_PAGE,\n lastPage: _Const2['default'].LAST_PAGE\n },\n fetchInfo: {\n dataTotalSize: 0\n },\n exportCSV: false,\n csvFileName: undefined\n};\n\nexports['default'] = BootstrapTable;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvQm9vdHN0cmFwVGFibGUuanM/YWEwOSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O3NDQUNKLENBQVk7Ozs7aUNBQ2YsQ0FBUzs7Ozt1Q0FDSCxDQUFlOzs7O3FDQUNqQixDQUFhOzs7O29EQUNSLEVBQTZCOzs7OzBDQUNwQyxFQUFtQjs7Ozt1Q0FDZixFQUFlOzs7OytDQUNWLEVBQXdCOztnQ0FDcEMsQ0FBUTs7OzsyQ0FDSCxFQUFtQjs7OztrQ0FDcEIsRUFBVTs7SUFFekIsY0FBYztZQUFkLGNBQWM7O0FBRVAsV0FGUCxjQUFjLENBRU4sS0FBSyxFQUFFOzs7MEJBRmYsY0FBYzs7QUFHaEIsK0JBSEUsY0FBYyw2Q0FHVixLQUFLLEVBQUU7O1NBdW9CZixhQUFhLEdBQUcsVUFBQyxDQUFDLEVBQUs7QUFDckIsWUFBSyxJQUFJLENBQ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zdC5ORVhUX1BBR0UsXG4gICAgZmlyc3RQYWdlOiBDb25zdC5GSVJTVF9QQUdFLFxuICAgIGxhc3RQYWdlOiBDb25zdC5MQVNUX1BBR0VcbiAgfSxcbiAgZmV0Y2hJbmZvOiB7XG4gICAgZGF0YVRvdGFsU2l6ZTogMCxcbiAgfSxcbiAgZXhwb3J0Q1NWOiBmYWxzZSxcbiAgY3N2RmlsZU5hbWU6IHVuZGVmaW5lZFxufTtcblxuZXhwb3J0IGRlZmF1bHQgQm9vdHN0cmFwVGFibGU7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9Cb290c3RyYXBUYWJsZS5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=");
},function(module,exports){eval("module.exports = __WEBPACK_EXTERNAL_MODULE_2__;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vZXh0ZXJuYWwge1wicm9vdFwiOlwiUmVhY3RcIixcImNvbW1vbmpzMlwiOlwicmVhY3RcIixcImNvbW1vbmpzXCI6XCJyZWFjdFwiLFwiYW1kXCI6XCJyZWFjdFwifT9jMDJmIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIiwiZmlsZSI6IjIuanMiLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cyA9IF9fV0VCUEFDS19FWFRFUk5BTF9NT0RVTEVfMl9fO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogZXh0ZXJuYWwge1wicm9vdFwiOlwiUmVhY3RcIixcImNvbW1vbmpzMlwiOlwicmVhY3RcIixcImNvbW1vbmpzXCI6XCJyZWFjdFwiLFwiYW1kXCI6XCJyZWFjdFwifVxuICoqIG1vZHVsZSBpZCA9IDJcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!\n Copyright (c) 2016 Jed Watson.\n Licensed under the MIT License (MIT), see\n http://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n 'use strict';\n\n var hasOwn = {}.hasOwnProperty;\n\n function classNames () {\n var classes = [];\n\n for (var i = 0; i < arguments.length; i++) {\n var arg = arguments[i];\n if (!arg) continue;\n\n var argType = typeof arg;\n\n if (argType === 'string' || argType === 'number') {\n classes.push(arg);\n } else if (Array.isArray(arg)) {\n classes.push(classNames.apply(null, arg));\n } else if (argType === 'object') {\n for (var key in arg) {\n if (hasOwn.call(arg, key) && arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n\n return classes.join(' ');\n }\n\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = classNames;\n } else if (true) {\n // register as 'classnames', consistent with npm package name\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n return classNames;\n }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {\n window.classNames = classNames;\n }\n}());\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L2NsYXNzbmFtZXMvaW5kZXguanM/OGU0MyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQSxnQkFBZ0I7O0FBRWhCO0FBQ0E7O0FBRUEsaUJBQWlCLHNCQUFzQjtBQUN2QztBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQSxJQUFJO0FBQ0o7QUFDQSxJQUFJO0FBQ0o7QUFDQTtBQUNBO0FBQ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GtleSBpbiBhcmcpIHtcblx0XHRcdFx0XHRpZiAoaGFzT3duLmNhbGwoYXJnLCBrZXkpICYmIGFyZ1trZXldKSB7XG5cdFx0XHRcdFx0XHRjbGFzc2VzLnB1c2goa2V5KTtcblx0XHRcdFx0XHR9XG5cdFx0XHRcdH1cblx0XHRcdH1cblx0XHR9XG5cblx0XHRyZXR1cm4gY2xhc3Nlcy5qb2luKCcgJyk7XG5cdH1cblxuXHRpZiAodHlwZW9mIG1vZHVsZSAhPT0gJ3VuZGVmaW5lZCcgJiYgbW9kdWxlLmV4cG9ydHMpIHtcblx0XHRtb2R1bGUuZXhwb3J0cyA9IGNsYXNzTmFtZXM7XG5cdH0gZWxzZSBpZiAodHlwZW9mIGRlZmluZSA9PT0gJ2Z1bmN0aW9uJyAmJiB0eXBlb2YgZGVmaW5lLmFtZCA9PT0gJ29iamVjdCcgJiYgZGVmaW5lLmFtZCkge1xuXHRcdC8vIHJlZ2lzdGVyIGFzICdjbGFzc25hbWVzJywgY29uc2lzdGVudCB3aXRoIG5wbSBwYWNrYWdlIG5hbWVcblx0XHRkZWZpbmUoJ2NsYXNzbmFtZXMnLCBbXSwgZnVuY3Rpb24gKCkge1xuXHRcdFx0cmV0dXJuIGNsYXNzTmFtZXM7XG5cdFx0fSk7XG5cdH0gZWxzZSB7XG5cdFx0d2luZG93LmNsYXNzTmFtZXMgPSBjbGFzc05hbWVzO1xuXHR9XG59KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL34vY2xhc3NuYW1lcy9pbmRleC5qc1xuICoqIG1vZHVsZSBpZCA9IDNcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports["default"] = {\n SORT_DESC: "desc",\n SORT_ASC: "asc",\n SIZE_PER_PAGE: 10,\n NEXT_PAGE: ">",\n LAST_PAGE: ">>",\n PRE_PAGE: "<",\n FIRST_PAGE: "<<",\n ROW_SELECT_BG_COLOR: "",\n ROW_SELECT_NONE: "none",\n ROW_SELECT_SINGLE: "radio",\n ROW_SELECT_MULTI: "checkbox",\n CELL_EDIT_NONE: "none",\n CELL_EDIT_CLICK: "click",\n CELL_EDIT_DBCLICK: "dbclick",\n SIZE_PER_PAGE_LIST: [10, 25, 30, 50],\n PAGINATION_SIZE: 5,\n NO_DATA_TEXT: "There is no data to display",\n SHOW_ONLY_SELECT: "Show Selected Only",\n SHOW_ALL: "Show All",\n FILTER_DELAY: 500,\n FILTER_TYPE: {\n TEXT: "TextFilter",\n REGEX: "RegexFilter",\n SELECT: "SelectFilter",\n NUMBER: "NumberFilter",\n DATE: "DateFilter",\n CUSTOM: "CustomFilter"\n }\n};\nmodule.exports = exports["default"];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvQ29uc3QuanM/MjQ1YiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztxQkFBZTtBQUNiLFdBQVMsRUFBRSxNQUFNO0FBQ2pCLFVBQVEsRUFBRSxLQUFLO0FBQ2YsZUFBYSxFQUFFLEVBQUU7QUFDakIsV0FBUyxFQUFFLEdBQUc7QUFDZCxXQUFTLEVBQUUsSUFBSTtBQUNmLFVBQVEsRUFBRSxHQUFHO0FBQ2IsWUFBVSxFQUFFLElBQUk7QUFDaEIscUJBQW1CLEVBQUUsRUFBRTtBQUN2QixpQkFBZSxFQUFFLE1BQU07QUFDdkIsbUJBQWlCLEVBQUUsT0FBTztBQUMxQixrQkFBZ0IsRUFBRSxVQUFVO0FBQzVCLGdCQUFjLEVBQUUsTUFBTTtBQUN0QixpQkFBZSxFQUFFLE9BQU87QUFDeEIsbUJBQWlCLEVBQUUsU0FBUztBQUM1QixvQkFBa0IsRUFBRSxDQUFDLEVBQUUsRUFB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6IFwiVGhlcmUgaXMgbm8gZGF0YSB0byBkaXNwbGF5XCIsXG4gIFNIT1dfT05MWV9TRUxFQ1Q6IFwiU2hvdyBTZWxlY3RlZCBPbmx5XCIsXG4gIFNIT1dfQUxMOiBcIlNob3cgQWxsXCIsXG4gIEZJTFRFUl9ERUxBWTogNTAwLFxuICBGSUxURVJfVFlQRToge1xuICAgIFRFWFQ6IFwiVGV4dEZpbHRlclwiLFxuICAgIFJFR0VYOiBcIlJlZ2V4RmlsdGVyXCIsXG4gICAgU0VMRUNUOiBcIlNlbGVjdEZpbHRlclwiLFxuICAgIE5VTUJFUjogXCJOdW1iZXJGaWx0ZXJcIixcbiAgICBEQVRFOiBcIkRhdGVGaWx0ZXJcIixcbiAgICBDVVNUT006IFwiQ3VzdG9tRmlsdGVyXCJcbiAgfVxufVxuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvQ29uc3QuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9')},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _reactDom = __webpack_require__(6);\n\nvar _reactDom2 = _interopRequireDefault(_reactDom);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _util = __webpack_require__(7);\n\nvar _util2 = _interopRequireDefault(_util);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _SelectRowHeaderColumn = __webpack_require__(8);\n\nvar _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn);\n\nvar Checkbox = (function (_React$Component) {\n _inherits(Checkbox, _React$Component);\n\n function Checkbox() {\n _classCallCheck(this, Checkbox);\n\n _get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments);\n }\n\n _createClass(Checkbox, [{\n key: 'componentDidMount',\n value: function componentDidMount() {\n this.update(this.props.checked);\n }\n }, {\n key: 'componentWillReceiveProps',\n value: function componentWillReceiveProps(props) {\n this.update(props.checked);\n }\n }, {\n key: 'update',\n value: function update(checked) {\n _reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate';\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2['default'].createElement('input', { className: 'react-bs-select-all', type: 'checkbox', checked: this.props.checked, onChange: this.props.onChange });\n }\n }]);\n\n return Checkbox;\n})(_react2['default'].Component);\n\nvar TableHeader = (function (_React$Component2) {\n _inherits(TableHeader, _React$Component2);\n\n function TableHeader(props) {\n _classCallCheck(this, TableHeader);\n\n _get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).call(this, props);\n }\n\n _createClass(TableHeader, [{\n key: 'render',\n value: function render() {\n var containerClasses = (0, _classnames2['default'])(\"react-bs-container-header\", \"table-header-wrapper\");\n var tableClasses = (0, _classnames2['default'])(\"table\", \"table-hover\", {\n \"table-bordered\": this.props.bordered,\n \"table-condensed\": this.props.condensed\n });\n var selectRowHeaderCol = this.props.hideSelectColumn ? null : this.renderSelectRowHeader();\n this._attachClearSortCaretFunc();\n\n return _react2['default'].createElement(\n 'div',\n { ref: 'container', className: containerClasses },\n _react2['default'].createElement(\n 'table',\n { className: tableClasses },\n _react2['default'].createElement(\n 'thead',\n null,\n _react2['default'].createElement(\n 'tr',\n { ref: 'header' },\n selectRowHeaderCol,\n this.props.children\n )\n )\n )\n );\n }\n }, {\n key: 'renderSelectRowHeader',\n value: function renderSelectRowHeader() {\n if (this.props.rowSelectType == _Const2['default'].ROW_SELECT_SINGLE) {\n return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null);\n } else if (this.props.rowSelectType == _Const2['default'].ROW_SELECT_MULTI) {\n return _react2['default'].createElement(\n _SelectRowHeaderColumn2['default'],\n null,\n _react2['default'].createElement(Checkbox, { onChange: this.props.onSelectAllRow, checked: this.props.isSelectAll })\n );\n } else {\n return null;\n }\n }\n }, {\n key: '_attachClearSortCaretFunc',\n value: function _attachClearSortCaretFunc() {\n var sortIndicator = this.props.sortIndicator;\n\n if (Array.isArray(this.props.children)) {\n for (var i = 0; i < this.props.children.length; i++) {\n var field = this.props.children[i].props.dataField;\n var sort = field === this.props.sortName ? this.props.sortOrder : undefined;\n this.props.children[i] = _react2['default'].cloneElement(this.props.children[i], { key: i, onSort: this.props.onSort, sort: sort, sortIndicator: sortIndicator });\n }\n } else {\n var field = this.props.children.props.dataField;\n var sort = field === this.props.sortName ? this.props.sortOrder : undefined;\n this.props.children = _react2['default'].cloneElement(this.props.children, { key: 0, onSort: this.props.onSort, sort: sort, sortIndicator: sortIndicator });\n }\n }\n }]);\n\n return TableHeader;\n})(_react2['default'].Component);\n\nTableHeader.propTypes = {\n rowSelectType: _react2['default'].PropTypes.string,\n onSort: _react2['default'].PropTypes.func,\n onSelectAllRow: _react2['default'].PropTypes.func,\n sortName: _react2['default'].PropTypes.string,\n sortOrder: _react2['default'].PropTypes.string,\n hideSelectColumn: _react2['default'].PropTypes.bool,\n bordered: _react2['default'].PropTypes.bool,\n condensed: _react2['default'].PropTypes.bool,\n isFiltered: _react2['default'].PropTypes.bool,\n isSelectAll: _react2['default'].PropTypes.oneOf([true, 'indeterminate', false]),\n sortIndicator: _react2['default'].PropTypes.bool\n};\n\nTableHeader.defaultProps = {};\nexports['default'] = TableHeader;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvVGFibGVIZWFkZXIuanM/Y2RjNyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O29DQUNKLENBQVc7Ozs7aUNBQ2QsQ0FBUzs7OztnQ0FDVixDQUFROzs7O3NDQUNKLENBQVk7Ozs7aURBQ0MsQ0FBeUI7Ozs7SUFFckQsUUFBUTtZQUFSLFFBQVE7O1dBQVIsUUFBUTswQkFBUixRQUFROzsrQkFBUixRQUFROzs7ZUFBUixRQUFROztXQUNLLDZCQUFHO0FBQUUsVUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQyxDQUFDO0tBQUU7OztXQUMvQixtQ0FBQyxLQUFLLEVBQUU7QUFBRSxVQUFJLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsQ0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oaXMucHJvcHMub25Tb3J0LCBzb3J0LCBzb3J0SW5kaWNhdG9yfSk7XG4gICAgfVxuICB9XG59XG5UYWJsZUhlYWRlci5wcm9wVHlwZXMgPSB7XG4gIHJvd1NlbGVjdFR5cGU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmcsXG4gIG9uU29ydDogUmVhY3QuUHJvcFR5cGVzLmZ1bmMsXG4gIG9uU2VsZWN0QWxsUm93OiBSZWFjdC5Qcm9wVHlwZXMuZnVuYyxcbiAgc29ydE5hbWU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmcsXG4gIHNvcnRPcmRlcjogUmVhY3QuUHJvcFR5cGVzLnN0cmluZyxcbiAgaGlkZVNlbGVjdENvbHVtbjogUmVhY3QuUHJvcFR5cGVzLmJvb2wsXG4gIGJvcmRlcmVkOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbCxcbiAgY29uZGVuc2VkOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbCxcbiAgaXNGaWx0ZXJlZDogUmVhY3QuUHJvcFR5cGVzLmJvb2wsXG4gIGlzU2VsZWN0QWxsOiBSZWFjdC5Qcm9wVHlwZXMub25lT2YoW3RydWUsICdpbmRldGVybWluYXRlJywgZmFsc2VdKSxcbiAgc29ydEluZGljYXRvcjogUmVhY3QuUHJvcFR5cGVzLmJvb2xcbn07XG5cblRhYmxlSGVhZGVyLmRlZmF1bHRQcm9wcyA9IHtcbn07XG5leHBvcnQgZGVmYXVsdCBUYWJsZUhlYWRlcjtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL1RhYmxlSGVhZGVyLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports){eval("module.exports = __WEBPACK_EXTERNAL_MODULE_6__;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vZXh0ZXJuYWwge1wicm9vdFwiOlwiUmVhY3RET01cIixcImNvbW1vbmpzMlwiOlwicmVhY3QtZG9tXCIsXCJjb21tb25qc1wiOlwicmVhY3QtZG9tXCIsXCJhbWRcIjpcInJlYWN0LWRvbVwifT9iMTFhIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIiwiZmlsZSI6IjYuanMiLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cyA9IF9fV0VCUEFDS19FWFRFUk5BTF9NT0RVTEVfNl9fO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogZXh0ZXJuYWwge1wicm9vdFwiOlwiUmVhY3RET01cIixcImNvbW1vbmpzMlwiOlwicmVhY3QtZG9tXCIsXCJjb21tb25qc1wiOlwicmVhY3QtZG9tXCIsXCJhbWRcIjpcInJlYWN0LWRvbVwifVxuICoqIG1vZHVsZSBpZCA9IDZcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nexports['default'] = {\n\n renderReactSortCaret: function renderReactSortCaret(order) {\n var orderClass = (0, _classnames2['default'])(\"order\", {\n 'dropup': order == _Const2['default'].SORT_ASC\n });\n return _react2['default'].createElement(\n 'span',\n { className: orderClass },\n _react2['default'].createElement('span', { className: 'caret', style: { margin: '0px 5px' } })\n );\n },\n\n getScrollBarWidth: function getScrollBarWidth() {\n var inner = document.createElement('p');\n inner.style.width = \"100%\";\n inner.style.height = \"200px\";\n\n var outer = document.createElement('div');\n outer.style.position = \"absolute\";\n outer.style.top = \"0px\";\n outer.style.left = \"0px\";\n outer.style.visibility = \"hidden\";\n outer.style.width = \"200px\";\n outer.style.height = \"150px\";\n outer.style.overflow = \"hidden\";\n outer.appendChild(inner);\n\n document.body.appendChild(outer);\n var w1 = inner.offsetWidth;\n outer.style.overflow = 'scroll';\n var w2 = inner.offsetWidth;\n if (w1 == w2) w2 = outer.clientWidth;\n\n document.body.removeChild(outer);\n\n return w1 - w2;\n }\n\n};\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvdXRpbC5qcz9hZDAwIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O2lDQUNQLENBQVM7Ozs7c0NBQ04sQ0FBWTs7OztxQkFDbEI7O0FBRWIsc0JBQW9CLGdDQUFDLEtBQUssRUFBQztBQUN6QixRQUFJLFVBQVUsR0FBRyw2QkFBUyxPQUFPLEVBQUU7QUFDakMsY0FBUSxFQUFFLEtBQUssSUFBSSxtQkFBTSxRQUFRO0tBQ2xDLENBQUMsQ0FBQztBQUNILFdBQ0U7O1FBQU0sU0FBUyxFQUFFLFVBQVc7TUFDMUIsMkNBQU0sU0FBUyxFQUFDLE9BQU8sRUFBQyxLQUFLLEVBQUUsRUFBQyxNQUFNLEVBQUUsU0FBUyxFQUFFLEdBQVE7S0FDdEQsQ0FDUDtHQUNIOztBQUVELG1CQUFpQiwrQkFBRTtBQUNqQixRQUFJLEtBQUssR0FBRyxRQUFRLENBQUMsYUFBYSxDQUFDLEdBQUcsQ0FBQyxDQUFDO0FBQ3hDLFNBQUssQ0FBQyxLQUFLLENBQUMsS0FBSyxHQUFHLE1BQU0sQ0FBQztBQUMzQixTQUFLLENBQUMsS0FBSyxDQUFDLE1BQU0sR0FBRyxPQUFPLENBQUM7O0FBRTdCLFFBQUks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uc3R5bGUub3ZlcmZsb3cgPSBcImhpZGRlblwiO1xuICAgIG91dGVyLmFwcGVuZENoaWxkIChpbm5lcik7XG5cbiAgICBkb2N1bWVudC5ib2R5LmFwcGVuZENoaWxkIChvdXRlcik7XG4gICAgdmFyIHcxID0gaW5uZXIub2Zmc2V0V2lkdGg7XG4gICAgb3V0ZXIuc3R5bGUub3ZlcmZsb3cgPSAnc2Nyb2xsJztcbiAgICB2YXIgdzIgPSBpbm5lci5vZmZzZXRXaWR0aDtcbiAgICBpZiAodzEgPT0gdzIpIHcyID0gb3V0ZXIuY2xpZW50V2lkdGg7XG5cbiAgICBkb2N1bWVudC5ib2R5LnJlbW92ZUNoaWxkIChvdXRlcik7XG5cbiAgICByZXR1cm4gKHcxIC0gdzIpO1xuICB9XG5cbn07XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy91dGlsLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar SelectRowHeaderColumn = (function (_React$Component) {\n _inherits(SelectRowHeaderColumn, _React$Component);\n\n function SelectRowHeaderColumn() {\n _classCallCheck(this, SelectRowHeaderColumn);\n\n _get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments);\n }\n\n _createClass(SelectRowHeaderColumn, [{\n key: 'render',\n value: function render() {\n return _react2['default'].createElement(\n 'th',\n { style: { textAlign: 'center' } },\n this.props.children\n );\n }\n }]);\n\n return SelectRowHeaderColumn;\n})(_react2['default'].Component);\n\nexports['default'] = SelectRowHeaderColumn;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvU2VsZWN0Um93SGVhZGVyQ29sdW1uLmpzP2FhYmMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztzQ0FDSixDQUFZOzs7O2lDQUNmLENBQVM7Ozs7SUFFckIscUJBQXFCO1lBQXJCLHFCQUFxQjs7V0FBckIscUJBQXFCOzBCQUFyQixxQkFBcUI7OytCQUFyQixxQkFBcUI7OztlQUFyQixxQkFBcUI7O1dBRW5CLGtCQUFFO0FBQ04sYUFDRTs7VUFBSSxLQUFLLEVBQUUsRUFBQyxTQUFTLEVBQUUsUUFBUSxFQUFFO1FBQzdCLElBQUksQ0FBQyxLQUFLLENBQUMsUUFBUTtPQUNsQixDQUNOO0tBQ0Y7OztTQVJHLHFCQUFxQjtHQUFTLG1CQUFNLFNBQVM7O3FCQVdwQyxxQkFBcUIiLCJmaWxlIjoiOC5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBSZWFjdCBmcm9tICdyZWFjdCc7XG5pbXBvcnQgY2xhc3NTZXQgZnJvbSAnY2xhc3NuYW1lcyc7XG5pbXBvcnQgQ29uc3QgZnJvbSAnLi9Db25zdCc7XG5cbmNsYXNzIFNlbGVjdFJvd0hlYWRlckNvbHVtbiBleHRlbmRzIFJlYWN0LkNvbXBvbmVudHtcblxuICByZW5kZXIoKXtcbiAgICByZXR1cm4oXG4gICAgICA8dGggc3R5bGU9e3t0ZXh0QWxpZ246ICdjZW50ZXInfX0+XG4gICAgICAgIHsgdGhpcy5wcm9wcy5jaGlsZHJlbiB9XG4gICAgICA8L3RoPlxuICAgIClcbiAgfVxufVxuXG5leHBvcnQgZGVmYXVsdCBTZWxlY3RSb3dIZWFkZXJDb2x1bW47XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9TZWxlY3RSb3dIZWFkZXJDb2x1bW4uanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _TableRow = __webpack_require__(10);\n\nvar _TableRow2 = _interopRequireDefault(_TableRow);\n\nvar _TableColumn = __webpack_require__(11);\n\nvar _TableColumn2 = _interopRequireDefault(_TableColumn);\n\nvar _TableEditColumn = __webpack_require__(12);\n\nvar _TableEditColumn2 = _interopRequireDefault(_TableEditColumn);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar isFun = function isFun(obj) {\n return obj && typeof obj === \"function\";\n};\n\nvar TableBody = (function (_React$Component) {\n _inherits(TableBody, _React$Component);\n\n function TableBody(props) {\n _classCallCheck(this, TableBody);\n\n _get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props);\n this.state = {\n currEditCell: null\n };\n this.editing = false;\n }\n\n _createClass(TableBody, [{\n key: 'render',\n value: function render() {\n var tableClasses = (0, _classnames2['default'])(\"table\", {\n 'table-striped': this.props.striped,\n 'table-bordered': this.props.bordered,\n 'table-hover': this.props.hover,\n 'table-condensed': this.props.condensed\n });\n\n var isSelectRowDefined = this._isSelectRowDefined();\n var tableHeader = this.renderTableHeader(isSelectRowDefined);\n\n var tableRows = this.props.data.map(function (data, r) {\n var tableColumns = this.props.columns.map(function (column, i) {\n var fieldValue = data[column.name];\n if (this.editing && column.name !== this.props.keyField && // Key field can't be edit\n column.editable && // column is editable? default is true, user can set it false\n this.state.currEditCell != null && this.state.currEditCell.rid == r && this.state.currEditCell.cid == i) {\n var format = column.format ? function (value) {\n return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, '');\n } : false;\n\n return _react2['default'].createElement(\n _TableEditColumn2['default'],\n { completeEdit: this.handleCompleteEditCell.bind(this),\n //add by bluespring for column editor customize\n editable: isFun(column.editable) ? column.editable(fieldValue, data, r, i) : column.editable,\n format: column.format ? format : false,\n key: i,\n blurToSave: this.props.cellEdit.blurToSave,\n rowIndex: r,\n colIndex: i },\n fieldValue\n );\n } else {\n //add by bluespring for className customize\n var tdClassName = isFun(column.className) ? column.className(fieldValue, data, r, i) : column.className;\n\n if (typeof column.format !== \"undefined\") {\n var formattedValue = column.format(fieldValue, data, column.formatExtraData);\n if (!_react2['default'].isValidElement(formattedValue)) {\n formattedValue = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } });\n }\n return _react2['default'].createElement(\n _TableColumn2['default'],\n { dataAlign: column.align,\n key: i,\n className: tdClassName,\n cellEdit: this.props.cellEdit,\n hidden: column.hidden,\n onEdit: this.handleEditCell.bind(this),\n width: column.width },\n formattedValue\n );\n } else {\n return _react2['default'].createElement(\n _TableColumn2['default'],\n { dataAlign: column.align,\n key: i,\n className: tdClassName,\n cellEdit: this.props.cellEdit,\n hidden: column.hidden,\n onEdit: this.handleEditCell.bind(this),\n width: column.width },\n fieldValue\n );\n }\n }\n }, this);\n var selected = this.props.selectedRowKeys.indexOf(data[this.props.keyField]) != -1;\n var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected) : null;\n //add by bluespring for className customize\n var trClassName = isFun(this.props.trClassName) ? this.props.trClassName(data, r) : this.props.trClassName;\n return _react2['default'].createElement(\n _TableRow2['default'],\n { isSelected: selected, key: r, className: trClassName,\n selectRow: isSelectRowDefined ? this.props.selectRow : undefined,\n enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE,\n onRowClick: this.handleRowClick.bind(this),\n onRowMouseOver: this.handleRowMouseOver.bind(this),\n onRowMouseOut: this.handleRowMouseOut.bind(this),\n onSelectRow: this.handleSelectRow.bind(this) },\n selectRowColumn,\n tableColumns\n );\n }, this);\n\n if (tableRows.length === 0) {\n tableRows.push(_react2['default'].createElement(\n _TableRow2['default'],\n { key: '##table-empty##' },\n _react2['default'].createElement(\n 'td',\n { colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0),\n className: 'react-bs-table-no-data' },\n this.props.noDataText || _Const2['default'].NO_DATA_TEXT\n )\n ));\n }\n\n this.editing = false;\n\n return _react2['default'].createElement(\n 'div',\n { ref: 'container', className: 'react-bs-container-body', style: this.props.style },\n _react2['default'].createElement(\n 'table',\n { className: tableClasses },\n tableHeader,\n _react2['default'].createElement(\n 'tbody',\n { ref: 'tbody' },\n tableRows\n )\n )\n );\n }\n }, {\n key: 'renderTableHeader',\n value: function renderTableHeader(isSelectRowDefined) {\n var selectRowHeader = null;\n\n if (isSelectRowDefined) {\n var style = {\n width: 30,\n minWidth: 30\n };\n selectRowHeader = this.props.selectRow.hideSelectColumn ? null : _react2['default'].createElement('col', { style: style, key: -1 });\n }\n var theader = this.props.columns.map(function (column, i) {\n var width = column.width == null ? column.width : parseInt(column.width);\n var style = {\n display: column.hidden ? \"none\" : null,\n width: width,\n minWidth: width\n /** add min-wdth to fix user assign column width not eq offsetWidth in large column table **/\n };\n return _react2['default'].createElement('col', { style: style, key: i, className: column.className });\n });\n\n return _react2['default'].createElement(\n 'colgroup',\n { ref: 'header' },\n selectRowHeader,\n theader\n );\n }\n }, {\n key: 'handleRowMouseOut',\n value: function handleRowMouseOut(rowIndex) {\n var targetRow = this.props.data[rowIndex];\n this.props.onRowMouseOut(targetRow);\n }\n }, {\n key: 'handleRowMouseOver',\n value: function handleRowMouseOver(rowIndex) {\n var targetRow = this.props.data[rowIndex];\n this.props.onRowMouseOver(targetRow);\n }\n }, {\n key: 'handleRowClick',\n value: function handleRowClick(rowIndex) {\n var key, selectedRow;\n this.props.data.forEach(function (row, i) {\n if (i == rowIndex - 1) {\n key = row[this.props.keyField];\n selectedRow = row;\n }\n }, this);\n this.props.onRowClick(selectedRow);\n }\n }, {\n key: 'handleSelectRow',\n value: function handleSelectRow(rowIndex, isSelected) {\n var key, selectedRow;\n this.props.data.forEach(function (row, i) {\n if (i == rowIndex - 1) {\n key = row[this.props.keyField];\n selectedRow = row;\n return false;\n }\n }, this);\n this.props.onSelectRow(selectedRow, isSelected);\n }\n }, {\n key: 'handleSelectRowColumChange',\n value: function handleSelectRowColumChange(e) {\n if (!this.props.selectRow.clickToSelect || !this.props.selectRow.clickToSelectAndEditCell) {\n this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked);\n }\n }\n }, {\n key: 'handleEditCell',\n value: function handleEditCell(rowIndex, columnIndex) {\n this.editing = true;\n if (this._isSelectRowDefined()) {\n columnIndex--;\n if (this.props.selectRow.hideSelectColumn) columnIndex++;\n }\n rowIndex--;\n var stateObj = {\n currEditCell: {\n rid: rowIndex,\n cid: columnIndex\n }\n };\n\n if (this.props.selectRow.clickToSelectAndEditCell) {\n this.handleSelectRow(rowIndex + 1, true);\n }\n this.setState(stateObj);\n }\n }, {\n key: 'cancelEdit',\n value: function cancelEdit() {\n var currEditCell = this.state.currEditCell;\n if (currEditCell) {\n this.handleCompleteEditCell(null, currEditCell.rid, currEditCell.cid);\n }\n }\n }, {\n key: 'handleCompleteEditCell',\n value: function handleCompleteEditCell(newVal, rowIndex, columnIndex) {\n this.setState({ currEditCell: null });\n if (null != newVal) this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex);\n }\n }, {\n key: 'renderSelectRowColumn',\n value: function renderSelectRowColumn(selected) {\n if (this.props.selectRow.mode == _Const2['default'].ROW_SELECT_SINGLE) {\n return _react2['default'].createElement(\n _TableColumn2['default'],\n { dataAlign: 'center' },\n _react2['default'].createElement('input', { type: 'radio', checked: selected, onChange: this.handleSelectRowColumChange.bind(this) })\n );\n } else {\n return _react2['default'].createElement(\n _TableColumn2['default'],\n { dataAlign: 'center' },\n _react2['default'].createElement('input', { type: 'checkbox', checked: selected, onChange: this.handleSelectRowColumChange.bind(this) })\n );\n }\n }\n }, {\n key: '_isSelectRowDefined',\n value: function _isSelectRowDefined() {\n return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI;\n }\n }]);\n\n return TableBody;\n})(_react2['default'].Component);\n\nTableBody.propTypes = {\n // height: React.PropTypes.string,\n data: _react2['default'].PropTypes.array,\n columns: _react2['default'].PropTypes.array,\n striped: _react2['default'].PropTypes.bool,\n bordered: _react2['default'].PropTypes.bool,\n hover: _react2['default'].PropTypes.bool,\n condensed: _react2['default'].PropTypes.bool,\n keyField: _react2['default'].PropTypes.string,\n selectedRowKeys: _react2['default'].PropTypes.array,\n onRowClick: _react2['default'].PropTypes.func,\n onSelectRow: _react2['default'].PropTypes.func,\n noDataText: _react2['default'].PropTypes.string,\n style: _react2['default'].PropTypes.object\n};\nexports['default'] = TableBody;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJ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2x1bW4gZGF0YUFsaWduPXtjb2x1bW4uYWxpZ259XG4gICAgICAgICAgICAgICAgICAgICAgICAgICBrZXk9e2l9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICBjbGFzc05hbWU9e3RkQ2xhc3NOYW1lfVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgY2VsbEVkaXQ9e3RoaXMucHJvcHMuY2VsbEVkaXR9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICBoaWRkZW49e2NvbHVtbi5oaWRkZW59XG4gICAgICAgICAgICAgICAgICAgICAgICAgICBvbkVkaXQ9e3RoaXMuaGFuZGxlRWRpdENlbGwuYmluZCh0aGlzKX1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgIHdpZHRoPXtjb2x1bW4ud2lkdGh9PlxuICAgICAgICAgICAgICAgIHtmb3JtYXR0ZWRWYWx1ZX1cbiAgICAgICAgICAgICAgPC9UYWJsZUNvbHVtbj5cbiAgICAgICAgICAgIClcbiAgICAgICAgICB9IGVsc2V7XG4gICAgICAgICAgICByZXR1cm4oXG4gICAgICAgICAgICAgIDxUYWJsZUNvbHVtbiBkYXRhQWxpZ249e2NvbHVtbi5hbGlnbn1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgIGtleT17aX1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgIGNsYXNzTmFtZT17dGRDbGFzc05hbWV9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICBjZWxsRWRpdD17dGhpcy5wcm9wcy5jZWxsRWRpdH1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgIGhpZGRlbj17Y29sdW1uLmhpZGRlbn1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgIG9uRWRpdD17dGhpcy5oYW5kbGVFZGl0Q2VsbC5iaW5kKHRoaXMpfVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgd2lkdGg9e2NvbHVtbi53aWR0aH0+XG4gICAgICAgICAgICAgICAge2ZpZWxkVmFsdWV9XG4gICAgICAgICAgICAgI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IC4vc3JjL1RhYmxlQm9keS5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar TableRow = (function (_React$Component) {\n _inherits(TableRow, _React$Component);\n\n function TableRow(props) {\n _classCallCheck(this, TableRow);\n\n _get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props);\n this.clickNum = 0;\n }\n\n _createClass(TableRow, [{\n key: 'rowClick',\n value: function rowClick(e) {\n var _this = this;\n\n if (e.target.tagName !== \"INPUT\" && e.target.tagName !== \"SELECT\" && e.target.tagName !== \"TEXTAREA\") {\n (function () {\n var rowIndex = e.currentTarget.rowIndex + 1;\n if (_this.props.selectRow) {\n if (_this.props.selectRow.clickToSelect) {\n _this.props.onSelectRow(rowIndex, !_this.props.isSelected);\n } else if (_this.props.selectRow.clickToSelectAndEditCell) {\n _this.clickNum++;\n /** if clickToSelectAndEditCell is enabled,\n * there should be a delay to prevent a selection changed when\n * user dblick to edit cell on same row but different cell\n **/\n setTimeout(function () {\n if (_this.clickNum === 1) {\n _this.props.onSelectRow(rowIndex, !_this.props.isSelected);\n }\n _this.clickNum = 0;\n }, 200);\n }\n }\n if (_this.props.onRowClick) _this.props.onRowClick(rowIndex);\n })();\n }\n }\n }, {\n key: 'rowMouseOut',\n value: function rowMouseOut(e) {\n if (this.props.onRowMouseOut) {\n this.props.onRowMouseOut(e.currentTarget.rowIndex);\n }\n }\n }, {\n key: 'rowMouseOver',\n value: function rowMouseOver(e) {\n if (this.props.onRowMouseOver) {\n this.props.onRowMouseOver(e.currentTarget.rowIndex);\n }\n }\n }, {\n key: 'render',\n value: function render() {\n this.clickNum = 0;\n var trCss = {\n style: {\n backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null\n },\n className: (this.props.isSelected && this.props.selectRow.className ? this.props.selectRow.className : '') + (this.props.className || '')\n };\n\n if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) {\n return _react2['default'].createElement(\n 'tr',\n _extends({}, trCss, {\n onMouseOver: this.rowMouseOver.bind(this),\n onMouseOut: this.rowMouseOut.bind(this),\n onClick: this.rowClick.bind(this) }),\n this.props.children\n );\n } else {\n return _react2['default'].createElement(\n 'tr',\n trCss,\n this.props.children\n );\n }\n }\n }]);\n\n return TableRow;\n})(_react2['default'].Component);\n\nTableRow.propTypes = {\n isSelected: _react2['default'].PropTypes.bool,\n enableCellEdit: _react2['default'].PropTypes.bool,\n onRowClick: _react2['default'].PropTypes.func,\n onSelectRow: _react2['default'].PropTypes.func,\n onRowMouseOut: _react2['default'].PropTypes.func,\n onRowMouseOver: _react2['default'].PropTypes.func\n};\nTableRow.defaultProps = {\n onRowClick: undefined\n};\nexports['default'] = TableRow;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvVGFibGVSb3cuanM/MDNjYyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7aUNBQWtCLENBQU87Ozs7aUNBQ1AsQ0FBUzs7OztJQUVyQixRQUFRO1lBQVIsUUFBUTs7QUFFRCxXQUZQLFFBQVEsQ0FFQSxLQUFLLEVBQUU7MEJBRmYsUUFBUTs7QUFHViwrQkFIRSxRQUFRLDZDQUdKLEtBQUssRUFBRTtBQUNiLFFBQUksQ0FBQyxRQUFRLEdBQUcsQ0FBQyxDQUFDO0dBQ25COztlQUxHLFFBQVE7O1dBT0osa0JBQUMsQ0FBQyxFQUFDOzs7QUFDVCxVQUFHLENBQUMsQ0FBQyxNQUFNLENBQUMsT0FBTyxLQUFLLE9BQU8sSUFDM0IsQ0FBQyxDQUFDLE1BQU0sQ0FBQyxPQUFPLEtBQUssUUFBUSxJQUM3QixDQUFDLENBQUMsTUFBTSxDQUFDLE9BQU8sS0FBSyxVQUFVLEVBQUU7O0FBQ25DLGNBQU0sUUFBUSxHQUFHLENBQUMsQ0FBQyxhQUF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AhPT0gXCJTRUxFQ1RcIiAmJlxuICAgICAgICBlLnRhcmdldC50YWdOYW1lICE9PSBcIlRFWFRBUkVBXCIpIHtcbiAgICAgIGNvbnN0IHJvd0luZGV4ID0gZS5jdXJyZW50VGFyZ2V0LnJvd0luZGV4ICsgMTtcbiAgICAgIGlmICh0aGlzLnByb3BzLnNlbGVjdFJvdykge1xuICAgICAgICAgIGlmICh0aGlzLnByb3BzLnNlbGVjdFJvdy5jbGlja1RvU2VsZWN0KSB7XG4gICAgICAgICAgICB0aGlzLnByb3BzLm9uU2VsZWN0Um93KHJvd0luZGV4LCAhdGhpcy5wcm9wcy5pc1NlbGVjdGVkKTtcbiAgICAgICAgICB9IGVsc2UgaWYgKHRoaXMucHJvcHMuc2VsZWN0Um93LmNsaWNrVG9TZWxlY3RBbmRFZGl0Q2VsbCkge1xuICAgICAgICAgICAgdGhpcy5jbGlja051bSsrO1xuICAgICAgICAgICAgLyoqIGlmIGNsaWNrVG9TZWxlY3RBbmRFZGl0Q2VsbCBpcyBlbmFibGVkLFxuICAgICAgICAgICAgICogIHRoZXJlIHNob3VsZCBiZSBhIGRlbGF5IHRvIHByZXZlbnQgYSBzZWxlY3Rpb24gY2hhbmdlZCB3aGVuXG4gICAgICAgICAgICAgKiAgdXNlciBkYmxpY2sgdG8gZWRpdCBjZWxsIG9uIHNhbWUgcm93IGJ1dCBkaWZmZXJlbnQgY2VsbFxuICAgICAgICAgICAgKiovXG4gICAgICAgICAgICBzZXRUaW1lb3V0KCgpID0+IHtcbiAgICAgICAgICAgICAgaWYodGhpcy5jbGlja051bSA9PT0gMSkge1xuICAgICAgICAgICAgICAgIHRoaXMucHJvcHMub25TZWxlY3RSb3cocm93SW5kZXgsICF0aGlzLnByb3BzLmlzU2VsZWN0ZWQpO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIHRoaXMuY2xpY2tOdW0gPSAwO1xuICAgICAgICAgICAgfSwgMjAwKTtcbiAgICAgICAgICB9XG4gICAgICB9X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cbiAgICAgICAgPHRyIHsuLi50ckNzc31cbiAgICAgICAgICAgIG9uTW91c2VPdmVyPXt0aGlzLnJvd01vdXNlT3Zlci5iaW5kKHRoaXMpfVxuICAgICAgICAgICAgb25Nb3VzZU91dD17dGhpcy5yb3dNb3VzZU91dC5iaW5kKHRoaXMpfVxuICAgICAgICAgICAgb25DbGljaz17dGhpcy5yb3dDbGljay5iaW5kKHRoaXMpfT57dGhpcy5wcm9wcy5jaGlsZHJlbn08L3RyPlxuICAgICAgKVxuICAgIH1lbHNle1xuICAgICAgcmV0dXJuKFxuICAgICAgICA8dHIgey4uLnRyQ3NzfT57dGhpcy5wcm9wcy5jaGlsZHJlbn08L3RyPlxuICAgICAgKVxuICAgIH1cbiAgfVxufVxuVGFibGVSb3cucHJvcFR5cGVzID0ge1xuICBpc1NlbGVjdGVkOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbCxcbiAgZW5hYmxlQ2VsbEVkaXQ6IFJlYWN0LlByb3BUeXBlcy5ib29sLFxuICBvblJvd0NsaWNrOiBSZWFjdC5Qcm9wVHlwZXMuZnVuYyxcbiAgb25TZWxlY3RSb3c6IFJlYWN0LlByb3BUeXBlcy5mdW5jLFxuICBvblJvd01vdXNlT3V0OiBSZWFjdC5Qcm9wVHlwZXMuZnVuYyxcbiAgb25Sb3dNb3VzZU92ZXI6IFJlYWN0LlByb3BUeXBlcy5mdW5jXG59O1xuVGFibGVSb3cuZGVmYXVsdFByb3BzID0ge1xuICBvblJvd0NsaWNrOiB1bmRlZmluZWRcbn1cbmV4cG9ydCBkZWZhdWx0IFRhYmxlUm93O1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvVGFibGVSb3cuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar TableColumn = (function (_React$Component) {\n _inherits(TableColumn, _React$Component);\n\n function TableColumn(props) {\n _classCallCheck(this, TableColumn);\n\n _get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props);\n }\n\n _createClass(TableColumn, [{\n key: 'shouldComponentUpdate',\n value: function shouldComponentUpdate(nextProps, nextState) {\n var children = this.props.children;\n\n var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString();\n\n if (shouldUpdated) {\n return shouldUpdated;\n }\n\n if (typeof children === 'object' && children !== null && children.props !== null) {\n if (children.props.type === 'checkbox' || children.props.type === 'radio') {\n shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked;\n } else {\n shouldUpdated = true;\n }\n } else {\n shouldUpdated = shouldUpdated || children !== nextProps.children;\n }\n\n if (shouldUpdated) {\n return shouldUpdated;\n }\n\n if (!(this.props.cellEdit && nextProps.cellEdit)) {\n return false;\n } else {\n return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode;\n }\n }\n }, {\n key: 'handleCellEdit',\n value: function handleCellEdit(e) {\n if (this.props.cellEdit.mode == _Const2['default'].CELL_EDIT_DBCLICK) {\n if (document.selection && document.selection.empty) {\n document.selection.empty();\n } else if (window.getSelection) {\n var sel = window.getSelection();\n sel.removeAllRanges();\n }\n }\n this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex);\n }\n }, {\n key: 'render',\n value: function render() {\n var tdStyle = {\n textAlign: this.props.dataAlign,\n display: this.props.hidden ? \"none\" : null\n };\n\n var opts = {};\n if (this.props.cellEdit) {\n if (this.props.cellEdit.mode == _Const2['default'].CELL_EDIT_CLICK) {\n opts.onClick = this.handleCellEdit.bind(this);\n } else if (this.props.cellEdit.mode == _Const2['default'].CELL_EDIT_DBCLICK) {\n opts.onDoubleClick = this.handleCellEdit.bind(this);\n }\n }\n return _react2['default'].createElement(\n 'td',\n _extends({ style: tdStyle, className: this.props.className }, opts),\n this.props.children\n );\n }\n }]);\n\n return TableColumn;\n})(_react2['default'].Component);\n\nTableColumn.propTypes = {\n dataAlign: _react2['default'].PropTypes.string,\n hidden: _react2['default'].PropTypes.bool,\n className: _react2['default'].PropTypes.string\n};\n\nTableColumn.defaultProps = {\n dataAlign: \"left\",\n hidden: false,\n className: \"\"\n};\nexports['default'] = TableColumn;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvVGFibGVDb2x1bW4uanM/YjNmMSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7aUNBQWtCLENBQU87Ozs7aUNBQ1AsQ0FBUzs7OztJQUVyQixXQUFXO1lBQVgsV0FBVzs7QUFFSixXQUZQLFdBQVcsQ0FFSCxLQUFLLEVBQUU7MEJBRmYsV0FBVzs7QUFHYiwrQkFIRSxXQUFXLDZDQUdQLEtBQUssRUFBRTtHQUNkOztlQUpHLFdBQVc7O1dBTU0sK0JBQUMsU0FBUyxFQUFFLFNBQVMsRUFBRTtVQUNsQyxRQUFRLEdBQUssSUFBSSxDQUFDLEtBQUssQ0FBdkIsUUFBUTs7QUFDaEIsVUFBSSxhQUFhLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxLQUFLLEtBQUssU0FBUyxDQUFDLEtBQUssSUFDbkQsSUFBSSxDQUFDLEtBQUssQ0FBQyxTQUFTLEtBQUssU0FBUyxDQUFDLFNBQVMsSUFDNUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxNQUFNLEtBQUssU0FBUyxDQUFDLE1BQU0sSUFDdEMsSUFBSSxDQUFDLEtBQUssQ0FBQyxTQUFTLEtBQUssU0FBUyxDQUFDLFNBQVMsSUFDNUMsT0FBTyxRQUFRLEtBQUssT0FBTyxTQUFTLENBQUMsUUFBUSxJQUM3QyxDQUFDLEVBQUUsR0FBQyxJQUFJLENBQUMsS0FBSyxDQUF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59O1xuXG5UYWJsZUNvbHVtbi5kZWZhdWx0UHJvcHMgPSB7XG4gIGRhdGFBbGlnbjogXCJsZWZ0XCIsXG4gIGhpZGRlbjogZmFsc2UsXG4gIGNsYXNzTmFtZTpcIlwiXG59XG5leHBvcnQgZGVmYXVsdCBUYWJsZUNvbHVtbjtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL1RhYmxlQ29sdW1uLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _Editor = __webpack_require__(13);\n\nvar _Editor2 = _interopRequireDefault(_Editor);\n\nvar _NotificationJs = __webpack_require__(14);\n\nvar _NotificationJs2 = _interopRequireDefault(_NotificationJs);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar TableEditColumn = (function (_React$Component) {\n _inherits(TableEditColumn, _React$Component);\n\n function TableEditColumn(props) {\n _classCallCheck(this, TableEditColumn);\n\n _get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props);\n this.timeouteClear = 0;\n this.state = {\n shakeEditor: false\n };\n }\n\n _createClass(TableEditColumn, [{\n key: 'handleKeyPress',\n value: function handleKeyPress(e) {\n if (e.keyCode == 13) {\n //Pressed ENTER\n var value = e.currentTarget.type == 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value;\n\n if (!this.validator(value)) {\n return;\n }\n this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);\n } else if (e.keyCode == 27) {\n this.props.completeEdit(null, this.props.rowIndex, this.props.colIndex);\n }\n }\n }, {\n key: 'handleBlur',\n value: function handleBlur(e) {\n if (this.props.blurToSave) {\n var value = e.currentTarget.type == 'checkbox' ? this._getCheckBoxValue(e) : e.currentTarget.value;\n if (!this.validator(value)) {\n return;\n }\n this.props.completeEdit(value, this.props.rowIndex, this.props.colIndex);\n }\n }\n }, {\n key: 'validator',\n value: function validator(value) {\n var ts = this;\n if (ts.props.editable.validator) {\n var valid = ts.props.editable.validator(value);\n if (valid !== true) {\n ts.refs.notifier.notice('error', valid, \"Pressed ESC can cancel\");\n var input = ts.refs.inputRef;\n //animate input\n ts.clearTimeout();\n ts.setState({ shakeEditor: true });\n ts.timeouteClear = setTimeout(function () {\n ts.setState({ shakeEditor: false });\n }, 300);\n input.focus();\n return false;\n }\n }\n return true;\n }\n }, {\n key: 'clearTimeout',\n value: (function (_clearTimeout) {\n function clearTimeout() {\n return _clearTimeout.apply(this, arguments);\n }\n\n clearTimeout.toString = function () {\n return _clearTimeout.toString();\n };\n\n return clearTimeout;\n })(function () {\n if (this.timeouteClear != 0) {\n clearTimeout(this.timeouteClear);\n this.timeouteClear = 0;\n }\n })\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n var input = this.refs.inputRef;\n // input.value = this.props.children||'';\n input.focus();\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n this.clearTimeout();\n }\n }, {\n key: 'render',\n value: function render() {\n var editable = this.props.editable,\n format = this.props.format,\n attr = {\n ref: \"inputRef\",\n onKeyDown: this.handleKeyPress.bind(this),\n onBlur: this.handleBlur.bind(this)\n };\n //put placeholder if exist\n editable.placeholder && (attr.placeholder = editable.placeholder);\n\n var editorClass = (0, _classnames2['default'])({ 'animated': this.state.shakeEditor, 'shake': this.state.shakeEditor });\n return _react2['default'].createElement(\n 'td',\n { ref: 'td', style: { position: 'relative' } },\n (0, _Editor2['default'])(editable, attr, format, editorClass, this.props.children || ''),\n _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' })\n );\n }\n }, {\n key: '_getCheckBoxValue',\n value: function _getCheckBoxValue(e) {\n var value = '';\n var values = e.currentTarget.value.split(':');\n value = e.currentTarget.checked ? values[0] : values[1];\n return value;\n }\n }]);\n\n return TableEditColumn;\n})(_react2['default'].Component);\n\nTableEditColumn.propTypes = {\n completeEdit: _react2['default'].PropTypes.func,\n rowIndex: _react2['default'].PropTypes.number,\n colIndex: _react2['default'].PropTypes.number,\n blurToSave: _react2['default'].PropTypes.bool\n};\n\nexports['default'] = TableEditColumn;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2V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biAgICB2YWx1ZSA9IGUuY3VycmVudFRhcmdldC5jaGVja2VkP3ZhbHVlc1swXTp2YWx1ZXNbMV07XG4gICAgcmV0dXJuIHZhbHVlO1xuICB9XG5cbn1cblRhYmxlRWRpdENvbHVtbi5wcm9wVHlwZXMgPSB7XG4gIGNvbXBsZXRlRWRpdDogUmVhY3QuUHJvcFR5cGVzLmZ1bmMsXG4gIHJvd0luZGV4OiBSZWFjdC5Qcm9wVHlwZXMubnVtYmVyLFxuICBjb2xJbmRleDogUmVhY3QuUHJvcFR5cGVzLm51bWJlcixcbiAgYmx1clRvU2F2ZTogUmVhY3QuUHJvcFR5cGVzLmJvb2xcbn07XG5cblxuZXhwb3J0IGRlZmF1bHQgVGFibGVFZGl0Q29sdW1uO1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvVGFibGVFZGl0Q29sdW1uLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar Editor = function Editor(editable, attr, format, editorClass, defaultValue) {\n\n if (editable === true || typeof editable === \"string\") {\n //simple declare\n var type = editable === true ? 'text' : editable;\n return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,\n className: (editorClass || \"\") + \" form-control editor edit-text\" }));\n } else if (!editable) {\n var type = editable === true ? 'text' : editable;\n return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, disabled: 'disabled',\n className: (editorClass || \"\") + \" form-control editor edit-text\" }));\n } else if (editable.type) {\n //standard declare\n //put style if exist\n editable.style && (attr.style = editable.style);\n\n //put class if exist\n attr.className = (editorClass || \"\") + \" form-control editor edit-\" + editable.type + (editable.className ? \" \" + editable.className : \"\");\n\n if (editable.type === 'select') {\n //process select input\n var options = [],\n values = editable.options.values;\n if (Array.isArray(values)) {\n //only can use arrray data for options\n var rowValue;\n options = values.map(function (d, i) {\n rowValue = format ? format(d) : d;\n return _react2['default'].createElement(\n 'option',\n { key: 'option' + i, value: d },\n rowValue\n );\n });\n }\n return _react2['default'].createElement(\n 'select',\n _extends({}, attr, { defaultValue: defaultValue }),\n options\n );\n } else if (editable.type === 'textarea') {\n //process textarea input\n //put other if exist\n editable.cols && (attr.cols = editable.cols);\n editable.rows && (attr.rows = editable.rows);\n var keyUpHandler = attr.onKeyDown,\n saveBtn = null;\n if (keyUpHandler) {\n attr.onKeyDown = function (e) {\n if (e.keyCode != 13) {\n //not Pressed ENTER\n keyUpHandler(e);\n }\n };\n saveBtn = _react2['default'].createElement(\n 'butto',\n { className: 'btn btn-info btn-xs textarea-save-btn', onClick: keyUpHandler },\n 'save'\n );\n }\n\n return _react2['default'].createElement(\n 'div',\n null,\n _react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })),\n saveBtn\n );\n } else if (editable.type === 'checkbox') {\n var _values = 'true:false';\n if (editable.options && editable.options.values) {\n // values = editable.options.values.split(':');\n _values = editable.options.values;\n }\n attr.className = attr.className.replace('form-control', '');\n attr.className += ' checkbox pull-right';\n\n var checked = defaultValue && defaultValue.toString() == _values.split(':')[0] ? true : false;\n\n return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox', value: _values, defaultChecked: checked }));\n } else {\n //process other input type. as password,url,email...\n return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue }));\n }\n }\n //default return for other case of editable\n return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', className: (editorClass || \"\") + \" form-control editor edit-text\" }));\n};\n\nexports['default'] = Editor;\nmodule.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ZXM9ZWRpdGFibGUub3B0aW9ucy52YWx1ZXM7XG4gICAgICAgICAgICBpZihBcnJheS5pc0FycmF5KHZhbHVlcykpey8vb25seSBjYW4gdXNlIGFycnJheSBkYXRhIGZvciBvcHRpb25zXG4gICAgICAgICAgICAgICAgdmFyIHJvd1ZhbHVlO1xuICAgICAgICAgICAgICAgIG9wdGlvbnM9dmFsdWVzLm1hcChmdW5jdGlvbihkLGkpe1xuICAgICAgICAgICAgICAgICAgICByb3dWYWx1ZT1mb3JtYXQ/Zm9ybWF0KGQpOmQ7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybihcbiAgICAgICAgICAgICAgICAgICAgICAgIDxvcHRpb24ga2V5PXsnb3B0aW9uJytpfSB2YWx1ZT17ZH0+e3Jvd1ZhbHVlfTwvb3B0aW9uPlxuICAgICAgICAgICAgICAgICAgICApXG4gICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICByZXR1cm4oXG4gICAgICAgICAgICAgICAgPHNlbGVjdCB7Li4uYXR0cn0gZGVmYXVsdFZhbHVlPXtkZWZhdWx0VmFsdWV9PntvcHRpb25zfTwvc2VsZWN0PlxuICAgICAgICAgICAgKTtcbiAgICAgICAgfSBlbHNlIGlmKGVkaXRhYmxlLnR5cGUgPT09ICd0ZXh0YXJlYScpey8vcHJvY2VzcyB0ZXh0YXJlYSBpbnB1dFxuICAgICAgICAgICAgLy9wdXQgIG90aGVyIGlmIGV4aXN0XG4gICAgICAgICAgICBlZGl0YWJsZS5jb2xzJiYoYXR0ci5jb2xzPWVkaXRhYmxlLmNvbHMpO1xuICAgICAgICAgICAgZWRpdGFibGUucm93cyYmKGF0dHIucm93cz1lZGl0YWJsZS5yb3dzKTtcbiAgICAgICAgICAgIHZhciBrZXlVcEhhbmRsZXI9YXR0ci5vbktleURvd24sc2F2ZUJ0bj1udWxsO1xuICAgICAgICAgICAgaWYoa2V5VXBIYW5kbGVyKXtcbiAgICAgICAgICAgICAgICBhdHRyLm9uS2V5RG93bj1mdW5jdGlvbihlKXtcbiAgICAgICAgICAgICAgICAgICAgaWYgKGUua2V5Q29kZSAhPSAxMykgeyAvL25vdCBQcmVzc2VkIEVOVEVSXG4gICAgICAgICAgICAgICAgICAgICAgICBrZXlVcEhhbmRsZXIoZSk7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB9O1xuICAgICAgICAgICAgICAgIHNhdmVCdG49PGJ1dHRvIGNsYXNzTmFtZT1cImJ0biBidG4taW5mbyBidG4teHMgdGV4dGFyZWEtc2F2ZS1idG5cIiBvbkNsaWNrPXtrZXlVcEhhbmRsZXJ9PnNhdmU8L2J1dHRvPlxuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICByZXR1cm4oXG4gICAgICAgICAgICAgICAgPGRpdj5cbiAgICAgICAgICAgICAgICAgICAgPHRleHRhcmVhIHsuLi5hdHRyfSBkZWZhdWx0VmFsdWU9e2RlZmF1bHRWYWx1ZX0+PC90ZXh0YXJlYT5cbiAgICAgICAgICAgICAgICAgICAge3NhdmVCdG59XG4gICAgICAgICAgICAgICAgPC9kaXY+XG5cbiAgICAgICAgICAgICk7XG4gICAgICAgIH0gZWxzZSBpZihlZGl0YWJsZS50eXBlID09PSAnY2hlY2tib3gnKXtcbiAgICAgICAgICBsZXQgdmFsdWVzID0gJ3RydWU6ZmFsc2UnO1xuICAgICAgICAgIGlmKGVkaXRhYmxlLm9wdGlvbnMgJiYgZWRpdGFibGUub3B0aW9ucy52YWx1ZXMpe1xuICAgICAgICAgICAgLy8gdmFsdWVzID0gZWRpdGFibGUub3B0aW9ucy52YWx1ZXMuc3BsaXQoJzonKTtcbiAgICAgICAgICAgIHZhbHVlcyA9IGVkaXRhYmxlLm9wdGlvbnMudmFsdWVzO1xuICAgICAgICAgIH1cbiAgICAgICAgICBhdHRyLmNsYXNzTmFtZSA9IGF0dHIuY2xhc3NOYW1lLnJlcGxhY2UoJ2Zvcm0tY29udHJvbCcsJycpO1xuICAgICAgICAgIGF0dHIuY2xhc3NOYW1lICs9ICcgY2hlY2tib3ggcHVsbC1yaWdodCc7XG5cbiAgICAgICAgICBsZXQgY2hlY2tlZCA9IGRlZmF1bHRWYWx1ZSAmJiBkZWZhdWx0VmFsdWUudG9TdHJpbmcoKSA9PSB2YWx1ZXMuc3BsaXQoJzonKVswXT90cnVlOmZhbHNlO1xuXG4gICAgICAgICAgcmV0dXJuIChcbiAgICAgICAgICAgIDxpbnB1dCB7Li4uYXR0cn0gdHlwZT0nY2hlY2tib3gnIHZhbHVlPXt2YWx1ZXN9IGRlZmF1bHRDaGVja2VkPXtjaGVja2VkfS8+XG4gICAgICAgICAgKTtcbiAgICAgICAgfSBlbHNley8vcHJvY2VzcyBvdGhlciBpbnB1dCB0eXBlLiBhcyBwYXNzd29yZCx1cmwsZW1haWwuLi5cbiAgICAgICAgICAgIHJldHVybihcbiAgICAgICAgICAgICAgICA8aW5wdXQgey4uLmF0dHJ9IHR5cGU9e3R5cGV9IGRlZmF1bHRWYWx1ZT17ZGVmYXVsdFZhbHVlfS8+XG4gICAgICAgICAgICApXG4gICAgICAgIH1cbiAgICB9XG4gICAgLy9kZWZhdWx0IHJldHVybiBmb3Igb3RoZXIgY2FzZSBvZiBlZGl0YWJsZVxuICAgIHJldHVybihcbiAgICAgICAgPGlucHV0IHsuLi5hdHRyfSB0eXBlPVwidGV4dFwiIGNsYXNzTmFtZT17KGVkaXRvckNsYXNzfHxcIlwiKStcIiBmb3JtLWNvbnRyb2wgZWRpdG9yIGVkaXQtdGV4dFwifS8+XG4gICAgKVxufTtcblxuZXhwb3J0IGRlZmF1bHQgRWRpdG9yO1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvRWRpdG9yLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _reactToastr = __webpack_require__(15);\n\nvar ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation);\n\nvar Notification = (function (_React$Component) {\n _inherits(Notification, _React$Component);\n\n function Notification() {\n _classCallCheck(this, Notification);\n\n _get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments);\n }\n\n _createClass(Notification, [{\n key: 'notice',\n\n // allow type is success,info,warning,error\n value: function notice(type, msg, title) {\n this.refs.toastr[type](msg, title, {\n mode: 'single',\n timeOut: 5000,\n extendedTimeOut: 1000,\n showAnimation: \"animated bounceIn\",\n hideAnimation: \"animated bounceOut\"\n });\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr', toastMessageFactory: ToastrMessageFactory,\n id: 'toast-container', className: 'toast-top-right' });\n }\n }]);\n\n return Notification;\n})(_react2['default'].Component);\n\nexports['default'] = Notification;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvTm90aWZpY2F0aW9uLmpzPzNjODYiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztpQ0FDUCxDQUFTOzs7O3VDQUtwQixFQUFjOztBQUdyQixJQUFJLG9CQUFvQixHQUFDLG1CQUFNLGFBQWEsQ0FBQywwQkFBYSxTQUFTLENBQUMsQ0FBQzs7SUFFL0QsWUFBWTtZQUFaLFlBQVk7O1dBQVosWUFBWTswQkFBWixZQUFZOzsrQkFBWixZQUFZOzs7ZUFBWixZQUFZOzs7O1dBRVYsZ0JBQUMsSUFBSSxFQUFDLEdBQUcsRUFBQyxLQUFLLEVBQUM7QUFDcEIsVUFBSSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLENBQ2xCLEdBQUcsRUFBQyxLQUFLLEVBQUU7QUFDVCxZQUFJLEVBQUMsUUFBUTtBQUNiLGVBQU8sRUFBRSxJQUFJO0FBQ2IsdUJBQWUsRUFBRSxJQUFJO0FBQ3JCLHFCQUFhLEVBQUUsb0JBQW9CO0FBQ25DLHFCQUFhLEVBQUUsb0JBQW9CO09BQ3BDLENBQUMsQ0FBQztLQUNSOzs7V0FFSyxrQk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biAgICAgICAgPFRvYXN0Q29udGFpbmVyIHJlZj1cInRvYXN0clwiIHRvYXN0TWVzc2FnZUZhY3Rvcnk9e1RvYXN0ck1lc3NhZ2VGYWN0b3J5fVxuICAgICAgICAgICAgICAgICAgICAgICAgIGlkPVwidG9hc3QtY29udGFpbmVyXCIgIGNsYXNzTmFtZT1cInRvYXN0LXRvcC1yaWdodFwiPjwvVG9hc3RDb250YWluZXI+XG4gICAgKVxuICB9XG59XG5cbmV4cG9ydCBkZWZhdWx0IE5vdGlmaWNhdGlvbjtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL05vdGlmaWNhdGlvbi5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.ToastMessage = exports.ToastContainer = undefined;\n\nvar _ToastContainer = __webpack_require__(16);\n\nvar _ToastContainer2 = _interopRequireDefault(_ToastContainer);\n\nvar _ToastMessage = __webpack_require__(23);\n\nvar _ToastMessage2 = _interopRequireDefault(_ToastMessage);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nexports.ToastContainer = _ToastContainer2.default;\nexports.ToastMessage = _ToastMessage2.default;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0LXRvYXN0ci9saWIvaW5kZXguanM/ODEyNyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7QUFFQTtBQUNBO0FBQ0EsQ0FBQztBQUNEOztBQUVBOztBQUVBOztBQUVBOztBQUVBOztBQUVBLHNDQUFzQyx1Q0FBdUMsZ0JBQWdCOztBQUU3RjtBQUNBIiwiZmlsZSI6IjE1LmpzIiwic291cmNlc0NvbnRlbnQiOlsiXCJ1c2Ugc3RyaWN0XCI7XG5cbk9iamVjdC5kZWZpbmVQcm9wZXJ0eShleHBvcnRzLCBcIl9fZXNNb2R1bGVcIiwge1xuICB2YWx1ZTogdHJ1ZVxufSk7XG5leHBvcnRzLlRvYXN0TWVzc2FnZSA9IGV4cG9ydHMuVG9hc3RDb250YWluZXIgPSB1bmRlZmluZWQ7XG5cbnZhciBfVG9hc3RDb250YWluZXIgPSByZXF1aXJlKFwiLi9Ub2FzdENvbnRhaW5lclwiKTtcblxudmFyIF9Ub2FzdENvbnRhaW5lcjIgPSBfaW50ZXJvcFJlcXVpcmVEZWZhdWx0KF9Ub2FzdENvbnRhaW5lcik7XG5cbnZhciBfVG9hc3RNZXNzYWdlID0gcmVxdWlyZShcIi4vVG9hc3RNZXNzYWdlXCIpO1xuXG52YXIgX1RvYXN0TWVzc2FnZTIgPSBfaW50ZXJvcFJlcXVpcmVEZWZhdWx0KF9Ub2FzdE1lc3NhZ2UpO1xuXG5mdW5jdGlvbiBfaW50ZXJvcFJlcXVpcmVEZWZhdWx0KG9iaikgeyByZXR1cm4gb2JqICYmIG9iai5fX2VzTW9kdWxlID8gb2JqIDogeyBkZWZhdWx0OiBvYmogfTsgfVxuXG5leHBvcnRzLlRvYXN0Q29udGFpbmVyID0gX1RvYXN0Q29udGFpbmVyMi5kZWZhdWx0O1xuZXhwb3J0cy5Ub2FzdE1lc3NhZ2UgPSBfVG9hc3RNZXNzYWdlMi5kZWZhdWx0O1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0LXRvYXN0ci9saWIvaW5kZXguanNcbiAqKiBtb2R1bGUgaWQgPSAxNVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==')},function(module,exports,__webpack_require__){eval('"use strict";\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _reactAddonsUpdate = __webpack_require__(17);\n\nvar _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);\n\nvar _ToastMessage = __webpack_require__(23);\n\nvar _ToastMessage2 = _interopRequireDefault(_ToastMessage);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn\'t been initialised - super() hasn\'t been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar ToastContainer = function (_Component) {\n _inherits(ToastContainer, _Component);\n\n function ToastContainer() {\n var _Object$getPrototypeO;\n\n var _temp, _this, _ret;\n\n _classCallCheck(this, ToastContainer);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {\n toasts: [],\n toastId: 0,\n previousMessage: null\n }, _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n _createClass(ToastContainer, [{\n key: "error",\n value: function error(message, title, optionsOverride) {\n this._notify(this.props.toastType.error, message, title, optionsOverride);\n }\n }, {\n key: "info",\n value: function info(message, title, optionsOverride) {\n this._notify(this.props.toastType.info, message, title, optionsOverride);\n }\n }, {\n key: "success",\n value: function success(message, title, optionsOverride) {\n this._notify(this.props.toastType.success, message, title, optionsOverride);\n }\n }, {\n key: "warning",\n value: function warning(message, title, optionsOverride) {\n this._notify(this.props.toastType.warning, message, title, optionsOverride);\n }\n }, {\n key: "clear",\n value: function clear() {\n var _this2 = this;\n\n Object.keys(this.refs).forEach(function (key) {\n _this2.refs[key].hideToast(false);\n });\n }\n }, {\n key: "render",\n value: function render() {\n var _this3 = this;\n\n return _react2.default.createElement(\n "div",\n _extends({}, this.props, { "aria-live": "polite", role: "alert" }),\n this.state.toasts.map(function (toast) {\n return _this3.props.toastMessageFactory(toast);\n })\n );\n }\n }, {\n key: "_notify",\n value: function _notify(type, message, title) {\n var _this4 = this;\n\n var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];\n\n if (this.props.preventDuplicates) {\n if (this.state.previousMessage === message) {\n return;\n }\n }\n var key = this.state.toastId++;\n var toastId = key;\n var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {\n $merge: {\n type: type,\n title: title,\n message: message,\n toastId: toastId,\n key: key,\n ref: "toasts__" + key,\n handleOnClick: function handleOnClick(e) {\n if ("function" === typeof optionsOverride.handleOnClick) {\n optionsOverride.handleOnClick();\n }\n return _this4._handle_toast_on_click(e);\n },\n handleRemove: this._handle_toast_remove.bind(this)\n }\n });\n var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);\n\n var nextState = (0, _reactAddonsUpdate2.default)(this.state, {\n toasts: toastOperation,\n previousMessage: { $set: message }\n });\n this.setState(nextState);\n }\n }, {\n key: "_handle_toast_on_click",\n value: function _handle_toast_on_click(event) {\n this.props.onClick(event);\n if (event.defaultPrevented) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n }\n }, {\n key: "_handle_toast_remove",\n value: function _handle_toast_remove(toastId) {\n var _this5 = this;\n\n var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");\n this.state.toasts[operationName](function (found, toast, index) {\n if (found || toast.toastId !== toastId) {\n return false;\n }\n _this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {\n toasts: { $splice: [[index, 1]] }\n }));\n return true;\n }, false);\n }\n }]);\n\n return ToastContainer;\n}(_react.Component);\n\nToastContainer.defaultProps = {\n toastType: {\n error: "error",\n info: "info",\n success: "success",\n warning: "warning"\n },\n id: "toast-container",\n toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),\n preventDuplicates: false,\n newestOnTop: true,\n onClick: function onClick() {}\n};\nexports.default = ToastContainer;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0LXRvYXN0ci9saWIvVG9hc3RDb250YWluZXIuanM/MmQyYiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7QUFFQSxtREFBbUQsZ0JBQWdCLHNCQUFzQixPQUFPLDJCQUEyQiwwQkFBMEIseURBQXlELDJCQUEyQixFQUFFLEVBQUUsRUFBRSxlQUFlOztBQUU5UCxnQ0FBZ0MsMkNBQTJDLGdCQUFnQixrQkFBa0IsT0FBTywyQkFBMkIsd0RBQXdELGdDQUFnQyx1REFBdUQsMkRBQTJELEVBQUUsRUFBRSx5REFBeUQscUVBQXFFLDZEQUE2RCxvQkFBb0Is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BpZDogXCJ0b2FzdC1jb250YWluZXJcIixcbiAgdG9hc3RNZXNzYWdlRmFjdG9yeTogX3JlYWN0Mi5kZWZhdWx0LmNyZWF0ZUZhY3RvcnkoX1RvYXN0TWVzc2FnZTIuZGVmYXVsdCksXG4gIHByZXZlbnREdXBsaWNhdGVzOiBmYWxzZSxcbiAgbmV3ZXN0T25Ub3A6IHRydWUsXG4gIG9uQ2xpY2s6IGZ1bmN0aW9uIG9uQ2xpY2soKSB7fVxufTtcbmV4cG9ydHMuZGVmYXVsdCA9IFRvYXN0Q29udGFpbmVyO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0LXRvYXN0ci9saWIvVG9hc3RDb250YWluZXIuanNcbiAqKiBtb2R1bGUgaWQgPSAxNlxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==');
},function(module,exports,__webpack_require__){eval("module.exports = __webpack_require__(18);\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0LXRvYXN0ci9+L3JlYWN0LWFkZG9ucy11cGRhdGUvaW5kZXguanM/NGUyMyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsImZpbGUiOiIxNy5qcyIsInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gcmVxdWlyZSgncmVhY3QvbGliL3VwZGF0ZScpO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0LXRvYXN0ci9+L3JlYWN0LWFkZG9ucy11cGRhdGUvaW5kZXguanNcbiAqKiBtb2R1bGUgaWQgPSAxN1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("/* WEBPACK VAR INJECTION */(function(process) {/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule update\n */\n\n/* global hasOwnProperty:true */\n\n'use strict';\n\nvar assign = __webpack_require__(20);\nvar keyOf = __webpack_require__(21);\nvar invariant = __webpack_require__(22);\nvar hasOwnProperty = ({}).hasOwnProperty;\n\nfunction shallowCopy(x) {\n if (Array.isArray(x)) {\n return x.concat();\n } else if (x && typeof x === 'object') {\n return assign(new x.constructor(), x);\n } else {\n return x;\n }\n}\n\nvar COMMAND_PUSH = keyOf({ $push: null });\nvar COMMAND_UNSHIFT = keyOf({ $unshift: null });\nvar COMMAND_SPLICE = keyOf({ $splice: null });\nvar COMMAND_SET = keyOf({ $set: null });\nvar COMMAND_MERGE = keyOf({ $merge: null });\nvar COMMAND_APPLY = keyOf({ $apply: null });\n\nvar ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];\n\nvar ALL_COMMANDS_SET = {};\n\nALL_COMMANDS_LIST.forEach(function (command) {\n ALL_COMMANDS_SET[command] = true;\n});\n\nfunction invariantArrayCase(value, spec, command) {\n !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined;\n var specValue = spec[command];\n !Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined;\n}\n\nfunction update(value, spec) {\n !(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined;\n\n if (hasOwnProperty.call(spec, COMMAND_SET)) {\n !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined;\n\n return spec[COMMAND_SET];\n }\n\n var nextValue = shallowCopy(value);\n\n if (hasOwnProperty.call(spec, COMMAND_MERGE)) {\n var mergeObj = spec[COMMAND_MERGE];\n !(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \\'object\\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined;\n !(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \\'object\\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined;\n assign(nextValue, spec[COMMAND_MERGE]);\n }\n\n if (hasOwnProperty.call(spec, COMMAND_PUSH)) {\n invariantArrayCase(value, spec, COMMAND_PUSH);\n spec[COMMAND_PUSH].forEach(function (item) {\n nextValue.push(item);\n });\n }\n\n if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {\n invariantArrayCase(value, spec, COMMAND_UNSHIFT);\n spec[COMMAND_UNSHIFT].forEach(function (item) {\n nextValue.unshift(item);\n });\n }\n\n if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {\n !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined;\n !Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;\n spec[COMMAND_SPLICE].forEach(function (args) {\n !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;\n nextValue.splice.apply(nextValue, args);\n });\n }\n\n if (hasOwnProperty.call(spec, COMMAND_APPLY)) {\n !(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined;\n nextValue = spec[COMMAND_APPLY](nextValue);\n }\n\n for (var k in spec) {\n if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {\n nextValue[k] = update(value[k], spec[k]);\n }\n }\n\n return nextValue;\n}\n\nmodule.exports = update;\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L2xpYi91cGRhdGUuanM/ZTdlMCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSx3QkFBd0I7O0FBRXhCO0FBQ0E7QUFDQTtBQUNBLEdBQUc7QUFDSDtBQUNBLEdBQUc7QUFDSDtBQUNBO0FBQ0E7O0FBRUEsMEJBQTBCLGNBQWM7QUFDeEMsNkJBQTZCLGlCQUFpQjtBQUM5Qyw0QkFBNEIsZ0JBQWdCO0FBQzVDLHlCQUF5QixhQUFhO0FBQ3RDLDJCQUEyQixlQUFlO0FBQzFDLDJCQUEyQixlQUFlOztBQUUxQzs7QUFFQTs7QUFFQTtBQUNBO0FBQ0EsQ0FBQzs7QUFFRDtBQUNBLG1JQUFtSTtBQUNuSTtBQUNBLHFJQUFxSTtBQUNySTs7QUFFQTtBQU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XNzLmVudi5OT0RFX0VOViAhPT0gJ3Byb2R1Y3Rpb24nID8gaW52YXJpYW50KGZhbHNlLCAndXBkYXRlKCk6IGV4cGVjdGVkIHNwZWMgb2YgJXMgdG8gYmUgYSBmdW5jdGlvbjsgZ290ICVzLicsIENPTU1BTkRfQVBQTFksIHNwZWNbQ09NTUFORF9BUFBMWV0pIDogaW52YXJpYW50KGZhbHNlKSA6IHVuZGVmaW5lZDtcbiAgICBuZXh0VmFsdWUgPSBzcGVjW0NPTU1BTkRfQVBQTFldKG5leHRWYWx1ZSk7XG4gIH1cblxuICBmb3IgKHZhciBrIGluIHNwZWMpIHtcbiAgICBpZiAoIShBTExfQ09NTUFORFNfU0VULmhhc093blByb3BlcnR5KGspICYmIEFMTF9DT01NQU5EU19TRVRba10pKSB7XG4gICAgICBuZXh0VmFsdWVba10gPSB1cGRhdGUodmFsdWVba10sIHNwZWNba10pO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiBuZXh0VmFsdWU7XG59XG5cbm1vZHVsZS5leHBvcnRzID0gdXBkYXRlO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0L2xpYi91cGRhdGUuanNcbiAqKiBtb2R1bGUgaWQgPSAxOFxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports){eval("// shim for using process in browser\n\nvar process = module.exports = {};\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = setTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n clearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n setTimeout(drainQueue, 0);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vKHdlYnBhY2spL34vbm9kZS1saWJzLWJyb3dzZXIvfi9wcm9jZXNzL2Jyb3dzZXIuanM/NmYwZSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsS0FBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUF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pO1xufTtcbnByb2Nlc3MudW1hc2sgPSBmdW5jdGlvbigpIHsgcmV0dXJuIDA7IH07XG5cblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqICh3ZWJwYWNrKS9+L25vZGUtbGlicy1icm93c2VyL34vcHJvY2Vzcy9icm93c2VyLmpzXG4gKiogbW9kdWxlIGlkID0gMTlcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports){eval("/**\n * Copyright 2014-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule Object.assign\n */\n\n// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign\n\n'use strict';\n\nfunction assign(target, sources) {\n if (target == null) {\n throw new TypeError('Object.assign target cannot be null or undefined');\n }\n\n var to = Object(target);\n var hasOwnProperty = Object.prototype.hasOwnProperty;\n\n for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {\n var nextSource = arguments[nextIndex];\n if (nextSource == null) {\n continue;\n }\n\n var from = Object(nextSource);\n\n // We don't currently support accessors nor proxies. Therefore this\n // copy cannot throw. If we ever supported this then we must handle\n // exceptions and side-effects. We don't support symbols so they won't\n // be transferred.\n\n for (var key in from) {\n if (hasOwnProperty.call(from, key)) {\n to[key] = from[key];\n }\n }\n }\n\n return to;\n}\n\nmodule.exports = assign;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L2xpYi9PYmplY3QuYXNzaWduLmpzPzRhNTUiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0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odW5rcyA9IDBcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports){eval("/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule keyOf\n */\n\n/**\n * Allows extraction of a minified key. Let's the build system minify keys\n * without losing the ability to dynamically use key strings as values\n * themselves. Pass in an object with a single key/val pair and it will return\n * you the string key of that single record. Suppose you want to grab the\n * value for a key 'className' inside of an object. Key/val minification may\n * have aliased that key to be 'xa12'. keyOf({className: null}) will return\n * 'xa12' in that case. Resolve keys you want to use once at startup time, then\n * reuse those resolutions.\n */\n\"use strict\";\n\nvar keyOf = function (oneKeyObj) {\n var key;\n for (key in oneKeyObj) {\n if (!oneKeyObj.hasOwnProperty(key)) {\n continue;\n }\n return key;\n }\n return null;\n};\n\nmodule.exports = keyOf;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L34vZmJqcy9saWIva2V5T2YuanM/NjVlOSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4Q0FBOEMsZ0JBQWdCO0FBQzlEO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBIiwiZmlsZSI6IjIxLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgMjAxMy0yMDE1LCBGYWNlYm9vaywgSW5jLlxuICogQWxsIHJpZ2h0cyByZXNlcnZlZC5cbiAq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ugb25jZSBhdCBzdGFydHVwIHRpbWUsIHRoZW5cbiAqIHJldXNlIHRob3NlIHJlc29sdXRpb25zLlxuICovXG5cInVzZSBzdHJpY3RcIjtcblxudmFyIGtleU9mID0gZnVuY3Rpb24gKG9uZUtleU9iaikge1xuICB2YXIga2V5O1xuICBmb3IgKGtleSBpbiBvbmVLZXlPYmopIHtcbiAgICBpZiAoIW9uZUtleU9iai5oYXNPd25Qcm9wZXJ0eShrZXkpKSB7XG4gICAgICBjb250aW51ZTtcbiAgICB9XG4gICAgcmV0dXJuIGtleTtcbiAgfVxuICByZXR1cm4gbnVsbDtcbn07XG5cbm1vZHVsZS5leHBvcnRzID0ga2V5T2Y7XG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL34vcmVhY3Qvfi9mYmpzL2xpYi9rZXlPZi5qc1xuICoqIG1vZHVsZSBpZCA9IDIxXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("/* WEBPACK VAR INJECTION */(function(process) {/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule invariant\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nfunction invariant(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n}\n\nmodule.exports = invariant;\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L34vZmJqcy9saWIvaW52YXJpYW50LmpzPzU2OGMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBLHFEQUFxRDtBQUNyRCxLQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0E7QUFDQSxPQUFPO0FBQ1A7QUFDQTs7QUFFQSwwQkFBMEI7QUFDMUI7QUFDQTtBQUNBOztBQUVBLDJCIiwiZmlsZSI6IjIyLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBDb3B5cmlnaHQgMjAxMy0yMDE1LCBGYWNlYm9vaywgSW5jLlxuICogQWxsIHJpZ2h0cyByZXNlcnZlZC5cbiAqXG4gKiBUaGlzIHNvdXJjZSBjb2RlIGlzIGxpY2Vuc2VkIHVuZGVyIHRoZSBCU0Qtc3R5bGUgbGljZW5zZSBmb3VuZCBpbiB0aGVcbiAqIExJQ0VOU0UgZmlsZSBpbiB0aGUgcm9vdCBkaXJlY3Rvcnkgb2YgdGhpcyBzb3VyY2UgdHJlZS4gQW4gYWRkaXRpb25hbCBncmFudFxuICogb2YgcGF0ZW50IHJpZ2h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BlcnJvciA9IG5ldyBFcnJvcignTWluaWZpZWQgZXhjZXB0aW9uIG9jY3VycmVkOyB1c2UgdGhlIG5vbi1taW5pZmllZCBkZXYgZW52aXJvbm1lbnQgJyArICdmb3IgdGhlIGZ1bGwgZXJyb3IgbWVzc2FnZSBhbmQgYWRkaXRpb25hbCBoZWxwZnVsIHdhcm5pbmdzLicpO1xuICAgIH0gZWxzZSB7XG4gICAgICB2YXIgYXJncyA9IFthLCBiLCBjLCBkLCBlLCBmXTtcbiAgICAgIHZhciBhcmdJbmRleCA9IDA7XG4gICAgICBlcnJvciA9IG5ldyBFcnJvcihmb3JtYXQucmVwbGFjZSgvJXMvZywgZnVuY3Rpb24gKCkge1xuICAgICAgICByZXR1cm4gYXJnc1thcmdJbmRleCsrXTtcbiAgICAgIH0pKTtcbiAgICAgIGVycm9yLm5hbWUgPSAnSW52YXJpYW50IFZpb2xhdGlvbic7XG4gICAgfVxuXG4gICAgZXJyb3IuZnJhbWVzVG9Qb3AgPSAxOyAvLyB3ZSBkb24ndCBjYXJlIGFib3V0IGludmFyaWFudCdzIG93biBmcmFtZVxuICAgIHRocm93IGVycm9yO1xuICB9XG59XG5cbm1vZHVsZS5leHBvcnRzID0gaW52YXJpYW50O1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0L34vZmJqcy9saWIvaW52YXJpYW50LmpzXG4gKiogbW9kdWxlIGlkID0gMjJcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\nexports.jQuery = exports.animation = undefined;\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _reactAddonsUpdate = __webpack_require__(17);\n\nvar _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _animationMixin = __webpack_require__(24);\n\nvar _animationMixin2 = _interopRequireDefault(_animationMixin);\n\nvar _jQueryMixin = __webpack_require__(29);\n\nvar _jQueryMixin2 = _interopRequireDefault(_jQueryMixin);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction noop() {}\n\nvar ToastMessageSpec = {\n displayName: "ToastMessage",\n\n getDefaultProps: function getDefaultProps() {\n var iconClassNames = {\n error: "toast-error",\n info: "toast-info",\n success: "toast-success",\n warning: "toast-warning"\n };\n\n return {\n className: "toast",\n iconClassNames: iconClassNames,\n titleClassName: "toast-title",\n messageClassName: "toast-message",\n tapToDismiss: true,\n closeButton: false\n };\n },\n handleOnClick: function handleOnClick(event) {\n this.props.handleOnClick(event);\n if (this.props.tapToDismiss) {\n this.hideToast(true);\n }\n },\n _handle_close_button_click: function _handle_close_button_click(event) {\n event.stopPropagation();\n this.hideToast(true);\n },\n _handle_remove: function _handle_remove() {\n this.props.handleRemove(this.props.toastId);\n },\n _render_close_button: function _render_close_button() {\n return this.props.closeButton ? _react2.default.createElement("button", {\n className: "toast-close-button", role: "button",\n onClick: this._handle_close_button_click,\n dangerouslySetInnerHTML: { __html: "×" }\n }) : false;\n },\n _render_title_element: function _render_title_element() {\n return this.props.title ? _react2.default.createElement(\n "div",\n { className: this.props.titleClassName },\n this.props.title\n ) : false;\n },\n _render_message_element: function _render_message_element() {\n return this.props.message ? _react2.default.createElement(\n "div",\n { className: this.props.messageClassName },\n this.props.message\n ) : false;\n },\n render: function render() {\n var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type];\n\n return _react2.default.createElement(\n "div",\n {\n className: (0, _classnames2.default)(this.props.className, iconClassName),\n style: this.props.style,\n onClick: this.handleOnClick,\n onMouseEnter: this.handleMouseEnter,\n onMouseLeave: this.handleMouseLeave\n },\n this._render_close_button(),\n this._render_title_element(),\n this._render_message_element()\n );\n }\n};\n\nvar animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {\n displayName: { $set: "ToastMessage.animation" },\n mixins: { $set: [_animationMixin2.default] }\n}));\n\nvar jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {\n displayName: { $set: "ToastMessage.jQuery" },\n mixins: { $set: [_jQueryMixin2.default] }\n}));\n\n/*\n * assign default noop functions\n */\nToastMessageSpec.handleMouseEnter = noop;\nToastMessageSpec.handleMouseLeave = noop;\nToastMessageSpec.hideToast = noop;\n\nvar ToastMessage = _react2.default.createClass(ToastMessageSpec);\n\nToastMessage.animation = animation;\nToastMessage.jQuery = jQuery;\n\nexports.default = ToastMessage;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0LXRvYXN0ci9saWIvVG9hc3RNZXNzYWdlL2luZGV4LmpzP2NkODQiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7O0FBRUE7QUFDQTtBQUNBLENBQUM7QUFDRDs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQTs7QUFFQSxzQ0FBc0MsdUNBQXVDLGdCQUFnQjs7QUFFN0Y7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsR0FBRztBQUNIO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxHQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0EsR0FBRztBQUNIO0FBQ0E7QUFDQSxHQUFHO0FBQ0g7QUFDQTtBQUNBO0FBQ0E7QUFDQSxnQ0FBZ0MsaUJBQWlCO0FBQ2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lvbnNcbiAqL1xuVG9hc3RNZXNzYWdlU3BlYy5oYW5kbGVNb3VzZUVudGVyID0gbm9vcDtcblRvYXN0TWVzc2FnZVNwZWMuaGFuZGxlTW91c2VMZWF2ZSA9IG5vb3A7XG5Ub2FzdE1lc3NhZ2VTcGVjLmhpZGVUb2FzdCA9IG5vb3A7XG5cbnZhciBUb2FzdE1lc3NhZ2UgPSBfcmVhY3QyLmRlZmF1bHQuY3JlYXRlQ2xhc3MoVG9hc3RNZXNzYWdlU3BlYyk7XG5cblRvYXN0TWVzc2FnZS5hbmltYXRpb24gPSBhbmltYXRpb247XG5Ub2FzdE1lc3NhZ2UualF1ZXJ5ID0galF1ZXJ5O1xuXG5leHBvcnRzLmRlZmF1bHQgPSBUb2FzdE1lc3NhZ2U7XG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL34vcmVhY3QtdG9hc3RyL2xpYi9Ub2FzdE1lc3NhZ2UvaW5kZXguanNcbiAqKiBtb2R1bGUgaWQgPSAyM1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==');
},function(module,exports,__webpack_require__){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\n\nvar _CSSCore = __webpack_require__(25);\n\nvar _CSSCore2 = _interopRequireDefault(_CSSCore);\n\nvar _ReactTransitionEvents = __webpack_require__(27);\n\nvar _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents);\n\nvar _reactDom = __webpack_require__(6);\n\nvar _reactDom2 = _interopRequireDefault(_reactDom);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar TICK = 17;\nvar toString = Object.prototype.toString;\nexports.default = {\n getDefaultProps: function getDefaultProps() {\n return {\n transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate)\n showAnimation: "animated bounceIn", // or other animations from animate.css\n hideAnimation: "animated bounceOut",\n timeOut: 5000,\n extendedTimeOut: 1000\n };\n },\n componentWillMount: function componentWillMount() {\n this.classNameQueue = [];\n this.isHiding = false;\n this.intervalId = null;\n },\n componentDidMount: function componentDidMount() {\n var _this = this;\n\n this._is_mounted = true;\n this._show();\n var node = _reactDom2.default.findDOMNode(this);\n\n var onHideComplete = function onHideComplete() {\n if (_this.isHiding) {\n _this._set_is_hiding(false);\n _ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete);\n _this._handle_remove();\n }\n };\n _ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete);\n\n if (this.props.timeOut > 0) {\n this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));\n }\n },\n componentWillUnmount: function componentWillUnmount() {\n this._is_mounted = false;\n if (this.intervalId) {\n clearTimeout(this.intervalId);\n }\n },\n _set_transition: function _set_transition(hide) {\n var animationType = hide ? "leave" : "enter";\n var node = _reactDom2.default.findDOMNode(this);\n var className = this.props.transition + "-" + animationType;\n var activeClassName = className + "-active";\n\n var endListener = function endListener(e) {\n if (e && e.target !== node) {\n return;\n }\n\n _CSSCore2.default.removeClass(node, className);\n _CSSCore2.default.removeClass(node, activeClassName);\n\n _ReactTransitionEvents2.default.removeEndEventListener(node, endListener);\n };\n\n _ReactTransitionEvents2.default.addEndEventListener(node, endListener);\n\n _CSSCore2.default.addClass(node, className);\n\n // Need to do this to actually trigger a transition.\n this._queue_class(activeClassName);\n },\n _clear_transition: function _clear_transition(hide) {\n var node = _reactDom2.default.findDOMNode(this);\n var animationType = hide ? "leave" : "enter";\n var className = this.props.transition + "-" + animationType;\n var activeClassName = className + "-active";\n\n _CSSCore2.default.removeClass(node, className);\n _CSSCore2.default.removeClass(node, activeClassName);\n },\n _set_animation: function _set_animation(hide) {\n var node = _reactDom2.default.findDOMNode(this);\n var animations = this._get_animation_classes(hide);\n var endListener = function endListener(e) {\n if (e && e.target !== node) {\n return;\n }\n\n animations.forEach(function (anim) {\n _CSSCore2.default.removeClass(node, anim);\n });\n\n _ReactTransitionEvents2.default.removeEndEventListener(node, endListener);\n };\n\n _ReactTransitionEvents2.default.addEndEventListener(node, endListener);\n\n animations.forEach(function (anim) {\n _CSSCore2.default.addClass(node, anim);\n });\n },\n _get_animation_classes: function _get_animation_classes(hide) {\n var animations = hide ? this.props.hideAnimation : this.props.showAnimation;\n if ("[object Array]" === toString.call(animations)) {\n return animations;\n } else if ("string" === typeof animations) {\n return animations.split(" ");\n }\n },\n _clear_animation: function _clear_animation(hide) {\n var _this2 = this;\n\n var animations = this._get_animation_classes(hide);\n animations.forEach(function (animation) {\n _CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation);\n });\n },\n _queue_class: function _queue_class(className) {\n this.classNameQueue.push(className);\n\n if (!this.timeout) {\n this.timeout = setTimeout(this._flush_class_name_queue, TICK);\n }\n },\n _flush_class_name_queue: function _flush_class_name_queue() {\n if (this._is_mounted) {\n this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this)));\n }\n this.classNameQueue.length = 0;\n this.timeout = null;\n },\n _show: function _show() {\n if (this.props.transition) {\n this._set_transition();\n } else if (this.props.showAnimation) {\n this._set_animation();\n }\n },\n handleMouseEnter: function handleMouseEnter() {\n clearTimeout(this.intervalId);\n this._set_interval_id(null);\n if (this.isHiding) {\n this._set_is_hiding(false);\n\n if (this.props.hideAnimation) {\n this._clear_animation(true);\n } else if (this.props.transition) {\n this._clear_transition(true);\n }\n }\n },\n handleMouseLeave: function handleMouseLeave() {\n if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {\n this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));\n }\n },\n hideToast: function hideToast(override) {\n if (this.isHiding || this.intervalId === null && !override) {\n return;\n }\n\n this._set_is_hiding(true);\n if (this.props.transition) {\n this._set_transition(true);\n } else if (this.props.hideAnimation) {\n this._set_animation(true);\n } else {\n this._handle_remove();\n }\n },\n _set_interval_id: function _set_interval_id(interv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YgKHRoaXMucHJvcHMuaGlkZUFuaW1hdGlvbikge1xuICAgICAgdGhpcy5fc2V0X2FuaW1hdGlvbih0cnVlKTtcbiAgICB9IGVsc2Uge1xuICAgICAgdGhpcy5faGFuZGxlX3JlbW92ZSgpO1xuICAgIH1cbiAgfSxcbiAgX3NldF9pbnRlcnZhbF9pZDogZnVuY3Rpb24gX3NldF9pbnRlcnZhbF9pZChpbnRlcnZhbElkKSB7XG4gICAgdGhpcy5pbnRlcnZhbElkID0gaW50ZXJ2YWxJZDtcbiAgfSxcbiAgX3NldF9pc19oaWRpbmc6IGZ1bmN0aW9uIF9zZXRfaXNfaGlkaW5nKGlzSGlkaW5nKSB7XG4gICAgdGhpcy5pc0hpZGluZyA9IGlzSGlkaW5nO1xuICB9XG59O1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9+L3JlYWN0LXRvYXN0ci9saWIvVG9hc3RNZXNzYWdlL2FuaW1hdGlvbk1peGluLmpzXG4gKiogbW9kdWxlIGlkID0gMjRcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=')},function(module,exports,__webpack_require__){eval("/* WEBPACK VAR INJECTION */(function(process) {/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule CSSCore\n * @typechecks\n */\n\n'use strict';\n\nvar invariant = __webpack_require__(26);\n\n/**\n * The CSSCore module specifies the API (and implements most of the methods)\n * that should be used when dealing with the display of elements (via their\n * CSS classes and visibility on screen. It is an API focused on mutating the\n * display and not reading it as no logical state should be encoded in the\n * display of elements.\n */\n\nvar CSSCore = {\n\n /**\n * Adds the class passed in to the element if it doesn't already have it.\n *\n * @param {DOMElement} element the element to set the class on\n * @param {string} className the CSS className\n * @return {DOMElement} the element passed in\n */\n addClass: function (element, className) {\n !!/\\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. \"%s\" contains ' + 'multiple classes.', className) : invariant(false) : undefined;\n\n if (className) {\n if (element.classList) {\n element.classList.add(className);\n } else if (!CSSCore.hasClass(element, className)) {\n element.className = element.className + ' ' + className;\n }\n }\n return element;\n },\n\n /**\n * Removes the class passed in from the element\n *\n * @param {DOMElement} element the element to set the class on\n * @param {string} className the CSS className\n * @return {DOMElement} the element passed in\n */\n removeClass: function (element, className) {\n !!/\\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. \"%s\" contains ' + 'multiple classes.', className) : invariant(false) : undefined;\n\n if (className) {\n if (element.classList) {\n element.classList.remove(className);\n } else if (CSSCore.hasClass(element, className)) {\n element.className = element.className.replace(new RegExp('(^|\\\\s)' + className + '(?:\\\\s|$)', 'g'), '$1').replace(/\\s+/g, ' ') // multiple spaces to one\n .replace(/^\\s*|\\s*$/g, ''); // trim the ends\n }\n }\n return element;\n },\n\n /**\n * Helper to add or remove a class from an element based on a condition.\n *\n * @param {DOMElement} element the element to set the class on\n * @param {string} className the CSS className\n * @param {*} bool condition to whether to add or remove the class\n * @return {DOMElement} the element passed in\n */\n conditionClass: function (element, className, bool) {\n return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);\n },\n\n /**\n * Tests whether the element has the class specified.\n *\n * @param {DOMNode|DOMWindow} element the element to set the class on\n * @param {string} className the CSS className\n * @return {boolean} true if the element has the class, false if not\n */\n hasClass: function (element, className) {\n !!/\\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined;\n if (element.classList) {\n return !!className && element.classList.contains(className);\n }\n return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;\n }\n\n};\n\nmodule.exports = CSSCore;\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)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mIG5vdFxuICAgKi9cbiAgaGFzQ2xhc3M6IGZ1bmN0aW9uIChlbGVtZW50LCBjbGFzc05hbWUpIHtcbiAgICAhIS9cXHMvLnRlc3QoY2xhc3NOYW1lKSA/IHByb2Nlc3MuZW52Lk5PREVfRU5WICE9PSAncHJvZHVjdGlvbicgPyBpbnZhcmlhbnQoZmFsc2UsICdDU1MuaGFzQ2xhc3MgdGFrZXMgb25seSBhIHNpbmdsZSBjbGFzcyBuYW1lLicpIDogaW52YXJpYW50KGZhbHNlKSA6IHVuZGVmaW5lZDtcbiAgICBpZiAoZWxlbWVudC5jbGFzc0xpc3QpIHtcbiAgICAgIHJldHVybiAhIWNsYXNzTmFtZSAmJiBlbGVtZW50LmNsYXNzTGlzdC5jb250YWlucyhjbGFzc05hbWUpO1xuICAgIH1cbiAgICByZXR1cm4gKCcgJyArIGVsZW1lbnQuY2xhc3NOYW1lICsgJyAnKS5pbmRleE9mKCcgJyArIGNsYXNzTmFtZSArICcgJykgPiAtMTtcbiAgfVxuXG59O1xuXG5tb2R1bGUuZXhwb3J0cyA9IENTU0NvcmU7XG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL34vZmJqcy9saWIvQ1NTQ29yZS5qc1xuICoqIG1vZHVsZSBpZCA9IDI1XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("/* WEBPACK VAR INJECTION */(function(process) {/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule invariant\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nfunction invariant(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(format.replace(/%s/g, function () {\n return args[argIndex++];\n }));\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n}\n\nmodule.exports = invariant;\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L2ZianMvbGliL2ludmFyaWFudC5qcz80NTk5Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQSxxREFBcUQ7QUFDckQsS0FBSztBQUNMO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsT0FBTztBQUNQO0FBQ0E7O0FBRUEsMEJBQTBCO0FBQzFCO0FBQ0E7QUFDQTs7QUFFQSwyQiIsImZpbGUiOiIyNi5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IDIwMTMtMjAxNSwgRmFjZWJvb2ssIEluYy5cbiAqIEFsbCByaWdodHMgcmVzZXJ2ZWQuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNl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QgcmVxdWlyZXMgYW4gZXJyb3IgbWVzc2FnZSBhcmd1bWVudCcpO1xuICAgIH1cbiAgfVxuXG4gIGlmICghY29uZGl0aW9uKSB7XG4gICAgdmFyIGVycm9yO1xuICAgIGlmIChmb3JtYXQgPT09IHVuZGVmaW5lZCkge1xuICAgICAgZXJyb3IgPSBuZXcgRXJyb3IoJ01pbmlmaWVkIGV4Y2VwdGlvbiBvY2N1cnJlZDsgdXNlIHRoZSBub24tbWluaWZpZWQgZGV2IGVudmlyb25tZW50ICcgKyAnZm9yIHRoZSBmdWxsIGVycm9yIG1lc3NhZ2UgYW5kIGFkZGl0aW9uYWwgaGVscGZ1bCB3YXJuaW5ncy4nKTtcbiAgICB9IGVsc2Uge1xuICAgICAgdmFyIGFyZ3MgPSBbYSwgYiwgYywgZCwgZSwgZl07XG4gICAgICB2YXIgYXJnSW5kZXggPSAwO1xuICAgICAgZXJyb3IgPSBuZXcgRXJyb3IoZm9ybWF0LnJlcGxhY2UoLyVzL2csIGZ1bmN0aW9uICgpIHtcbiAgICAgICAgcmV0dXJuIGFyZ3NbYXJnSW5kZXgrK107XG4gICAgICB9KSk7XG4gICAgICBlcnJvci5uYW1lID0gJ0ludmFyaWFudCBWaW9sYXRpb24nO1xuICAgIH1cblxuICAgIGVycm9yLmZyYW1lc1RvUG9wID0gMTsgLy8gd2UgZG9uJ3QgY2FyZSBhYm91dCBpbnZhcmlhbnQncyBvd24gZnJhbWVcbiAgICB0aHJvdyBlcnJvcjtcbiAgfVxufVxuXG5tb2R1bGUuZXhwb3J0cyA9IGludmFyaWFudDtcblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIC4vfi9mYmpzL2xpYi9pbnZhcmlhbnQuanNcbiAqKiBtb2R1bGUgaWQgPSAyNlxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule ReactTransitionEvents\n */\n\n'use strict';\n\nvar ExecutionEnvironment = __webpack_require__(28);\n\n/**\n * EVENT_NAME_MAP is used to determine which event fired when a\n * transition/animation ends, based on the style property used to\n * define that event.\n */\nvar EVENT_NAME_MAP = {\n transitionend: {\n 'transition': 'transitionend',\n 'WebkitTransition': 'webkitTransitionEnd',\n 'MozTransition': 'mozTransitionEnd',\n 'OTransition': 'oTransitionEnd',\n 'msTransition': 'MSTransitionEnd'\n },\n\n animationend: {\n 'animation': 'animationend',\n 'WebkitAnimation': 'webkitAnimationEnd',\n 'MozAnimation': 'mozAnimationEnd',\n 'OAnimation': 'oAnimationEnd',\n 'msAnimation': 'MSAnimationEnd'\n }\n};\n\nvar endEvents = [];\n\nfunction detectEvents() {\n var testEl = document.createElement('div');\n var style = testEl.style;\n\n // On some platforms, in particular some releases of Android 4.x,\n // the un-prefixed \"animation\" and \"transition\" properties are defined on the\n // style object but the events that fire will still be prefixed, so we need\n // to check if the un-prefixed events are useable, and if not remove them\n // from the map\n if (!('AnimationEvent' in window)) {\n delete EVENT_NAME_MAP.animationend.animation;\n }\n\n if (!('TransitionEvent' in window)) {\n delete EVENT_NAME_MAP.transitionend.transition;\n }\n\n for (var baseEventName in EVENT_NAME_MAP) {\n var baseEvents = EVENT_NAME_MAP[baseEventName];\n for (var styleName in baseEvents) {\n if (styleName in style) {\n endEvents.push(baseEvents[styleName]);\n break;\n }\n }\n }\n}\n\nif (ExecutionEnvironment.canUseDOM) {\n detectEvents();\n}\n\n// We use the raw {add|remove}EventListener() call because EventListener\n// does not know how to remove event listeners and we really should\n// clean up. Also, these events are not triggered in older browsers\n// so we should be A-OK here.\n\nfunction addEventListener(node, eventName, eventListener) {\n node.addEventListener(eventName, eventListener, false);\n}\n\nfunction removeEventListener(node, eventName, eventListener) {\n node.removeEventListener(eventName, eventListener, false);\n}\n\nvar ReactTransitionEvents = {\n addEndEventListener: function (node, eventListener) {\n if (endEvents.length === 0) {\n // If CSS transitions are not supported, trigger an \"end animation\"\n // event immediately.\n window.setTimeout(eventListener, 0);\n return;\n }\n endEvents.forEach(function (endEvent) {\n addEventListener(node, endEvent, eventListener);\n });\n },\n\n removeEndEventListener: function (node, eventListener) {\n if (endEvents.length === 0) {\n return;\n }\n endEvents.forEach(function (endEvent) {\n removeEventListener(node, endEvent, eventListener);\n });\n }\n};\n\nmodule.exports = ReactTransitionEvents;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L2xpYi9SZWFjdFRyYW5zaXRpb25FdmVudHMuanM/YjZhYSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTs7QUFFQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxHQUFHOztBQUVIO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQSxtQkFBbUIsV0FBVztBQUM5QjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtB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iAgICAgIHJldHVybjtcbiAgICB9XG4gICAgZW5kRXZlbnRzLmZvckVhY2goZnVuY3Rpb24gKGVuZEV2ZW50KSB7XG4gICAgICByZW1vdmVFdmVudExpc3RlbmVyKG5vZGUsIGVuZEV2ZW50LCBldmVudExpc3RlbmVyKTtcbiAgICB9KTtcbiAgfVxufTtcblxubW9kdWxlLmV4cG9ydHMgPSBSZWFjdFRyYW5zaXRpb25FdmVudHM7XG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL34vcmVhY3QvbGliL1JlYWN0VHJhbnNpdGlvbkV2ZW50cy5qc1xuICoqIG1vZHVsZSBpZCA9IDI3XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9");
},function(module,exports){eval("/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule ExecutionEnvironment\n */\n\n'use strict';\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n\n/**\n * Simple, lightweight module assisting with the detection and context of\n * Worker. Helps avoid circular dependencies and allows code to reason about\n * whether or not they are in a Worker, even if they never include the main\n * `ReactWorker` dependency.\n */\nvar ExecutionEnvironment = {\n\n canUseDOM: canUseDOM,\n\n canUseWorkers: typeof Worker !== 'undefined',\n\n canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),\n\n canUseViewport: canUseDOM && !!window.screen,\n\n isInWorker: !canUseDOM // For now, this is true - might change in the future.\n\n};\n\nmodule.exports = ExecutionEnvironment;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0L34vZmJqcy9saWIvRXhlY3V0aW9uRW52aXJvbm1lbnQuanM/MjAzNS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bmNpZXMgYW5kIGFsbG93cyBjb2RlIHRvIHJlYXNvbiBhYm91dFxuICogd2hldGhlciBvciBub3QgdGhleSBhcmUgaW4gYSBXb3JrZXIsIGV2ZW4gaWYgdGhleSBuZXZlciBpbmNsdWRlIHRoZSBtYWluXG4gKiBgUmVhY3RXb3JrZXJgIGRlcGVuZGVuY3kuXG4gKi9cbnZhciBFeGVjdXRpb25FbnZpcm9ubWVudCA9IHtcblxuICBjYW5Vc2VET006IGNhblVzZURPTSxcblxuICBjYW5Vc2VXb3JrZXJzOiB0eXBlb2YgV29ya2VyICE9PSAndW5kZWZpbmVkJyxcblxuICBjYW5Vc2VFdmVudExpc3RlbmVyczogY2FuVXNlRE9NICYmICEhKHdpbmRvdy5hZGRFdmVudExpc3RlbmVyIHx8IHdpbmRvdy5hdHRhY2hFdmVudCksXG5cbiAgY2FuVXNlVmlld3BvcnQ6IGNhblVzZURPTSAmJiAhIXdpbmRvdy5zY3JlZW4sXG5cbiAgaXNJbldvcmtlcjogIWNhblVzZURPTSAvLyBGb3Igbm93LCB0aGlzIGlzIHRydWUgLSBtaWdodCBjaGFuZ2UgaW4gdGhlIGZ1dHVyZS5cblxufTtcblxubW9kdWxlLmV4cG9ydHMgPSBFeGVjdXRpb25FbnZpcm9ubWVudDtcblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIC4vfi9yZWFjdC9+L2ZianMvbGliL0V4ZWN1dGlvbkVudmlyb25tZW50LmpzXG4gKiogbW9kdWxlIGlkID0gMjhcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval('"use strict";\n\nObject.defineProperty(exports, "__esModule", {\n value: true\n});\n\nvar _reactDom = __webpack_require__(6);\n\nvar _reactDom2 = _interopRequireDefault(_reactDom);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction call_show_method($node, props) {\n $node[props.showMethod]({\n duration: props.showDuration,\n easing: props.showEasing\n });\n}\n\nexports.default = {\n getDefaultProps: function getDefaultProps() {\n return {\n style: {\n display: "none" },\n // effective $.hide()\n showMethod: "fadeIn", // slideDown, and show are built into jQuery\n showDuration: 300,\n showEasing: "swing", // and linear are built into jQuery\n hideMethod: "fadeOut",\n hideDuration: 1000,\n hideEasing: "swing",\n //\n timeOut: 5000,\n extendedTimeOut: 1000\n };\n },\n getInitialState: function getInitialState() {\n return {\n intervalId: null,\n isHiding: false\n };\n },\n componentDidMount: function componentDidMount() {\n call_show_method(this._get_$_node(), this.props);\n if (this.props.timeOut > 0) {\n this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));\n }\n },\n handleMouseEnter: function handleMouseEnter() {\n clearTimeout(this.state.intervalId);\n this._set_interval_id(null);\n this._set_is_hiding(false);\n\n call_show_method(this._get_$_node().stop(true, true), this.props);\n },\n handleMouseLeave: function handleMouseLeave() {\n if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {\n this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));\n }\n },\n hideToast: function hideToast(override) {\n if (this.state.isHiding || this.state.intervalId === null && !override) {\n return;\n }\n this.setState({ isHiding: true });\n\n this._get_$_node()[this.props.hideMethod]({\n duration: this.props.hideDuration,\n easing: this.props.hideEasing,\n complete: this._handle_remove\n });\n },\n _get_$_node: function _get_$_node() {\n /* eslint-disable no-undef */\n return jQuery(_reactDom2.default.findDOMNode(this));\n /* eslint-enable no-undef */\n },\n _set_interval_id: function _set_interval_id(intervalId) {\n this.setState({\n intervalId: intervalId\n });\n },\n _set_is_hiding: function _set_is_hiding(isHiding) {\n this.setState({\n isHiding: isHiding\n });\n }\n};\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9+L3JlYWN0LXRvYXN0ci9saWIvVG9hc3RNZXNzYWdlL2pRdW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yL2xpYi9Ub2FzdE1lc3NhZ2UvalF1ZXJ5TWl4aW4uanNcbiAqKiBtb2R1bGUgaWQgPSAyOVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==')},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _PageButtonJs = __webpack_require__(31);\n\nvar _PageButtonJs2 = _interopRequireDefault(_PageButtonJs);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar PaginationList = (function (_React$Component) {\n _inherits(PaginationList, _React$Component);\n\n function PaginationList() {\n _classCallCheck(this, PaginationList);\n\n _get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments);\n }\n\n _createClass(PaginationList, [{\n key: 'changePage',\n value: function changePage(page) {\n if (page == this.props.prePage) {\n page = this.props.currPage - 1 < 1 ? 1 : this.props.currPage - 1;\n } else if (page == this.props.nextPage) {\n page = this.props.currPage + 1 > this.totalPages ? this.totalPages : this.props.currPage + 1;\n } else if (page == this.props.lastPage) {\n page = this.totalPages;\n } else if (page == this.props.firstPage) {\n page = 1;\n } else {\n page = parseInt(page);\n }\n\n if (page != this.props.currPage) {\n this.props.changePage(page, this.props.sizePerPage);\n }\n }\n }, {\n key: 'changeSizePerPage',\n value: function changeSizePerPage(e) {\n e.preventDefault();\n\n var selectSize = parseInt(e.currentTarget.text);\n var currPage = this.props.currPage;\n\n if (selectSize != this.props.sizePerPage) {\n this.totalPages = Math.ceil(this.props.dataSize / selectSize);\n if (currPage > this.totalPages) currPage = this.totalPages;\n\n this.props.changePage(currPage, selectSize);\n if (this.props.onSizePerPageList) {\n this.props.onSizePerPageList(selectSize);\n }\n }\n }\n }, {\n key: 'render',\n value: function render() {\n var _this = this;\n\n this.totalPages = Math.ceil(this.props.dataSize / this.props.sizePerPage);\n var pageBtns = this.makePage();\n var pageListStyle = {\n float: \"right\",\n marginTop: \"0px\" //override the margin-top defined in .pagination class in bootstrap.\n };\n\n var sizePerPageList = this.props.sizePerPageList.map(function (sizePerPage) {\n return _react2['default'].createElement(\n 'li',\n { key: sizePerPage, role: 'presentation' },\n _react2['default'].createElement(\n 'a',\n { role: 'menuitem', tabIndex: '-1', href: '#', onClick: _this.changeSizePerPage.bind(_this) },\n sizePerPage\n )\n );\n });\n\n return _react2['default'].createElement(\n 'div',\n { className: 'row', style: { marginTop: 15 } },\n this.props.sizePerPageList.length > 1 ? _react2['default'].createElement(\n 'div',\n null,\n _react2['default'].createElement(\n 'div',\n { className: 'col-md-6' },\n _react2['default'].createElement(\n 'div',\n { className: 'dropdown' },\n _react2['default'].createElement(\n 'button',\n { className: 'btn btn-default dropdown-toggle', type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown',\n 'aria-expanded': 'true' },\n this.props.sizePerPage,\n _react2['default'].createElement(\n 'span',\n null,\n \" \",\n _react2['default'].createElement('span', { className: 'caret' })\n )\n ),\n _react2['default'].createElement(\n 'ul',\n { className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' },\n sizePerPageList\n )\n )\n ),\n _react2['default'].createElement(\n 'div',\n { className: 'col-md-6' },\n _react2['default'].createElement(\n 'ul',\n { className: 'pagination', style: pageListStyle },\n pageBtns\n )\n )\n ) : _react2['default'].createElement(\n 'div',\n { className: 'col-md-12' },\n _react2['default'].createElement(\n 'ul',\n { className: 'pagination', style: pageListStyle },\n pageBtns\n )\n )\n );\n }\n }, {\n key: 'makePage',\n value: function makePage() {\n var pages = this.getPages();\n return pages.map(function (page) {\n var isActive = page === this.props.currPage;\n var disabled = false;\n var hidden = false;\n if (this.props.currPage == 1 && (page === this.props.firstPage || page === this.props.prePage)) {\n disabled = true;\n hidden = true;\n }\n if (this.props.currPage == this.totalPages && (page === this.props.nextPage || page === this.props.lastPage)) {\n disabled = true;\n hidden = true;\n }\n return _react2['default'].createElement(\n _PageButtonJs2['default'],\n { changePage: this.changePage.bind(this), active: isActive, disable: disabled, hidden: hidden, key: page },\n page\n );\n }, this);\n }\n }, {\n key: 'getPages',\n value: function getPages() {\n var startPage = 1,\n endPage = this.totalPages;\n\n startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), 1);\n endPage = startPage + this.props.paginationSize - 1;\n\n if (endPage > this.totalPages) {\n endPage = this.totalPages;\n startPage = endPage - this.props.paginationSize + 1;\n }\n var pages;\n if (startPage != 1 && this.totalPages > this.props.paginationSize) {\n pages = [this.props.firstPage, this.props.prePage];\n } else if (this.totalPages > 1) {\n pages = [this.props.prePage];\n } else {\n pages = [];\n }\n for (var i = startPage; i <= endPage; i++) {\n if (i > 0) pages.push(i);\n }\n if (endPage != this.totalPages) {\n pages.push(this.props.nextPage);\n pages.push(this.props.lastPage);\n } else if (this.totalPages > 1) {\n pages.push(this.props.nextPage);\n }\n return pages;\n }\n }]);\n\n return PaginationList;\n})(_react2['default'].Component);\n\nPaginationList.propTypes = {\n currPage: _react2['default'].PropTypes.number,\n sizePerPage: _react2['default'].PropTypes.number,\n dataSize: _react2['default'].PropTypes.number,\n changePage: _react2['default'].PropTypes.func,\n sizePerPageList: _react2['default'].PropTypes.array,\n paginationSize: _react2['default'].PropTypes.number,\n remote: _react2['default'].PropTypes.bool,\n onSizePerPageList: _react2['default'].PropTypes.func,\n prePage: _react2['default'].PropTypes.string\n};\n\nPaginationList.defaultProps = {\n sizePerPage: _Const2['default'].SIZE_PER_PAGE\n};\n\nexports['default'] = PaginationList;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvcGFnaW5hdGlvbi9QYWdpbmF0aW9uTGlzdC5qcz81N2U5Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7aUNBQWtCLENBQU87Ozs7d0NBQ0YsRUFBaUI7Ozs7aUNBQ3RCLENBQVU7Ozs7SUFFdEIsY0FBYztZQUFkLGNBQWM7O1dBQWQsY0FBYzswQkFBZCxjQUFjOzsrQkFBZCxjQUFjOzs7ZUFBZCxjQUFjOztXQUVSLG9CQUFDLElBQUksRUFBRTtBQUNmLFVBQUksSUFBSSxJQUFJLElBQUksQ0FBQyxLQUFLLENBQUMsT0FBTyxFQUFFO0FBQzlCLFlBQUksR0FBRyxJQUFJLENBQUMs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RhdGEtdG9nZ2xlPVwiZHJvcGRvd25cIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFyaWEtZXhwYW5kZWQ9XCJ0cnVlXCI+XG4gICAgICAgICAgICAgICAgICAgICAge3RoaXMucHJvcHMuc2l6ZVBlclBhZ2V9XG4gICAgICAgICAgICAgICAgICAgICAgPHNwYW4+XG4gICAgICAgICAgICAgICAgICAgICAgICB7XCIgXCJ9XG4gICAgICAgICAgICAgICAgICAgICAgICA8c3BhbiBjbGFzc05hbWU9XCJjYXJldFwiLz5cbiAgICAgICAgICAgICAgICAgICAgICA8L3NwYW4+XG4gICAgICAgICAgICAgICAgICAgIDwvYnV0dG9uPlxuICAgICAgICAgICAgICAgICAgICA8dWwgY2xhc3NOYW1lPVwiZHJvcGRvd24tbWVudVwiIHJvbGU9XCJtZW51XCIgYXJpYS1sYWJlbGxlZGJ5PVwicGFnZURyb3BEb3duXCI+XG4gICAgICAgICAgICAgICAgICAgICAge3NpemVQZXJQYWdlTGlzdH1cbiAgICAgICAgICAgICAgICAgICAgPC91bD5cbiAgICAgICAgICAgICAgICAgIDwvZGl2PlxuICAgICAgICAgICAgICAgIDwvZGl2PlxuICAgICAgICAgICAgICAgIDxkaXYgY2xhc3NOYW1lPVwiY29sLW1kLTZcIj5cbiAgICAgICAgICAgICAgICAgIDx1bCBjbGFzc05hbWU9XCJwYWdpbmF0aW9uXCIgc3R5bGU9e3BhZ2VMaXN0U3R5bGV9PlxuICAgICAgICAgICAgICAgICAgICB7cGFnZUJ0bnN9XG4gICAgICAgICAgICAgICAgICA8L3VsPlxuICAgICAgICAgICAgICAgIDwvZGl2PlxuICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICA6IDxkaXYgY2xhc3NOYW1lPVwiY29sLW1kLTEyXCI+XG4gICAgICAgICAgICAgIDx1bCBjbGFzc05hbWU9XCJwYWdpbmF0aW9uXCIgc3R5bGU9e3BhZ2VMaXN0U3R5bGV9PlxuICAgICAgICAgICAgICAgI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5uZXh0UGFnZSk7XG4gICAgICBwYWdlcy5wdXNoKHRoaXMucHJvcHMubGFzdFBhZ2UpO1xuICAgIH0gZWxzZSBpZiAodGhpcy50b3RhbFBhZ2VzID4gMSl7XG4gICAgICBwYWdlcy5wdXNoKHRoaXMucHJvcHMubmV4dFBhZ2UpO1xuICAgIH1cbiAgICByZXR1cm4gcGFnZXM7XG4gIH1cbn1cblBhZ2luYXRpb25MaXN0LnByb3BUeXBlcyA9IHtcbiAgY3VyclBhZ2U6IFJlYWN0LlByb3BUeXBlcy5udW1iZXIsXG4gIHNpemVQZXJQYWdlOiBSZWFjdC5Qcm9wVHlwZXMubnVtYmVyLFxuICBkYXRhU2l6ZTogUmVhY3QuUHJvcFR5cGVzLm51bWJlcixcbiAgY2hhbmdlUGFnZTogUmVhY3QuUHJvcFR5cGVzLmZ1bmMsXG4gIHNpemVQZXJQYWdlTGlzdDogUmVhY3QuUHJvcFR5cGVzLmFycmF5LFxuICBwYWdpbmF0aW9uU2l6ZTogUmVhY3QuUHJvcFR5cGVzLm51bWJlcixcbiAgcmVtb3RlOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbCxcbiAgb25TaXplUGVyUGFnZUxpc3Q6IFJlYWN0LlByb3BUeXBlcy5mdW5jLFxuICBwcmVQYWdlOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nXG59O1xuXG5QYWdpbmF0aW9uTGlzdC5kZWZhdWx0UHJvcHMgPSB7XG4gIHNpemVQZXJQYWdlOiBDb25zdC5TSVpFX1BFUl9QQUdFXG59O1xuXG5leHBvcnQgZGVmYXVsdCBQYWdpbmF0aW9uTGlzdDtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL3BhZ2luYXRpb24vUGFnaW5hdGlvbkxpc3QuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar PageButton = (function (_React$Component) {\n _inherits(PageButton, _React$Component);\n\n function PageButton(props) {\n _classCallCheck(this, PageButton);\n\n _get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props);\n }\n\n _createClass(PageButton, [{\n key: 'pageBtnClick',\n value: function pageBtnClick(e) {\n e.preventDefault();\n this.props.changePage(e.currentTarget.textContent);\n }\n }, {\n key: 'render',\n value: function render() {\n var classes = (0, _classnames2['default'])({\n 'active': this.props.active,\n 'disabled': this.props.disable,\n 'hidden': this.props.hidden\n });\n return _react2['default'].createElement(\n 'li',\n { className: classes },\n _react2['default'].createElement(\n 'a',\n { href: '#', onClick: this.pageBtnClick.bind(this) },\n this.props.children\n )\n );\n }\n }]);\n\n return PageButton;\n})(_react2['default'].Component);\n\nPageButton.propTypes = {\n changePage: _react2['default'].PropTypes.func,\n active: _react2['default'].PropTypes.bool,\n disable: _react2['default'].PropTypes.bool\n};\n\nexports['default'] = PageButton;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvcGFnaW5hdGlvbi9QYWdlQnV0dG9uLmpzPzU0NGYiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztzQ0FDSixDQUFZOzs7O0lBRTNCLFVBQVU7WUFBVixVQUFVOztBQUVILFdBRlAsVUFBVSxDQUVGLEtBQUssRUFBRTswQkFGZixVQUFVOztBQUdkLCtCQUhJLFVBQVUsNkNBR1IsS0FBSyxFQUFFO0dBQ2I7O2VBSkksVUFBVTs7V0FNRixzQkFBQyxDQUFDLEVBQUM7QUFDYixPQUFDLENBQUMsY0FBYyxFQUFFLENBQUM7QUFDbkIsVUFBSSxDQUFDLEtBQUssQ0FBQyxVQUFVLENBQUMsQ0FBQyxDQUFDLGFBQWEsQ0FBQyxXQUFXLENBQUMsQ0FBQztLQUNwRDs7O1dBRUssa0JBQUU7QUFDTixVQUFJLE9BQU8sR0FBRyw2QkFBUztBQUNuQixnQkFBUSxFQUFFLElBQUksQ0FBQyxLQUFLLENBQUMsTUFBTTtBQUMzQixrQkFBVSxFQUFFLElBQUksQ0FBQyxLQUFLLENBQUMsT0FBTztBQUM5QixnQkFB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AgICdkaXNhYmxlZCc6IHRoaXMucHJvcHMuZGlzYWJsZSxcbiAgICAgICAgJ2hpZGRlbic6IHRoaXMucHJvcHMuaGlkZGVuXG4gICAgfSk7XG4gICAgcmV0dXJuIChcbiAgICAgICAgPGxpIGNsYXNzTmFtZT17Y2xhc3Nlc30+PGEgaHJlZj1cIiNcIiBvbkNsaWNrPXt0aGlzLnBhZ2VCdG5DbGljay5iaW5kKHRoaXMpfT57dGhpcy5wcm9wcy5jaGlsZHJlbn08L2E+PC9saT5cbiAgICApXG4gIH1cbn1cblBhZ2VCdXR0b24ucHJvcFR5cGVzID0ge1xuICBjaGFuZ2VQYWdlOiBSZWFjdC5Qcm9wVHlwZXMuZnVuYyxcbiAgYWN0aXZlOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbCxcbiAgZGlzYWJsZTogUmVhY3QuUHJvcFR5cGVzLmJvb2xcbn07XG5cbmV4cG9ydCBkZWZhdWx0IFBhZ2VCdXR0b247XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9wYWdpbmF0aW9uL1BhZ2VCdXR0b24uanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _Editor = __webpack_require__(13);\n\nvar _Editor2 = _interopRequireDefault(_Editor);\n\nvar _NotificationJs = __webpack_require__(14);\n\nvar _NotificationJs2 = _interopRequireDefault(_NotificationJs);\n\nvar ToolBar = (function (_React$Component) {\n _inherits(ToolBar, _React$Component);\n\n function ToolBar(props) {\n var _this = this;\n\n _classCallCheck(this, ToolBar);\n\n _get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props);\n\n this.handleShowOnlyToggle = function (e) {\n _this.setState({\n showSelected: !_this.state.showSelected\n });\n _this.props.onShowOnlySelected();\n };\n\n this.handleClearBtnClick = function () {\n _this.refs.seachInput.value = '';\n _this.props.onSearch('');\n };\n\n this.timeouteClear = 0;\n this.modalClassName;\n this.state = {\n isInsertRowTrigger: true,\n validateState: null,\n shakeEditor: false,\n showSelected: false\n };\n }\n\n _createClass(ToolBar, [{\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n this.clearTimeout();\n }\n }, {\n key: 'clearTimeout',\n value: (function (_clearTimeout) {\n function clearTimeout() {\n return _clearTimeout.apply(this, arguments);\n }\n\n clearTimeout.toString = function () {\n return _clearTimeout.toString();\n };\n\n return clearTimeout;\n })(function () {\n if (this.timeouteClear) {\n clearTimeout(this.timeouteClear);\n this.timeouteClear = 0;\n }\n })\n }, {\n key: 'checkAndParseForm',\n value: function checkAndParseForm() {\n var ts = this,\n newObj = {},\n isValid = true,\n tempValue,\n tempMsg,\n validateState = {};\n this.props.columns.forEach(function (column, i) {\n if (column.autoValue) {\n //when you want same auto generate value and not allow edit, example ID field\n tempValue = typeof column.autoValue == 'function' ? column.autoValue() : 'autovalue-' + new Date().getTime();\n } else {\n var dom = this.refs[column.field + i];\n tempValue = dom.value;\n\n if (column.editable && column.editable.type == 'checkbox') {\n var values = dom.value.split(':');\n tempValue = dom.checked ? values[0] : values[1];\n }\n\n if (column.editable && column.editable.validator) {\n //process validate\n tempMsg = column.editable.validator(tempValue);\n if (tempMsg !== true) {\n isValid = false;\n validateState[column.field] = tempMsg;\n }\n }\n }\n\n newObj[column.field] = tempValue;\n }, this);\n\n if (isValid) {\n return newObj;\n } else {\n ts.clearTimeout();\n //show error in form and shake it\n this.setState({ validateState: validateState, shakeEditor: true });\n //notifier error\n ts.refs.notifier.notice('error', \"Form validate errors, please checking!\", \"Pressed ESC can cancel\");\n //clear animate class\n ts.timeouteClear = setTimeout(function () {\n ts.setState({ shakeEditor: false });\n }, 300);\n return null;\n }\n }\n }, {\n key: 'handleSaveBtnClick',\n value: function handleSaveBtnClick(e) {\n var _this2 = this;\n\n var newObj = this.checkAndParseForm();\n if (!newObj) {\n //validate errors\n return;\n }\n var msg = this.props.onAddRow(newObj);\n if (msg) {\n var ts = this;\n ts.refs.notifier.notice('error', msg, \"Pressed ESC can cancel\");\n ts.clearTimeout();\n //shake form and hack prevent modal hide\n ts.setState({ shakeEditor: true, validateState: \"this is hack for prevent bootstrap modal hide\" });\n //clear animate class\n ts.timeouteClear = setTimeout(function () {\n ts.setState({ shakeEditor: false });\n }, 300);\n } else {\n //reset state and hide modal hide\n this.setState({\n validateState: null,\n shakeEditor: false\n }, function () {\n document.querySelector(\".\" + \"modal-backdrop\").click();\n document.querySelector(\".\" + _this2.modalClassName).click();\n });\n //reset form\n this.refs.form.reset();\n }\n }\n }, {\n key: 'handleDropRowBtnClick',\n value: function handleDropRowBtnClick(e) {\n this.props.onDropRow();\n }\n }, {\n key: 'handleCloseBtn',\n value: function handleCloseBtn(e) {\n this.refs.warning.style.display = \"none\";\n }\n }, {\n key: 'handleKeyUp',\n value: function handleKeyUp(e) {\n this.props.onSearch(e.currentTarget.value);\n }\n }, {\n key: 'handleExportCSV',\n value: function handleExportCSV() {\n this.props.onExportCSV();\n }\n }, {\n key: 'render',\n value: function render() {\n this.modalClassName = \"bs-table-modal-sm\" + new Date().getTime();\n var insertBtn = this.props.enableInsert ? _react2['default'].createElement(\n 'button',\n { type: 'button', onClick: this.props.onAddRowBegin, className: 'btn btn-info react-bs-table-add-btn', 'data-toggle': 'modal', 'data-target': '.' + this.modalClassName },\n _react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }),\n ' New'\n ) : null;\n\n var deleteBtn = this.props.enableDelete ? _react2['default'].createElement(\n 'button',\n { type: 'button', className: 'btn btn-warning react-bs-table-del-btn', 'data-toggle': 'tooltip', 'data-placement': 'right', title: 'Drop selected row',\n onClick: this.handleDropRowBtnClick.bind(this) },\n _react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }),\n ' Delete'\n ) : null;\n\n var searchTextInput = this.renderSearchPanel();\n\n var showSelectedOnlyBtn = this.props.enableShowOnlySelected ? _react2['default'].createElement(\n 'button',\n { type: 'button', onClick: this.handleShowOnlyToggle.bind(this), className: 'btn btn-primary', 'data-toggle': 'button', 'aria-pressed': 'false' },\n this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT\n ) : null;\n\n var modal = this.props.enableInsert ? this.renderInsertRowModal() : null;\n var warningStyle = {\n display: \"none\",\n marginBottom: 0\n };\n\n var exportCSV = this.props.enableExportCSV ? _react2['default'].createElement(\n 'button',\n { type: 'button', className: 'btn btn-success', onClick: this.handleExportCSV.bind(this) },\n _react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }),\n ' Export to CSV'\n ) : null;\n\n return _react2['default'].createElement(\n 'div',\n { className: 'row' },\n _react2['default'].createElement(\n 'div',\n { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' },\n _react2['default'].createElement(\n 'div',\n { className: 'btn-group btn-group-sm', role: 'group' },\n exportCSV,\n insertBtn,\n deleteBtn,\n showSelectedOnlyBtn\n )\n ),\n _react2['default'].createElement(\n 'div',\n { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' },\n searchTextInput\n ),\n _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }),\n modal\n );\n }\n }, {\n key: 'renderSearchPanel',\n value: function renderSearchPanel() {\n if (this.props.enableSearch) {\n var classNames = 'form-group form-group-sm react-bs-table-search-form';\n var clearBtn = null;\n if (this.props.clearSearch) {\n clearBtn = _react2['default'].createElement(\n 'span',\n { className: 'input-group-btn' },\n _react2['default'].createElement(\n 'button',\n {\n className: 'btn btn-default',\n type: 'button',\n onClick: this.handleClearBtnClick },\n 'Clear'\n )\n );\n classNames += ' input-group input-group-sm';\n }\n\n return _react2['default'].createElement(\n 'div',\n { className: classNames },\n _react2['default'].createElement('input', { ref: 'seachInput', className: 'form-control', type: 'text',\n placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search',\n onKeyUp: this.handleKeyUp.bind(this) }),\n clearBtn\n );\n } else {\n return null;\n }\n }\n }, {\n key: 'renderInsertRowModal',\n value: function renderInsertRowModal() {\n var validateState = this.state.validateState || {};\n var inputField = this.props.columns.map(function (column, i) {\n var editable = column.editable,\n format = column.format,\n attr = { ref: column.field + i, placeholder: editable.placeholder ? editable.placeholder : column.name };\n\n if (column.autoValue) {\n //when you want same auto generate value and not allow edit, example ID field\n return null;\n }\n var error = validateState[column.field] ? _react2['default'].createElement(\n 'span',\n { className: 'help-block bg-danger' },\n validateState[column.field]\n ) : null;\n\n // let editor = Editor(editable,attr,format);\n // if(editor.props.type && editor.props.type == 'checkbox'){\n return _react2['default'].createElement(\n 'div',\n { className: 'form-group', key: column.field },\n _react2['default'].createElement(\n 'label',\n null,\n column.name\n ),\n (0, _Editor2['default'])(editable, attr, format, ''),\n error\n );\n });\n var modalClass = (0, _classnames2['default'])(\"modal\", \"fade\", this.modalClassName, {\n 'in': this.state.shakeEditor || this.state.validateState //hack prevent bootstrap modal hide by reRender\n });\n var dialogClass = (0, _classnames2['default'])(\"modal-dialog\", \"modal-sm\", {\n \"animated\": this.state.shakeEditor,\n \"shake\": this.state.shakeEditor\n });\n return _react2['default'].createElement(\n 'div',\n { ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' },\n _react2['default'].createElement(\n 'div',\n { className: dialogClass },\n _react2['default'].createElement(\n 'div',\n { className: 'modal-content' },\n _react2['default'].createElement(\n 'div',\n { className: 'modal-header' },\n _react2['default'].createElement(\n 'button',\n { type: 'button', className: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' },\n _react2['default'].createElement(\n 'span',\n { 'aria-hidden': 'true' },\n '×'\n )\n ),\n _react2['default'].createElement(\n 'h4',\n { className: 'modal-title' },\n 'New Record'\n )\n ),\n _react2['default'].createElement(\n 'div',\n { className: 'modal-body' },\n _react2['default'].createElement(\n 'form',\n { ref: 'form' },\n inputField\n )\n ),\n _react2['default'].createElement(\n 'div',\n { className: 'modal-footer' },\n _react2['default'].createElement(\n 'button',\n { type: 'button', className: 'btn btn-default', 'data-dismiss': 'modal' },\n 'Close'\n ),\n _react2['default'].createElement(\n 'button',\n { type: 'button', className: 'btn btn-info', onClick: this.handleSaveBtnClick.bind(this) },\n 'Save'\n )\n )\n )\n )\n );\n }\n }]);\n\n return ToolBar;\n})(_react2['default'].Component);\n\nToolBar.propTypes = {\n onAddRow: _react2['default'].PropTypes.func,\n onDropRow: _react2['default'].PropTypes.func,\n onShowOnlySelected: _react2['default'].PropTypes.func,\n enableInsert: _react2['default'].PropTypes.bool,\n enableDelete: _react2['default'].PropTypes.bool,\n enableSearch: _react2['default'].PropTypes.bool,\n enableShowOnlySelected: _react2['default'].PropTypes.bool,\n columns: _react2['default'].PropTypes.array,\n searchPlaceholder: _react2['default'].PropTypes.string,\n clearSearch: _react2['default'].PropTypes.bool\n};\n\nToolBar.defaultProps = {\n enableInsert: false,\n enableDelete: false,\n enableSearch: false,\n enableShowOnlySelected: false,\n clearSearch: false\n};\nexports['default'] = ToolBar;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvdG9vbGJhci9Ub29sQmFyLmpzPzZiZjgiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztzQ0FDSixDQUFZOzs7O2lDQUNmLENBQVU7Ozs7a0NBQ1QsRUFBVzs7OzswQ0FDVCxFQUFvQjs7OztJQUVuQyxPQUFPO1lBQVAsT0FBTzs7QUFFQSxXQUZQLE9BQU8sQ0FFQyxLQUFLLEVBQUU7OzswQkFGZixPQUFPOztBQUdYLCtCQUhJLE9BQU8sNkNBR0wsS0FBSyxFQUFFOztTQXdGYixvQkFBb0IsR0FBRyxXQUFDLEVBQUk7QUFDMUIsWUFBSyxRQUFRLENBQUM7QUFDWixvQkFBWSxFQUFFLENBQUMsTUFBSyxLQUFLLENBQUMsWUFBWTtPQUN2QyxDQUFDLENBQUM7QUFDSCxZQUFLLEtBQUssQ0FBQyxrQkFBa0IsRUFBRSxDQUFDO0tBQ2pDOztTQWtCRCxtQkFBbUIsR0FBRyxZQUFNO0FBQzFCLFlBQUssSUFBSSxDQUFDLFVBQVUsQ0FBQy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qcm9wVHlwZXMuc3RyaW5nLFxuICBjbGVhclNlYXJjaDogUmVhY3QuUHJvcFR5cGVzLmJvb2xcbn07XG5cblRvb2xCYXIuZGVmYXVsdFByb3BzID0ge1xuICBlbmFibGVJbnNlcnQ6IGZhbHNlLFxuICBlbmFibGVEZWxldGU6IGZhbHNlLFxuICBlbmFibGVTZWFyY2g6IGZhbHNlLFxuICBlbmFibGVTaG93T25seVNlbGVjdGVkOiBmYWxzZSxcbiAgY2xlYXJTZWFyY2g6IGZhbHNlXG59XG5leHBvcnQgZGVmYXVsdCBUb29sQmFyO1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvdG9vbGJhci9Ub29sQmFyLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar TableFilter = (function (_React$Component) {\n _inherits(TableFilter, _React$Component);\n\n function TableFilter(props) {\n _classCallCheck(this, TableFilter);\n\n _get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props);\n this.filterObj = {};\n }\n\n _createClass(TableFilter, [{\n key: 'handleKeyUp',\n value: function handleKeyUp(e) {\n if (e.currentTarget.value.trim() === \"\") delete this.filterObj[e.currentTarget.name];else this.filterObj[e.currentTarget.name] = e.currentTarget.value;\n\n this.props.onFilter(this.filterObj);\n }\n }, {\n key: 'render',\n value: function render() {\n var tableClasses = (0, _classnames2['default'])(\"table\", {\n 'table-striped': this.props.striped,\n 'table-condensed': this.props.condensed\n });\n var selectRowHeader = null;\n\n if (this.props.rowSelectType == _Const2['default'].ROW_SELECT_SINGLE || this.props.rowSelectType == _Const2['default'].ROW_SELECT_MULTI) {\n var style = {\n width: 35,\n paddingLeft: 0,\n paddingRight: 0\n };\n selectRowHeader = _react2['default'].createElement(\n 'th',\n { style: style, key: -1 },\n 'Filter'\n );\n }\n var filterField = this.props.columns.map(function (column) {\n var thStyle = {\n display: column.hidden ? \"none\" : null,\n width: column.width\n };\n return _react2['default'].createElement(\n 'th',\n { key: column.name, style: thStyle },\n _react2['default'].createElement(\n 'div',\n { className: 'th-inner table-header-column' },\n _react2['default'].createElement('input', { size: '10', type: 'text', placeholder: column.name, name: column.name, onKeyUp: this.handleKeyUp.bind(this) })\n )\n );\n }, this);\n return _react2['default'].createElement(\n 'table',\n { className: tableClasses, style: { marginTop: 5 } },\n _react2['default'].createElement(\n 'thead',\n null,\n _react2['default'].createElement(\n 'tr',\n { style: { borderBottomStyle: 'hidden' } },\n selectRowHeader,\n filterField\n )\n )\n );\n }\n }]);\n\n return TableFilter;\n})(_react2['default'].Component);\n\nTableFilter.propTypes = {\n columns: _react2['default'].PropTypes.array,\n rowSelectType: _react2['default'].PropTypes.string,\n onFilter: _react2['default'].PropTypes.func\n};\nexports['default'] = TableFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvVGFibGVGaWx0ZXIuanM/MWI2OCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O2lDQUNQLENBQVM7Ozs7c0NBQ04sQ0FBWTs7OztJQUUzQixXQUFXO1lBQVgsV0FBVzs7QUFFSixXQUZQLFdBQVcsQ0FFSCxLQUFLLEVBQUU7MEJBRmYsV0FBVzs7QUFHYiwrQkFIRSxXQUFXLDZDQUdQLEtBQUssRUFBRTtBQUNiLFFBQUksQ0FBQyxTQUFTLEdBQUcsRUFBRSxDQUFDO0dBQ3JCOztlQUxHLFdBQVc7O1dBT0oscUJBQUMsQ0FBQyxFQUFDO0FBQ1osVUFBRyxDQUFDLENBQUMsYUFBYSxDQUFDLEtBQUssQ0FBQyxJQUFJLEVBQUUsS0FBSyxFQUFFLEVBQ3BDLE9BQU8sSUFBSSxDQUFDLFNBQVMsQ0FBQyxDQUFDLENBQUMsYUFBYSxDQUFDLElBQUksQ0FBQyxDQUFDLEtBRTVDLElBQUksQ0FBQyxTQUFTLENBQUMsQ0FBQyxDQUFDLGFBQWEsQ0FBQyxJQUFJLENB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4gIHJvd1NlbGVjdFR5cGU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmcsXG4gIG9uRmlsdGVyOiBSZWFjdC5Qcm9wVHlwZXMuZnVuY1xufTtcbmV4cG9ydCBkZWZhdWx0IFRhYmxlRmlsdGVyO1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvVGFibGVGaWx0ZXIuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar EventEmitter = __webpack_require__(35).EventEmitter;\n\nfunction _sort(arr, sortField, order, sortFunc) {\n order = order.toLowerCase();\n arr.sort(function (a, b) {\n if (sortFunc) {\n return sortFunc(a, b, order, sortField);\n } else {\n if (order == _Const2['default'].SORT_DESC) {\n return a[sortField] > b[sortField] ? -1 : a[sortField] < b[sortField] ? 1 : 0;\n } else {\n return a[sortField] < b[sortField] ? -1 : a[sortField] > b[sortField] ? 1 : 0;\n }\n }\n });\n\n return arr;\n}\n\nvar TableDataSet = (function (_EventEmitter) {\n _inherits(TableDataSet, _EventEmitter);\n\n function TableDataSet(data) {\n _classCallCheck(this, TableDataSet);\n\n _get(Object.getPrototypeOf(TableDataSet.prototype), 'constructor', this).call(this, data);\n this.data = data;\n }\n\n _createClass(TableDataSet, [{\n key: 'setData',\n value: function setData(data) {\n this.emit('change', data);\n }\n }, {\n key: 'clear',\n value: function clear() {\n this.data = null;\n }\n }, {\n key: 'getData',\n value: function getData() {\n return this.data;\n }\n }]);\n\n return TableDataSet;\n})(EventEmitter);\n\nexports.TableDataSet = TableDataSet;\n\nvar TableDataStore = (function () {\n function TableDataStore(data) {\n _classCallCheck(this, TableDataStore);\n\n this.data = data;\n this.colInfos = null;\n this.filteredData = null;\n this.isOnFilter = false;\n this.filterObj = null;\n this.searchText = null;\n this.sortObj = null;\n this.pageObj = {};\n this.selected = [];\n this.multiColumnSearch = false;\n this.showOnlySelected = false;\n this.remote = false; // remote data\n }\n\n _createClass(TableDataStore, [{\n key: 'setProps',\n value: function setProps(props) {\n this.keyField = props.keyField;\n this.enablePagination = props.isPagination;\n this.colInfos = props.colInfos;\n this.remote = props.remote;\n this.multiColumnSearch = props.multiColumnSearch;\n }\n }, {\n key: 'setData',\n value: function setData(data) {\n this.data = data;\n if (this.isOnFilter) {\n if (null !== this.filterObj) this.filter(this.filterObj);\n if (null !== this.searchText) this.search(this.searchText);\n }\n if (this.sortObj) {\n this.sort(this.sortObj.order, this.sortObj.sortField);\n }\n }\n }, {\n key: 'getSortInfo',\n value: function getSortInfo() {\n return this.sortObj;\n }\n }, {\n key: 'setSelectedRowKey',\n value: function setSelectedRowKey(selectedRowKeys) {\n this.selected = selectedRowKeys;\n }\n }, {\n key: 'getSelectedRowKeys',\n value: function getSelectedRowKeys() {\n return this.selected;\n }\n }, {\n key: 'getCurrentDisplayData',\n value: function getCurrentDisplayData() {\n if (this.isOnFilter) return this.filteredData;else return this.data;\n }\n }, {\n key: 'ignoreNonSelected',\n value: function ignoreNonSelected() {\n var _this = this;\n\n this.showOnlySelected = !this.showOnlySelected;\n if (this.showOnlySelected) {\n this.isOnFilter = true;\n this.filteredData = this.data.filter(function (row) {\n var result = _this.selected.find(function (x) {\n return row[_this.keyField] === x;\n });\n return typeof result !== 'undefined' ? true : false;\n });\n } else {\n this.isOnFilter = false;\n }\n }\n }, {\n key: 'sort',\n value: function sort(order, sortField) {\n this.sortObj = {\n order: order,\n sortField: sortField\n };\n\n var currentDisplayData = this.getCurrentDisplayData();\n if (!this.colInfos[sortField]) return this;\n\n var sortFunc = this.colInfos[sortField].sortFunc;\n\n currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc);\n\n return this;\n }\n }, {\n key: 'page',\n value: function page(_page, sizePerPage) {\n this.pageObj.end = _page * sizePerPage - 1;\n this.pageObj.start = this.pageObj.end - (sizePerPage - 1);\n return this;\n }\n }, {\n key: 'edit',\n value: function edit(newVal, rowIndex, fieldName) {\n var currentDisplayData = this.getCurrentDisplayData();\n var rowKeyCache = undefined;\n if (!this.enablePagination) {\n currentDisplayData[rowIndex][fieldName] = newVal;\n rowKeyCache = currentDisplayData[rowIndex][this.keyField];\n } else {\n currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal;\n rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField];\n }\n if (this.isOnFilter) {\n this.data.forEach(function (row) {\n if (row[this.keyField] === rowKeyCache) {\n row[fieldName] = newVal;\n }\n }, this);\n if (null !== this.filterObj) this.filter(this.filterObj);\n if (null !== this.searchText) this.search(this.searchText);\n }\n return this;\n }\n }, {\n key: 'addAtBegin',\n value: function addAtBegin(newObj) {\n if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {\n throw this.keyField + \" can't be empty value.\";\n }\n var currentDisplayData = this.getCurrentDisplayData();\n currentDisplayData.forEach(function (row) {\n if (row[this.keyField].toString() === newObj[this.keyField].toString()) {\n throw this.keyField + \" \" + newObj[this.keyField] + \" already exists\";\n }\n }, this);\n currentDisplayData.unshift(newObj);\n if (this.isOnFilter) {\n this.data.unshift(newObj);\n }\n }\n }, {\n key: 'add',\n value: function add(newObj) {\n if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {\n throw this.keyField + \" can't be empty value.\";\n }\n var currentDisplayData = this.getCurrentDisplayData();\n currentDisplayData.forEach(function (row) {\n if (row[this.keyField].toString() === newObj[this.keyField].toString()) {\n throw this.keyField + \" \" + newObj[this.keyField] + \" already exists\";\n }\n }, this);\n\n currentDisplayData.push(newObj);\n if (this.isOnFilter) {\n this.data.push(newObj);\n }\n }\n }, {\n key: 'remove',\n value: function remove(rowKey) {\n var currentDisplayData = this.getCurrentDisplayData();\n var result = currentDisplayData.filter(function (row) {\n return rowKey.indexOf(row[this.keyField]) == -1;\n }, this);\n\n if (this.isOnFilter) {\n this.data = this.data.filter(function (row) {\n return rowKey.indexOf(row[this.keyField]) == -1;\n }, this);\n this.filteredData = result;\n } else {\n this.data = result;\n }\n }\n }, {\n key: 'filter',\n value: function filter(filterObj) {\n var _this2 = this;\n\n if (Object.keys(filterObj).length == 0) {\n this.filteredData = null;\n this.isOnFilter = false;\n this.filterObj = null;\n if (null !== this.searchText) this.search(this.searchText);\n } else {\n this.filterObj = filterObj;\n this.filteredData = this.data.filter(function (row) {\n var valid = true;\n var filterVal = undefined;\n for (var key in filterObj) {\n var targetVal = row[key];\n\n switch (filterObj[key].type) {\n case _Const2['default'].FILTER_TYPE.NUMBER:\n {\n filterVal = filterObj[key].value.number;\n break;\n }\n case _Const2['default'].FILTER_TYPE.CUSTOM:\n {\n filterVal = typeof filterObj[key].value === \"object\" ? undefined : typeof filterObj[key].value === \"string\" ? filterObj[key].value.toLowerCase() : filterObj[key].value;\n break;\n }\n case _Const2['default'].FILTER_TYPE.REGEX:\n {\n filterVal = filterObj[key].value;\n break;\n }\n default:\n {\n filterVal = typeof filterObj[key].value === \"string\" ? filterObj[key].value.toLowerCase() : filterObj[key].value;\n if (filterVal === undefined) {\n // Support old filter\n filterVal = filterObj[key].toLowerCase();\n }\n break;\n }\n }\n\n if (_this2.colInfos[key]) {\n var _colInfos$key = _this2.colInfos[key];\n var format = _colInfos$key.format;\n var filterFormatted = _colInfos$key.filterFormatted;\n var formatExtraData = _colInfos$key.formatExtraData;\n\n if (filterFormatted && format) {\n targetVal = format(row[key], row, formatExtraData);\n }\n }\n\n switch (filterObj[key].type) {\n case _Const2['default'].FILTER_TYPE.NUMBER:\n {\n valid = _this2.filterNumber(targetVal, filterVal, filterObj[key].value.comparator);\n break;\n }\n case _Const2['default'].FILTER_TYPE.DATE:\n {\n valid = _this2.filterDate(targetVal, filterVal);\n break;\n }\n case _Const2['default'].FILTER_TYPE.REGEX:\n {\n valid = _this2.filterRegex(targetVal, filterVal);\n break;\n }\n case _Const2['default'].FILTER_TYPE.CUSTOM:\n {\n valid = _this2.filterCustom(targetVal, filterVal, filterObj[key].value);\n break;\n }\n default:\n {\n valid = _this2.filterText(targetVal, filterVal);\n break;\n }\n }\n if (!valid) {\n break;\n }\n }\n return valid;\n });\n this.isOnFilter = true;\n }\n }\n }, {\n key: 'filterNumber',\n value: function filterNumber(targetVal, filterVal, comparator) {\n var valid = true;\n switch (comparator) {\n case \"=\":\n {\n if (targetVal != filterVal) {\n valid = false;\n }\n break;\n }\n case \">\":\n {\n if (targetVal <= filterVal) {\n valid = false;\n }\n break;\n }\n case \">=\":\n {\n if (targetVal < filterVal) {\n valid = false;\n }\n break;\n }\n case \"<\":\n {\n if (targetVal >= filterVal) {\n valid = false;\n }\n break;\n }\n case \"<=\":\n {\n if (targetVal > filterVal) {\n valid = false;\n }\n break;\n }\n case \"!=\":\n {\n if (targetVal == filterVal) {\n valid = false;\n }\n break;\n }\n default:\n {\n console.error(\"Number comparator provided is not supported\");\n break;\n }\n }\n return valid;\n }\n }, {\n key: 'filterDate',\n value: function filterDate(targetVal, filterVal) {\n return targetVal.getDate() == filterVal.getDate() && targetVal.getMonth() == filterVal.getMonth() && targetVal.getFullYear() == filterVal.getFullYear();\n }\n }, {\n key: 'filterRegex',\n value: function filterRegex(targetVal, filterVal) {\n try {\n return new RegExp(filterVal, 'i').test(targetVal);\n } catch (e) {\n console.error('Invalid regular expression');\n return true;\n }\n }\n }, {\n key: 'filterCustom',\n value: function filterCustom(targetVal, filterVal, callbackInfo) {\n if (callbackInfo != null && typeof callbackInfo === \"object\") {\n return callbackInfo.callback(targetVal, callbackInfo.callbackParameters);\n }\n\n return filterText(targetVal, filterVal);\n }\n }, {\n key: 'filterText',\n value: function filterText(targetVal, filterVal) {\n if (targetVal.toString().toLowerCase().indexOf(filterVal) == -1) {\n return false;\n }\n\n return true;\n }\n\n /* General search function\n * It will search for the text if the input includes that text;\n */\n }, {\n key: 'search',\n value: function search(searchText) {\n var _this3 = this;\n\n if (searchText.trim() === \"\") {\n this.filteredData = null;\n this.isOnFilter = false;\n this.searchText = null;\n if (null !== this.filterObj) this.filter(this.filterObj);\n } else {\n (function () {\n _this3.searchText = searchText;\n var searchTextArray = [];\n\n if (_this3.multiColumnSearch) {\n searchTextArray = searchText.split(' ');\n } else {\n searchTextArray.push(searchText);\n }\n\n var source = _this3.isOnFilter ? _this3.filteredData : _this3.data;\n\n _this3.filteredData = source.filter(function (row) {\n var keys = Object.keys(row);\n var valid = false;\n // for loops are ugly, but performance matters here.\n // And you cant break from a forEach.\n // http://jsperf.com/for-vs-foreach/66\n for (var i = 0, keysLength = keys.length; i < keysLength; i++) {\n var key = keys[i];\n if (_this3.colInfos[key] && row[key]) {\n var _colInfos$key2 = _this3.colInfos[key];\n var format = _colInfos$key2.format;\n var filterFormatted = _colInfos$key2.filterFormatted;\n var formatExtraData = _colInfos$key2.formatExtraData;\n var searchable = _colInfos$key2.searchable;\n var hidden = _colInfos$key2.hidden;\n\n var targetVal = row[key];\n if (searchable) {\n if (filterFormatted && format) {\n targetVal = format(targetVal, row, formatExtraData);\n }\n for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) {\n var filterVal = searchTextArray[j].toLowerCase();\n if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) {\n valid = true;\n break;\n }\n }\n }\n }\n }\n return valid;\n });\n _this3.isOnFilter = true;\n })();\n }\n }\n }, {\n key: 'getDataIgnoringPagination',\n value: function getDataIgnoringPagination() {\n var _data = this.getCurrentDisplayData();\n return _data;\n }\n }, {\n key: 'get',\n value: function get() {\n var _data = this.getCurrentDisplayData();\n\n if (_data.length == 0) return _data;\n\n if (this.remote || !this.enablePagination) {\n return _data;\n } else {\n var result = [];\n for (var i = this.pageObj.start; i <= this.pageObj.end; i++) {\n result.push(_data[i]);\n if (i + 1 == _data.length) break;\n }\n return result;\n }\n }\n }, {\n key: 'getKeyField',\n value: function getKeyField() {\n return this.keyField;\n }\n }, {\n key: 'getDataNum',\n value: function getDataNum() {\n return this.getCurrentDisplayData().length;\n }\n }, {\n key: 'isChangedPage',\n value: function isChangedPage() {\n return this.pageObj.start && this.pageObj.end ? true : false;\n }\n }, {\n key: 'getAllRowkey',\n value: function getAllRowkey() {\n return this.data.map(function (row) {\n return row[this.keyField];\n }, this);\n }\n }]);\n\n return TableDataStore;\n})();\n\nexports.TableDataStore = TableDataStore;\n\n;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvc3RvcmUvVGFibGVEYXRhU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ICAgZmlsdGVyVmFsID0gZmlsdGVyT2JqW2tleV0udmFsdWUubnVtYmVyO1xuICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGNhc2UgQ29uc3QuRklMVEVSX1RZUEUuQ1VTVE9NOlxuICAgICAgICAgICAge1xuICAgICAgICAgICAgICBmaWx0ZXJWYWwgPSAodHlwZW9mIGZpbHRlck9ialtrZXldLnZhbHVlID09PSBcIm9iamVjdFwiKSA/XG4gICAgICAgICAgICAgICAgICB1bmRlZmluZWQgOlxuICAgICAgICAgICAgICAgICAgKHR5cGVvZiBmaWx0ZXJPYmpba2V5XS52YWx1ZSA9PT0gXCJzdHJpbmdcIikgPyBmaWx0ZXJPYmpba2V5XS52YWx1ZS50b0xvd2VyQ2FzZSgpIDogZmlsdGVyT2JqW2tleV0udmFsdWU7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgY2FzZSBDb25zdC5GSUxURVJfVFlQRS5SRUdFWDpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgZmlsdGVyVmFsID0gZmlsdGVyT2JqW2tleV0udmFsdWU7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZGVmYXVsdDoge1xuICAgICAgICAgICAgICBmaWx0ZXJWYWwgPSAodHlwZW9mIGZpbHRlck9ialtrZXldLnZhbHVlID09PSBcInN0cmluZ1wiKSA/IGZpbHRlck9ialtrZXldLnZhbHVlLnRvTG93ZXJDYXNlKCkgOiBmaWx0ZXJPYmpba2V5XS52YWx1ZTtcbiAgICAgICAgICAgICAgaWYgKGZpbHRlclZhbCA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgLy8gU3VwcG9ydCBvbGQgZmlsdGVyXG4gICAgICAgICAgICAgICAgZmlsdGVyVmFsID0gZmlsdGVyT2JqW2tleV0udG9Mb3dlckNhc2UoKTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG5cbiAgICAgICAgICBpZiAodGhpcy5jb2xJbmZvc1trZXldKSB7XG4gICAgICAgICAgICBjb25zdCB7IGZvcm1hdCwgZmlsdGVyRm9ybWF0dGVkLCBmb3JtYXRFeHRyYURhdGEgfSA9IHRoaXMuY29sSW5mb3Nba2V5XTtcbiAgICAgICAgICAgIGlmKGZpbHRlckZvcm1hdHRlZCAmJiBmb3JtYXQpIHtcbiAgICAgICAgICAgICAgdGFyZ2V0VmFsID0gZm9ybWF0KHJvd1trZXldLCByb3csIGZvcm1hdEV4dHJhRGF0YSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgc3dpdGNoIChmaWx0ZXJPYmpba2V5XS50eXBlKSB7XG4gICAgICAgICAgICBjYXNlIENvbnN0LkZJTFRFUl9UWVBFLk5VTUJFUjpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgdmFsaWQgPSB0aGlzLmZpbHRlck51bWJlcih0YXJnZXRWYWwsIGZpbHRlclZhbCwgZmlsdGVyT2JqW2tleV0udmFsdWUuY29tcGFyYXRvcik7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgY2FzZSBDb25zdC5GSUxURVJfVFlQRS5EQVRFOlxuICAgICAgICAgICAge1xuICAgICAgICAgICAgICB2YWxpZCA9IHRoaXMuZmlsdGVyRGF0ZSh0YXJnZXRWYWwsIGZpbHRlclZhbCk7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgY2FzZSBDb25zdC5GSUxURVJfVFlQRS5SRUdFWDpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgdmFsaWQgPSB0aGlzLmZpbHRlclJlZ2V4KHRhcmdldFZhbCwgZmlsdGVyVmFsKTtcbiAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBjYXNlIENvbnN0LkZJTFRFUl9UWVBFLkNVU1RPTTpcbiAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgdmFsaWQgPSB0aGlzLmZpbHRlckN1c3RvbSh0YXJnZXRWYWwsIGZpbHRlclZhbCwgZmlsdGVyT2JqW2tleV0udmFsdWUpO1xuICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGRlZmF1bHQ6IHtcbiAgICAgICAgICAgICAgdmFsaWQgPSB0aGlzLmZpbHRlclRleHQodGFyZ2V0VmFsLCBmaWx0ZXJWYWwpO1xuICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG4gICAgICAgICAgaWYgKCF2YWxpZCkge1xuICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIHJldHVybiB2YWxpZDtcbiAgICAgIH0pO1xuICAgICAgdGhpcy5pc09uRmlsdGVyID0gdHJ1ZTtcbiAgICB9XG4gIH1cblxuICBmaWx0ZXJOdW1iZXIodGFyZ2V0VmFsLCBmaWx0ZXJWYWwsIGNvbXBhcmF0b3IpIHtcbiAgICBsZXQgdmFsaWQgPSB0cnVlO1xuICAgIHN3aXRjaCAoY29tcGFyYXRvcikge1xuICAgICAgY2FzZSBcIj1cIjpcbiAgICAgIHtcbiAgICAgICAgaWYgKHRhcmdldFZhbCAhPSBmaWx0ZXJWYWwpIHtcbiAgICAgICAgICB2YWxpZCA9IGZhbHNlO1xuICAgICAgICB9XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgICAgY2FzZSBcIj5cIjpcbiAgICAgIHtcbiAgICAgICAgaWYgKHRhcmdldFZhbCA8PSBmaWx0ZXJWYWwpIHtcbiAgICAgICAgICB2YWxpZCA9IGZhbHNlO1xuICAgICAgICB9XG4gICAgICAgIGJyZWFrO1xuICAgICAgfVxuICAgICAgY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BrZXlzTGVuZ3RoID0ga2V5cy5sZW5ndGg7IGkgPCBrZXlzTGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICBjb25zdCBrZXkgPSBrZXlzW2ldO1xuICAgICAgICAgIGlmICh0aGlzLmNvbEluZm9zW2tleV0gJiYgcm93W2tleV0pIHtcbiAgICAgICAgICAgIGNvbnN0IHsgZm9ybWF0LCBmaWx0ZXJGb3JtYXR0ZWQsIGZvcm1hdEV4dHJhRGF0YSwgc2VhcmNoYWJsZSwgaGlkZGVuIH0gPSB0aGlzLmNvbEluZm9zW2tleV07XG4gICAgICAgICAgICBsZXQgdGFyZ2V0VmFsID0gcm93W2tleV07XG4gICAgICAgICAgICBpZiAoc2VhcmNoYWJsZSkge1xuICAgICAgICAgICAgICBpZiAoZmlsdGVyRm9ybWF0dGVkICYmIGZvcm1hdCkge1xuICAgICAgICAgICAgICAgIHRhcmdldFZhbCA9IGZvcm1hdCh0YXJnZXRWYWwsIHJvdywgZm9ybWF0RXh0cmFEYXRhKTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICBmb3IgKGxldCBqID0gMCwgdGV4dExlbmd0aCA9IHNlYXJjaFRleHRBcnJheS5sZW5ndGg7IGogPCB0ZXh0TGVuZ3RoOyBqKyspIHtcbiAgICAgICAgICAgICAgICBjb25zdCBmaWx0ZXJWYWwgPSBzZWFyY2hUZXh0QXJyYXlbal0udG9Mb3dlckNhc2UoKTtcbiAgICAgICAgICAgICAgICBpZiAodGFyZ2V0VmFsLnRvU3RyaW5nKCkudG9Mb3dlckNhc2UoKS5pbmRleE9mKGZpbHRlclZhbCkgIT09IC0xKSB7XG4gICAgICAgICAgICAgICAgICB2YWxpZCA9IHRydWU7XG4gICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgcmV0dXJuIHZhbGlkO1xuICAgIC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F0YS5tYXAoZnVuY3Rpb24gKHJvdykge1xuICAgICAgcmV0dXJuIHJvd1t0aGlzLmtleUZpZWxkXTtcbiAgICB9LCB0aGlzKTtcbiAgfVxuXG59XG47XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9zdG9yZS9UYWJsZURhdGFTdG9yZS5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=");
},function(module,exports){eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n }\n throw TypeError('Uncaught, unspecified \"error\" event.');\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vKHdlYnBhY2spL34vbm9kZS1saWJzLWJyb3dzZXIvfi9ldmVudHMvZXZlbnRzLmpzPzQ2YjMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQ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PT09IHZvaWQgMDtcbn1cblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogKHdlYnBhY2spL34vbm9kZS1saWJzLWJyb3dzZXIvfi9ldmVudHMvZXZlbnRzLmpzXG4gKiogbW9kdWxlIGlkID0gMzVcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\nif (typeof window !== 'undefined') {\n var filesaver = __webpack_require__(37);\n var saveAs = filesaver.saveAs;\n}\n\nfunction toString(data, keys) {\n var dataString = \"\";\n if (data.length === 0) return dataString;\n\n dataString += keys.join(',') + '\\n';\n\n data.map(function (row) {\n keys.map(function (col, i) {\n var cell = typeof row[col] !== 'undefined' ? '\"' + row[col] + '\"' : \"\";\n dataString += cell;\n if (i + 1 < keys.length) dataString += ',';\n });\n\n dataString += '\\n';\n });\n\n return dataString;\n};\n\nvar exportCSV = function exportCSV(data, keys, filename) {\n var dataString = toString(data, keys);\n if (typeof window !== 'undefined') {\n saveAs(new Blob([dataString], { type: \"text/plain;charset=utf-8\" }), filename || 'spreadsheet.csv');\n }\n};\n\nexports['default'] = exportCSV;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvY3N2X2V4cG9ydF91dGlsLmpzPzhlY2MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxJQUFHLE9BQU8sTUFBTSxLQUFLLFdBQVcsRUFBQztBQUMvQixNQUFJLFNBQVMsR0FBRyxtQkFBTyxDQUFDLEVBQWEsQ0FBQyxDQUFDO0FBQ3ZDLE1BQUksTUFBTSxHQUFHLFNBQVMsQ0FBQyxNQUFNO0NBQzlCOztBQUVELFNBQVMsUUFBUSxDQUFD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QXMoIG5ldyBCbG9iKFtkYXRhU3RyaW5nXSwge3R5cGU6IFwidGV4dC9wbGFpbjtjaGFyc2V0PXV0Zi04XCJ9KSwgZmlsZW5hbWUgfHwgJ3NwcmVhZHNoZWV0LmNzdicgKTtcbiAgfVxuXG59O1xuXG5leHBvcnQgZGVmYXVsdCBleHBvcnRDU1Y7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9jc3ZfZXhwb3J0X3V0aWwuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9")},function(module,exports,__webpack_require__){eval('var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js\n * A saveAs() FileSaver implementation.\n * 1.1.20151003\n *\n * By Eli Grey, http://eligrey.com\n * License: MIT\n * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md\n */\n\n/*global self */\n/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */\n\n/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */\n\n"use strict";\n\nvar saveAs = saveAs || (function (view) {\n "use strict";\n // IE <10 is explicitly unsupported\n if (typeof navigator !== "undefined" && /MSIE [1-9]\\./.test(navigator.userAgent)) {\n return;\n }\n var doc = view.document,\n \n // only get URL when necessary in case Blob.js hasn\'t overridden it yet\n get_URL = function get_URL() {\n return view.URL || view.webkitURL || view;\n },\n save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),\n can_use_save_link = ("download" in save_link),\n click = function click(node) {\n var event = new MouseEvent("click");\n node.dispatchEvent(event);\n },\n is_safari = /Version\\/[\\d\\.]+.*Safari/.test(navigator.userAgent),\n webkit_req_fs = view.webkitRequestFileSystem,\n req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem,\n throw_outside = function throw_outside(ex) {\n (view.setImmediate || view.setTimeout)(function () {\n throw ex;\n }, 0);\n },\n force_saveable_type = "application/octet-stream",\n fs_min_size = 0,\n \n // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and\n // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047\n // for the reasoning behind the timeout and revocation flow\n arbitrary_revoke_timeout = 500,\n // in ms\n revoke = function revoke(file) {\n var revoker = function revoker() {\n if (typeof file === "string") {\n // file is an object URL\n get_URL().revokeObjectURL(file);\n } else {\n // file is a File\n file.remove();\n }\n };\n if (view.chrome) {\n revoker();\n } else {\n setTimeout(revoker, arbitrary_revoke_timeout);\n }\n },\n dispatch = function dispatch(filesaver, event_types, event) {\n event_types = [].concat(event_types);\n var i = event_types.length;\n while (i--) {\n var listener = filesaver["on" + event_types[i]];\n if (typeof listener === "function") {\n try {\n listener.call(filesaver, event || filesaver);\n } catch (ex) {\n throw_outside(ex);\n }\n }\n }\n },\n auto_bom = function auto_bom(blob) {\n // prepend BOM for UTF-8 XML and text/* types (including HTML)\n if (/^\\s*(?:text\\/\\S*|application\\/xml|\\S*\\/\\S*\\+xml)\\s*;.*charset\\s*=\\s*utf-8/i.test(blob.type)) {\n return new Blob(["\ufeff", blob], { type: blob.type });\n }\n return blob;\n },\n FileSaver = function FileSaver(blob, name, no_auto_bom) {\n if (!no_auto_bom) {\n blob = auto_bom(blob);\n }\n // First try a.download, then web filesystem, then object URLs\n var filesaver = this,\n type = blob.type,\n blob_changed = false,\n object_url,\n target_view,\n dispatch_all = function dispatch_all() {\n dispatch(filesaver, "writestart progress write writeend".split(" "));\n },\n \n // on any filesys errors revert to saving with object URLs\n fs_error = function fs_error() {\n if (target_view && is_safari && typeof FileReader !== "undefined") {\n // Safari doesn\'t allow downloading of blob urls\n var reader = new FileReader();\n reader.onloadend = function () {\n var base64Data = reader.result;\n target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));\n filesaver.readyState = filesaver.DONE;\n dispatch_all();\n };\n reader.readAsDataURL(blob);\n filesaver.readyState = filesaver.INIT;\n return;\n }\n // don\'t create more object URLs than needed\n if (blob_changed || !object_url) {\n object_url = get_URL().createObjectURL(blob);\n }\n if (target_view) {\n target_view.location.href = object_url;\n } else {\n var new_tab = view.open(object_url, "_blank");\n if (new_tab == undefined && is_safari) {\n //Apple do not allow window.open, see http://bit.ly/1kZffRI\n view.location.href = object_url;\n }\n }\n filesaver.readyState = filesaver.DONE;\n dispatch_all();\n revoke(object_url);\n },\n abortable = function abortable(func) {\n return function () {\n if (filesaver.readyState !== filesaver.DONE) {\n return func.apply(this, arguments);\n }\n };\n },\n create_if_not_found = { create: true, exclusive: false },\n slice;\n filesaver.readyState = filesaver.INIT;\n if (!name) {\n name = "download";\n }\n if (can_use_save_link) {\n object_url = get_URL().createObjectURL(blob);\n save_link.href = object_url;\n save_link.download = name;\n setTimeout(function () {\n click(save_link);\n dispatch_all();\n revoke(object_url);\n filesaver.readyState = filesaver.DONE;\n });\n return;\n }\n // Object and web filesystem URLs have a problem saving in Google Chrome when\n // viewed in a tab, so I force save with application/octet-stream\n // http://code.google.com/p/chromium/issues/detail?id=91158\n // Update: Google errantly closed 91158, I submitted it again:\n // https://code.google.com/p/chromium/issues/detail?id=389642\n if (view.chrome && type && type !== force_saveable_type) {\n slice = blob.slice || blob.webkitSlice;\n blob = slice.call(blob, 0, blob.size, force_saveable_type);\n blob_changed = true;\n }\n // Since I can\'t be sure that the guessed media type will trigger a download\n // in WebKit, I append .download to the filename.\n // https://bugs.webkit.org/show_bug.cgi?id=65440\n if (webkit_req_fs && name !== "download") {\n name += ".download";\n }\n if (type === force_saveable_type || webkit_req_fs) {\n target_view = view;\n }\n if (!req_fs) {\n fs_error();\n return;\n }\n fs_min_size += blob.size;\n req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {\n fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {\n var save = function save() {\n dir.getFile(name, create_if_not_found, abortable(function (file) {\n file.createWriter(abortable(function (writer) {\n writer.onwriteend = function (event) {\n target_view.location.href = file.toURL();\n filesaver.readyState = filesaver.DONE;\n dispatch(filesaver, "writeend", event);\n revoke(file);\n };\n writer.onerror = function () {\n var error = writer.error;\n if (error.code !== error.ABORT_ERR) {\n fs_error();\n }\n };\n "writestart progress write abort".split(" ").forEach(function (event) {\n writer["on" + event] = filesaver["on" + event];\n });\n writer.write(blob);\n filesaver.abort = function () {\n writer.abort();\n filesaver.readyState = filesaver.DONE;\n };\n filesaver.readyState = filesaver.WRITING;\n }), fs_error);\n }), fs_error);\n };\n dir.getFile(name, { create: false }, abortable(function (file) {\n // delete file if it already exists\n file.remove();\n save();\n }), abortable(function (ex) {\n if (ex.code === ex.NOT_FOUND_ERR) {\n save();\n } else {\n fs_error();\n }\n }));\n }), fs_error);\n }), fs_error);\n },\n FS_proto = FileSaver.prototype,\n saveAs = function saveAs(blob, name, no_auto_bom) {\n return new FileSaver(blob, name, no_auto_bom);\n };\n // IE 10+ (native saveAs)\n if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {\n return function (blob, name, no_auto_bom) {\n if (!no_auto_bom) {\n blob = auto_bom(blob);\n }\n return navigator.msSaveOrOpenBlob(blob, name || "download");\n };\n }\n\n FS_proto.abort = function () {\n var filesaver = this;\n filesaver.readyState = filesaver.DONE;\n dispatch(filesaver, "abort");\n };\n FS_proto.readyState = FS_proto.INIT = 0;\n FS_proto.WRITING = 1;\n FS_proto.DONE = 2;\n\n FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;\n\n return saveAs;\n})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content);\n// `self` is undefined in Firefox for Android content script context\n// while `this` is nsIContentFrameMessageManager\n// with an attribute `content` that corresponds to the window\n\nif (typeof module !== "undefined" && module.exports) {\n module.exports.saveAs = saveAs;\n} else if ("function" !== "undefined" && __webpack_require__(38) !== null && __webpack_require__(39) != null) {\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n return saveAs;\n }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n}\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsZXNhdmVyLmpzP2NlYzIiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQWNBLElBQUksTUFBTSxHQUFHLE1BQU0sSUFBSyxXQUFTLElBQUksRUFBRTtBQUN0QyxhQUFZLENBQUM7O0FBRWIsS0FBSSxPQUFPLFNBQVMsS0FBSyxXQUFXLElBQUksY0FBYyxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsU0FBUyxDQUFDLEVBQUU7QUFDakYsU0FBTztFQUNQO0FBQ0QsS0FDRyxHQUFHLEdBQUcsSUFBSSxDQUFDLFFBQVE7OztBQUVuQixRQUFPLEdBQUcsU0FBVixPQUFPLEdBQWM7QUFDdEIsU0FBTyxJQUFJLENBQUMsR0FBRyxJQUFJLElBQUksQ0FBQyxTQUFTLElBQUksSUFBSSxDQUFDO0VBQzFDO0tBQ0MsU0FBUyxHQUFHLEdBQUcsQ0FBQyxlQUFlLENBQUMsOEJBQThCLEVBQUUsR0FBRyxDQUFDO0tBQ3BFLGlCQUFpQixJQUFHLFVBQVUsSUFBSSxTQUFTO0tBQzNDLEtBQUssR0FBRyxTQUFSLEtBQUssQ0FBWSxJQUFJLEVBQUU7QUFDeEIsTUFBSSxLQUFLLEdBQUcsSUFBSSxVQUFVLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDcEMsTUFBSSxDQUFDLGFBQWEsQ0FBQyxLQUFLLENBQUMsQ0FBQztFQUMxQjtLQUNDLFNBQVMsR0FBRywwQkFBMEIsQ0FBQyxJQUFJLENBQUMsU0FBUyxDQUFDLFNBQVMsQ0FBQztLQUN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90by5vbndyaXRlID1cblx0RlNfcHJvdG8ub25hYm9ydCA9XG5cdEZTX3Byb3RvLm9uZXJyb3IgPVxuXHRGU19wcm90by5vbndyaXRlZW5kID1cblx0XHRudWxsO1xuXG5cdHJldHVybiBzYXZlQXM7XG59KFxuXHQgICB0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIiAmJiBzZWxmXG5cdHx8IHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIgJiYgd2luZG93XG5cdHx8IHRoaXMuY29udGVudFxuKSk7XG4vLyBgc2VsZmAgaXMgdW5kZWZpbmVkIGluIEZpcmVmb3ggZm9yIEFuZHJvaWQgY29udGVudCBzY3JpcHQgY29udGV4dFxuLy8gd2hpbGUgYHRoaXNgIGlzIG5zSUNvbnRlbnRGcmFtZU1lc3NhZ2VNYW5hZ2VyXG4vLyB3aXRoIGFuIGF0dHJpYnV0ZSBgY29udGVudGAgdGhhdCBjb3JyZXNwb25kcyB0byB0aGUgd2luZG93XG5cbmlmICh0eXBlb2YgbW9kdWxlICE9PSBcInVuZGVmaW5lZFwiICYmIG1vZHVsZS5leHBvcnRzKSB7XG4gIG1vZHVsZS5leHBvcnRzLnNhdmVBcyA9IHNhdmVBcztcbn0gZWxzZSBpZiAoKHR5cGVvZiBkZWZpbmUgIT09IFwidW5kZWZpbmVkXCIgJiYgZGVmaW5lICE9PSBudWxsKSAmJiAoZGVmaW5lLmFtZCAhPSBudWxsKSkge1xuICBkZWZpbmUoW10sIGZ1bmN0aW9uKCkge1xuICAgIHJldHVybiBzYXZlQXM7XG4gIH0pO1xufVxuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvZmlsZXNhdmVyLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==');
},function(module,exports){eval('module.exports = function() { throw new Error("define cannot be used indirect"); };\r\n\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vKHdlYnBhY2spL2J1aWxkaW4vYW1kLWRlZmluZS5qcz8wYmJhIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLDZCQUE2QixtREFBbUQiLCJmaWxlIjoiMzguanMiLCJzb3VyY2VzQ29udGVudCI6WyJtb2R1bGUuZXhwb3J0cyA9IGZ1bmN0aW9uKCkgeyB0aHJvdyBuZXcgRXJyb3IoXCJkZWZpbmUgY2Fubm90IGJlIHVzZWQgaW5kaXJlY3RcIik7IH07XHJcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogKHdlYnBhY2spL2J1aWxkaW4vYW1kLWRlZmluZS5qc1xuICoqIG1vZHVsZSBpZCA9IDM4XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9')},function(module,exports){eval("/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;\r\n\n/* WEBPACK VAR INJECTION */}.call(exports, {}))\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vKHdlYnBhY2spL2J1aWxkaW4vYW1kLW9wdGlvbnMuanM/NWY3MSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsImZpbGUiOiIzOS5qcyIsInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gX193ZWJwYWNrX2FtZF9vcHRpb25zX187XHJcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogKHdlYnBhY2spL2J1aWxkaW4vYW1kLW9wdGlvbnMuanNcbiAqKiBtb2R1bGUgaWQgPSAzOVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar EventEmitter = __webpack_require__(35).EventEmitter;\n\nvar Filter = (function (_EventEmitter) {\n _inherits(Filter, _EventEmitter);\n\n function Filter(data) {\n _classCallCheck(this, Filter);\n\n _get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data);\n this.currentFilter = {};\n }\n\n _createClass(Filter, [{\n key: 'handleFilter',\n value: function handleFilter(dataField, value, type) {\n var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM;\n\n if (value != null && typeof value === 'object') {\n // value of the filter is an object\n var hasValue = true;\n for (var prop in value) {\n if (!value[prop] || value[prop] === \"\") {\n hasValue = false;\n break;\n }\n }\n // if one of the object properties is undefined or empty, we remove the filter\n hasValue ? this.currentFilter[dataField] = { value: value, type: filterType } : delete this.currentFilter[dataField];\n } else if (!value || value.trim() === \"\") {\n delete this.currentFilter[dataField];\n } else {\n this.currentFilter[dataField] = { value: value.trim(), type: filterType };\n }\n this.emit('onFilterChange', this.currentFilter);\n }\n }]);\n\n return Filter;\n})(EventEmitter);\n\nexports.Filter = Filter;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvRmlsdGVyLmpzPzVkNzMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBUzs7OztBQUMzQixJQUFJLFlBQVksR0FBRyxtQkFBTyxDQUFDLEVBQVEsQ0FBQyxDQUFDLFlBQVksQ0FBQzs7SUFFckMsTUFBTTtjQUFOLE1BQU07O0FBQ0osYUFERixNQUFNLENBQ0gsSUFBSSxFQUFFOzhCQURULE1BQU07O0FBRVgsbUNBRkssTUFBTSw2Q0FFTCxJQUFJLEVBQUU7QUFDWixZQUFJLENBQUMsYUFBYSxHQUFHLEVBQUUsQ0FBQztLQUMzQjs7aUJBSlEsTUFBTTs7ZUFNSCxzQkFBQyxTQUFTLEVBQUUsS0FBSyxFQUFFLElBQUksRUFBRTtBQUNqQyxnQkFBTSxVQUFVLEdBQUcsSUFBSSxJQUFJLG1CQUFNLFdBQVcsQ0FBQyxNQUFNLENBQUM7O0FBRXBELGdCQUFJLEtBQUssSUFBSSxJQUFJLElBQUksT0FBTyxLQUFLLEtBQUssUUFBUSxFQUFFOztBQUU1QyxvQkFBSSxRQ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B2YWx1ZS50cmltKCkgPT09IFwiXCIpIHtcbiAgICAgICAgICAgIGRlbGV0ZSB0aGlzLmN1cnJlbnRGaWx0ZXJbZGF0YUZpZWxkXTtcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHRoaXMuY3VycmVudEZpbHRlcltkYXRhRmllbGRdID0ge3ZhbHVlOiB2YWx1ZS50cmltKCksIHR5cGU6IGZpbHRlclR5cGV9O1xuICAgICAgICB9XG4gICAgICAgIHRoaXMuZW1pdCgnb25GaWx0ZXJDaGFuZ2UnLCB0aGlzLmN1cnJlbnRGaWx0ZXIpO1xuICAgIH1cbn1cblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL0ZpbHRlci5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar _util = __webpack_require__(7);\n\nvar _util2 = _interopRequireDefault(_util);\n\nvar _filtersDate = __webpack_require__(42);\n\nvar _filtersDate2 = _interopRequireDefault(_filtersDate);\n\nvar _filtersText = __webpack_require__(43);\n\nvar _filtersText2 = _interopRequireDefault(_filtersText);\n\nvar _filtersRegex = __webpack_require__(44);\n\nvar _filtersRegex2 = _interopRequireDefault(_filtersRegex);\n\nvar _filtersSelect = __webpack_require__(45);\n\nvar _filtersSelect2 = _interopRequireDefault(_filtersSelect);\n\nvar _filtersNumber = __webpack_require__(46);\n\nvar _filtersNumber2 = _interopRequireDefault(_filtersNumber);\n\nvar TableHeaderColumn = (function (_React$Component) {\n _inherits(TableHeaderColumn, _React$Component);\n\n function TableHeaderColumn(props) {\n _classCallCheck(this, TableHeaderColumn);\n\n _get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props);\n this.handleFilter = this.handleFilter.bind(this);\n }\n\n _createClass(TableHeaderColumn, [{\n key: 'handleColumnClick',\n value: function handleColumnClick(e) {\n if (!this.props.dataSort) return;\n var order = this.props.sort == _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC;\n this.props.onSort(order, this.props.dataField);\n }\n }, {\n key: 'handleFilter',\n value: function handleFilter(value, type) {\n this.props.filter.emitter.handleFilter(this.props.dataField, value, type);\n }\n }, {\n key: 'getFilters',\n value: function getFilters() {\n switch (this.props.filter.type) {\n case _Const2['default'].FILTER_TYPE.TEXT:\n {\n return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter }));\n }\n case _Const2['default'].FILTER_TYPE.REGEX:\n {\n return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter }));\n }\n case _Const2['default'].FILTER_TYPE.SELECT:\n {\n return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter }));\n }\n case _Const2['default'].FILTER_TYPE.NUMBER:\n {\n return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter }));\n }\n case _Const2['default'].FILTER_TYPE.DATE:\n {\n return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter }));\n }\n case _Const2['default'].FILTER_TYPE.CUSTOM:\n {\n return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters);\n }\n }\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n this.refs[\"header-col\"].setAttribute(\"data-field\", this.props.dataField);\n }\n }, {\n key: 'render',\n value: function render() {\n var defaultCaret = undefined;\n var thStyle = {\n textAlign: this.props.dataAlign,\n display: this.props.hidden ? \"none\" : null\n };\n if (this.props.sortIndicator) {\n defaultCaret = !this.props.dataSort ? null : _react2['default'].createElement(\n 'span',\n { className: 'order' },\n _react2['default'].createElement(\n 'span',\n { className: 'dropdown' },\n _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } })\n ),\n _react2['default'].createElement(\n 'span',\n { className: 'dropup' },\n _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } })\n )\n );\n }\n var sortCaret = this.props.sort ? _util2['default'].renderReactSortCaret(this.props.sort) : defaultCaret;\n\n var classes = this.props.className + \" \" + (this.props.dataSort ? \"sort-column\" : \"\");\n return _react2['default'].createElement(\n 'th',\n { ref: 'header-col',\n className: classes,\n style: thStyle,\n title: this.props.children,\n onClick: this.handleColumnClick.bind(this) },\n this.props.children,\n sortCaret,\n this.props.filter ? this.getFilters() : null\n );\n }\n }]);\n\n return TableHeaderColumn;\n})(_react2['default'].Component);\n\nvar filterTypeArray = [];\nfor (var key in _Const2['default'].FILTER_TYPE) {\n filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]);\n}\n\nTableHeaderColumn.propTypes = {\n dataField: _react2['default'].PropTypes.string,\n dataAlign: _react2['default'].PropTypes.string,\n dataSort: _react2['default'].PropTypes.bool,\n onSort: _react2['default'].PropTypes.func,\n dataFormat: _react2['default'].PropTypes.func,\n isKey: _react2['default'].PropTypes.bool,\n editable: _react2['default'].PropTypes.any,\n hidden: _react2['default'].PropTypes.bool,\n searchable: _react2['default'].PropTypes.bool,\n className: _react2['default'].PropTypes.string,\n width: _react2['default'].PropTypes.string,\n sortFunc: _react2['default'].PropTypes.func,\n columnClassName: _react2['default'].PropTypes.any,\n filterFormatted: _react2['default'].PropTypes.bool,\n sort: _react2['default'].PropTypes.string,\n formatExtraData: _react2['default'].PropTypes.any,\n filter: _react2['default'].PropTypes.shape({\n type: _react2['default'].PropTypes.oneOf(filterTypeArray),\n delay: _react2['default'].PropTypes.number,\n options: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.object, // for SelectFilter\n _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.number) //for NumberFilter\n ]),\n numberComparators: _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.string),\n emitter: _react2['default'].PropTypes.object,\n placeholder: _react2['default'].PropTypes.string,\n getElement: _react2['default'].PropTypes.func,\n customFilterParameters: _react2['default'].PropTypes.object\n }),\n sortIndicator: _react2['default'].PropTypes.bool\n};\n\nTableHeaderColumn.defaultProps = {\n dataAlign: \"left\",\n dataSort: false,\n dataFormat: undefined,\n isKey: false,\n editable: true,\n onSort: undefined,\n hidden: false,\n searchable: true,\n className: \"\",\n width: null,\n sortFunc: undefined,\n columnClassName: '',\n filterFormatted: false,\n sort: undefined,\n formatExtraData: undefined,\n filter: undefined,\n sortIndicator: true\n};\n\nexports['default'] = TableHeaderColumn;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvVGFibGVIZWFkZXJDb2x1bW4uanM/YTNlNSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7aUNBQWtCLENBQU87Ozs7c0NBQ0osQ0FBWTs7OztpQ0FDZixDQUFTOzs7O2dDQUNWLENBQVE7Ozs7dUNBQ0YsRUFBZ0I7Ozs7dUNBQ2hCLEVBQWdCOzs7O3dDQUNmLEVBQWlCOzs7O3lDQUNoQixFQUFrQjs7Ozt5Q0FDbEIsRUFBa0I7Ozs7SUFFckMsaUJBQWlCO1lBQWpCLGlCQUFpQjs7QUFFVixXQUZQLGlCQUFpQixDQUVULEtBQUssRUFBRTswQkFGZixpQkFBaUI7O0FBR25CLCtCQUhFLGlCQUFpQiw2Q0FHYixLQUFLLEVBQUU7QUFDYixRQUFJLENBQUMsWUFBWSxHQUFHLElBQUksQ0FBQyxZQUFZLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0dBQ2xEOztlQUxHLGlCQUFpQjs7V0FPSiwyQkFBQyxDQUFDLEVBQUM7QUFDbEIsVUFBRyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsUUFBUSxFQUFDLE9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jdC5Qcm9wVHlwZXMuZnVuYyxcbiAgICBjdXN0b21GaWx0ZXJQYXJhbWV0ZXJzOiBSZWFjdC5Qcm9wVHlwZXMub2JqZWN0XG4gIH0pLFxuICBzb3J0SW5kaWNhdG9yOiBSZWFjdC5Qcm9wVHlwZXMuYm9vbFxufTtcblxuVGFibGVIZWFkZXJDb2x1bW4uZGVmYXVsdFByb3BzID0ge1xuICBkYXRhQWxpZ246IFwibGVmdFwiLFxuICBkYXRhU29ydDogZmFsc2UsXG4gIGRhdGFGb3JtYXQ6IHVuZGVmaW5lZCxcbiAgaXNLZXk6IGZhbHNlLFxuICBlZGl0YWJsZTogdHJ1ZSxcbiAgb25Tb3J0OiB1bmRlZmluZWQsXG4gIGhpZGRlbjogZmFsc2UsXG4gIHNlYXJjaGFibGU6IHRydWUsXG4gIGNsYXNzTmFtZTogXCJcIixcbiAgd2lkdGg6IG51bGwsXG4gIHNvcnRGdW5jOiB1bmRlZmluZWQsXG4gIGNvbHVtbkNsYXNzTmFtZTogJycsXG4gIGZpbHRlckZvcm1hdHRlZDogZmFsc2UsXG4gIHNvcnQ6IHVuZGVmaW5lZCxcbiAgZm9ybWF0RXh0cmFEYXRhOiB1bmRlZmluZWQsXG4gIGZpbHRlcjogdW5kZWZpbmVkLFxuICBzb3J0SW5kaWNhdG9yOiB0cnVlXG59O1xuXG5leHBvcnQgZGVmYXVsdCBUYWJsZUhlYWRlckNvbHVtbjtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL1RhYmxlSGVhZGVyQ29sdW1uLmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar DateFilter = (function (_React$Component) {\n _inherits(DateFilter, _React$Component);\n\n function DateFilter(props) {\n _classCallCheck(this, DateFilter);\n\n _get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props);\n this.filter = this.filter.bind(this);\n }\n\n _createClass(DateFilter, [{\n key: 'setDefaultDate',\n value: function setDefaultDate() {\n var defaultDate = \"\";\n if (this.props.defaultValue) {\n // Set the appropriate format for the input type=date, i.e. \"YYYY-MM-DD\"\n var defaultValue = new Date(this.props.defaultValue);\n defaultDate = defaultValue.getFullYear() + '-' + (\"0\" + (defaultValue.getMonth() + 1)).slice(-2) + '-' + (\"0\" + defaultValue.getDate()).slice(-2);\n }\n return defaultDate;\n }\n }, {\n key: 'filter',\n value: function filter(event) {\n var dateValue = event.target.value;\n if (dateValue) {\n this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);\n } else {\n this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE);\n }\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n var dateValue = this.refs.inputDate.defaultValue;\n if (dateValue) {\n this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);\n }\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2['default'].createElement('input', { ref: 'inputDate',\n className: 'filter date-filter form-control',\n type: 'date',\n onChange: this.filter,\n defaultValue: this.setDefaultDate() });\n }\n }]);\n\n return DateFilter;\n})(_react2['default'].Component);\n\n;\n\nDateFilter.propTypes = {\n filterHandler: _react2['default'].PropTypes.func.isRequired,\n defaultValue: _react2['default'].PropTypes.object,\n columnName: _react2['default'].PropTypes.string\n};\n\nexports['default'] = DateFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsdGVycy9EYXRlLmpzP2ExOTIiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztpQ0FDUCxDQUFVOzs7O0lBRXRCLFVBQVU7Y0FBVixVQUFVOztBQUNELGFBRFQsVUFBVSxDQUNBLEtBQUssRUFBRTs4QkFEakIsVUFBVTs7QUFFUixtQ0FGRixVQUFVLDZDQUVGLEtBQUssRUFBRTtBQUNiLFlBQUksQ0FBQyxNQUFNLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7S0FDeEM7O2lCQU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F0ZVZhbHVlKSB7XG4gICAgICAgICAgICB0aGlzLnByb3BzLmZpbHRlckhhbmRsZXIobmV3IERhdGUoZGF0ZVZhbHVlKSwgQ29uc3QuRklMVEVSX1RZUEUuREFURSk7XG4gICAgICAgIH1cbiAgICB9XG5cbiAgICByZW5kZXIoKSB7XG4gICAgICAgIHJldHVybiAoXG4gICAgICAgICAgICA8aW5wdXQgcmVmPVwiaW5wdXREYXRlXCJcbiAgICAgICAgICAgICAgICAgICBjbGFzc05hbWU9XCJmaWx0ZXIgZGF0ZS1maWx0ZXIgZm9ybS1jb250cm9sXCJcbiAgICAgICAgICAgICAgICAgICB0eXBlPVwiZGF0ZVwiXG4gICAgICAgICAgICAgICAgICAgb25DaGFuZ2U9e3RoaXMuZmlsdGVyfVxuICAgICAgICAgICAgICAgICAgIGRlZmF1bHRWYWx1ZT17dGhpcy5zZXREZWZhdWx0RGF0ZSgpfSAvPlxuICAgICAgICApO1xuICAgIH1cbn07XG5cbkRhdGVGaWx0ZXIucHJvcFR5cGVzID0ge1xuICAgIGZpbHRlckhhbmRsZXI6IFJlYWN0LlByb3BUeXBlcy5mdW5jLmlzUmVxdWlyZWQsXG4gICAgZGVmYXVsdFZhbHVlOiBSZWFjdC5Qcm9wVHlwZXMub2JqZWN0LFxuICAgIGNvbHVtbk5hbWU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmdcbn07XG5cbmV4cG9ydCBkZWZhdWx0IERhdGVGaWx0ZXI7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9maWx0ZXJzL0RhdGUuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9");
},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar TextFilter = (function (_React$Component) {\n _inherits(TextFilter, _React$Component);\n\n function TextFilter(props) {\n _classCallCheck(this, TextFilter);\n\n _get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props);\n this.filter = this.filter.bind(this);\n this.timeout = null;\n }\n\n _createClass(TextFilter, [{\n key: 'filter',\n value: function filter(event) {\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n var self = this;\n var filterValue = event.target.value;\n this.timeout = setTimeout(function () {\n self.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT);\n }, self.props.delay);\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n if (this.refs.inputText.defaultValue) {\n this.props.filterHandler(this.refs.inputText.defaultValue, _Const2['default'].FILTER_TYPE.TEXT);\n }\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n clearTimeout(this.timeout);\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2['default'].createElement('input', { ref: 'inputText',\n className: 'filter text-filter form-control',\n type: 'text',\n onChange: this.filter,\n placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',\n defaultValue: this.props.defaultValue ? this.props.defaultValue : \"\" });\n }\n }]);\n\n return TextFilter;\n})(_react2['default'].Component);\n\n;\n\nTextFilter.propTypes = {\n filterHandler: _react2['default'].PropTypes.func.isRequired,\n defaultValue: _react2['default'].PropTypes.string,\n delay: _react2['default'].PropTypes.number,\n placeholder: _react2['default'].PropTypes.string,\n columnName: _react2['default'].PropTypes.string\n};\n\nTextFilter.defaultProps = {\n delay: _Const2['default'].FILTER_DELAY\n};\n\nexports['default'] = TextFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsdGVycy9UZXh0LmpzPzIxYWIiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztpQ0FBa0IsQ0FBTzs7OztpQ0FDUCxDQUFVOzs7O0lBRXRCLFVBQVU7V0FBVixVQUFVOztBQUNKLFVBRE4sVUFBVSxDQUNILEtBQUssRUFBRTt3QkFEZCxVQUFVOztBQUVkLDZCQUZJLFVBQVUsNkNBRVIsS0FBSyxFQUFFO0FBQ2IsTUFBSSxDQUFDLE1BQU0sR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztBQUNyQyxNQUFJLENBQUMsT0FBTyxHQUFHLEl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0VmFsdWUpID8gdGhpcy5wcm9wcy5kZWZhdWx0VmFsdWUgOiBcIlwifSAvPlxuXHRcdCk7XG5cdH1cbn07XG5cblRleHRGaWx0ZXIucHJvcFR5cGVzID0ge1xuXHRmaWx0ZXJIYW5kbGVyOiBSZWFjdC5Qcm9wVHlwZXMuZnVuYy5pc1JlcXVpcmVkLFxuXHRkZWZhdWx0VmFsdWU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmcsXG5cdGRlbGF5OiBSZWFjdC5Qcm9wVHlwZXMubnVtYmVyLFxuXHRwbGFjZWhvbGRlcjogUmVhY3QuUHJvcFR5cGVzLnN0cmluZyxcblx0Y29sdW1uTmFtZTogUmVhY3QuUHJvcFR5cGVzLnN0cmluZ1xufTtcblxuVGV4dEZpbHRlci5kZWZhdWx0UHJvcHMgPSB7XG5cdGRlbGF5OiBDb25zdC5GSUxURVJfREVMQVlcbn1cblxuZXhwb3J0IGRlZmF1bHQgVGV4dEZpbHRlcjtcblxuXG5cbi8qKiBXRUJQQUNLIEZPT1RFUiAqKlxuICoqIC4vc3JjL2ZpbHRlcnMvVGV4dC5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar RegexFilter = (function (_React$Component) {\n _inherits(RegexFilter, _React$Component);\n\n function RegexFilter(props) {\n _classCallCheck(this, RegexFilter);\n\n _get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props);\n this.filter = this.filter.bind(this);\n this.timeout = null;\n }\n\n _createClass(RegexFilter, [{\n key: 'filter',\n value: function filter(event) {\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n var self = this;\n var filterValue = event.target.value;\n this.timeout = setTimeout(function () {\n self.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX);\n }, self.props.delay);\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n if (this.refs.inputText.defaultValue) {\n this.props.filterHandler(this.refs.inputText.defaultValue, _Const2['default'].FILTER_TYPE.REGEX);\n }\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n clearTimeout(this.timeout);\n }\n }, {\n key: 'render',\n value: function render() {\n return _react2['default'].createElement('input', { ref: 'inputText',\n className: 'filter text-filter form-control',\n type: 'text',\n onChange: this.filter,\n placeholder: this.props.placeholder || 'Enter Regex for ' + this.props.columnName + '...',\n defaultValue: this.props.defaultValue ? this.props.defaultValue : \"\" });\n }\n }]);\n\n return RegexFilter;\n})(_react2['default'].Component);\n\n;\n\nRegexFilter.propTypes = {\n filterHandler: _react2['default'].PropTypes.func.isRequired,\n defaultValue: _react2['default'].PropTypes.string,\n delay: _react2['default'].PropTypes.number,\n placeholder: _react2['default'].PropTypes.string,\n columnName: _react2['default'].PropTypes.string\n};\n\nRegexFilter.defaultProps = {\n delay: _Const2['default'].FILTER_DELAY\n};\n\nexports['default'] = RegexFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsdGVycy9SZWdleC5qcz8wNzY3Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7Ozs7aUNBQWtCLENBQU87Ozs7aUNBQ1AsQ0FBVTs7OztJQUV0QixXQUFXO1dBQVgsV0FBVzs7QUFDTCxVQUROLFdBQVcsQ0FDSixLQUFLLEVBQUU7d0JBRGQsV0FBVzs7QUFFZiw2QkFGSSxXQUFXLDZDQUVULEtBQUssRUFBRTtBQUNiLE1BQUksQ0FBQyxNQUFNLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDckMsTUFBSSxDQUFDLE9BQU8sR0FBRyxJQUFJLENBQUM7RUFDcEI7O2NBTEksV0FBVzs7U0FPVixnQkFBQyxLQUFLLEVBQUU7QUFDYixPQUFJLElBQUksQ0FBQyxPQUFPLEVBQUU7QUFDakIsZ0JBQVksQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUM7SUFDM0I7QUFDRCxPQUFNLElBQUksR0FBRyxJQUFJLENBQUM7QUFDbEIsT0FBTSxXQUFXLEdBQUcsS0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JvcFR5cGVzLnN0cmluZyxcblx0ZGVsYXk6IFJlYWN0LlByb3BUeXBlcy5udW1iZXIsXG5cdHBsYWNlaG9sZGVyOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nLFxuXHRjb2x1bW5OYW1lOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nXG59O1xuXG5SZWdleEZpbHRlci5kZWZhdWx0UHJvcHMgPSB7XG5cdGRlbGF5OiBDb25zdC5GSUxURVJfREVMQVlcbn1cblxuZXhwb3J0IGRlZmF1bHQgUmVnZXhGaWx0ZXI7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9maWx0ZXJzL1JlZ2V4LmpzXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ==")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar SelectFilter = (function (_React$Component) {\n _inherits(SelectFilter, _React$Component);\n\n function SelectFilter(props) {\n _classCallCheck(this, SelectFilter);\n\n _get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props);\n this.filter = this.filter.bind(this);\n this.state = {\n isPlaceholderSelected: this.props.defaultValue == undefined || !this.props.options.hasOwnProperty(this.props.defaultValue)\n };\n }\n\n _createClass(SelectFilter, [{\n key: 'filter',\n value: function filter(event) {\n this.setState({ isPlaceholderSelected: event.target.value === \"\" });\n this.props.filterHandler(event.target.value, _Const2['default'].FILTER_TYPE.SELECT);\n }\n }, {\n key: 'getOptions',\n value: function getOptions() {\n var optionTags = [];\n var options = this.props.options;\n optionTags.push(_react2['default'].createElement(\n 'option',\n { key: '-1', value: '' },\n this.props.placeholder || 'Select ' + this.props.columnName + '...'\n ));\n Object.keys(options).map(function (key) {\n optionTags.push(_react2['default'].createElement(\n 'option',\n { key: key, value: key },\n options[key]\n ));\n });\n return optionTags;\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n if (this.refs.selectInput.value) {\n this.props.filterHandler(this.refs.selectInput.value, _Const2['default'].FILTER_TYPE.SELECT);\n }\n }\n }, {\n key: 'render',\n value: function render() {\n var selectClass = (0, _classnames2['default'])(\"filter\", \"select-filter\", \"form-control\", { \"placeholder-selected\": this.state.isPlaceholderSelected });\n\n return _react2['default'].createElement(\n 'select',\n { ref: 'selectInput',\n className: selectClass,\n onChange: this.filter,\n defaultValue: this.props.defaultValue != undefined ? this.props.defaultValue : \"\" },\n this.getOptions()\n );\n }\n }]);\n\n return SelectFilter;\n})(_react2['default'].Component);\n\n;\n\nSelectFilter.propTypes = {\n filterHandler: _react2['default'].PropTypes.func.isRequired,\n options: _react2['default'].PropTypes.object.isRequired,\n placeholder: _react2['default'].PropTypes.string,\n columnName: _react2['default'].PropTypes.string\n};\n\nexports['default'] = SelectFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsdGVycy9TZWxlY3QuanM/YmYyNSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O3NDQUNKLENBQVk7Ozs7aUNBQ2YsQ0FBVTs7OztJQUV0QixZQUFZO1dBQVosWUFBWTs7QUFDTixVQUROLFlBQVksQ0FDTCxLQUFLLEVBQUU7d0JBRGQsWUFBWTs7QUFFaEIsNkJBRkksWUFBWSw2Q0FFVixLQUFLLEVBQUU7QUFDYixNQUFJLENBQUMsTUFBTSxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQ3JDLE1BQUksQ0FBQyxLQUFLLEdBQUc7QUFDWix3QkFBcUIsRUFBRyxJQUFJLENBQUMsS0FBSyxDQUFDLFlBQVksSUFBSSxTQUFTLElBQ3RELENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxPQUFPLENBQUMsY0FBYyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsWUFBWSxDQUFFO0dBQ2xFLENBQUM7RUFDRjs7Y0FSSSxZQUFZOztTQVVYLGdCQUFDLEtBQUssRUFBRTtBQUNiLE9BQUksQ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C5Qcm9wVHlwZXMub2JqZWN0LmlzUmVxdWlyZWQsXG5cdHBsYWNlaG9sZGVyOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nLFxuXHRjb2x1bW5OYW1lOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nXG59O1xuXG5leHBvcnQgZGVmYXVsdCBTZWxlY3RGaWx0ZXI7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiAuL3NyYy9maWx0ZXJzL1NlbGVjdC5qc1xuICoqLyJdLCJzb3VyY2VSb290IjoiIn0=")},function(module,exports,__webpack_require__){eval("'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nvar _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();\n\nvar _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }\n\nvar _react = __webpack_require__(2);\n\nvar _react2 = _interopRequireDefault(_react);\n\nvar _classnames = __webpack_require__(3);\n\nvar _classnames2 = _interopRequireDefault(_classnames);\n\nvar _Const = __webpack_require__(4);\n\nvar _Const2 = _interopRequireDefault(_Const);\n\nvar legalComparators = [\"=\", \">\", \">=\", \"<\", \"<=\", \"!=\"];\n\nvar NumberFilter = (function (_React$Component) {\n _inherits(NumberFilter, _React$Component);\n\n function NumberFilter(props) {\n _classCallCheck(this, NumberFilter);\n\n _get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props);\n this.numberComparators = this.props.numberComparators || legalComparators;\n this.timeout = null;\n this.state = {\n isPlaceholderSelected: this.props.defaultValue == undefined || this.props.defaultValue.number == undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) == -1\n };\n this.onChangeNumber = this.onChangeNumber.bind(this);\n this.onChangeNumberSet = this.onChangeNumberSet.bind(this);\n this.onChangeComparator = this.onChangeComparator.bind(this);\n }\n\n _createClass(NumberFilter, [{\n key: 'onChangeNumber',\n value: function onChangeNumber(event) {\n if (this.refs.numberFilterComparator.value === \"\") {\n return;\n }\n if (this.timeout) {\n clearTimeout(this.timeout);\n }\n var self = this;\n var filterValue = event.target.value;\n this.timeout = setTimeout(function () {\n self.props.filterHandler({ number: filterValue, comparator: self.refs.numberFilterComparator.value }, _Const2['default'].FILTER_TYPE.NUMBER);\n }, self.props.delay);\n }\n }, {\n key: 'onChangeNumberSet',\n value: function onChangeNumberSet(event) {\n this.setState({ isPlaceholderSelected: event.target.value === \"\" });\n if (this.refs.numberFilterComparator.value === \"\") {\n return;\n }\n this.props.filterHandler({ number: event.target.value, comparator: this.refs.numberFilterComparator.value }, _Const2['default'].FILTER_TYPE.NUMBER);\n }\n }, {\n key: 'onChangeComparator',\n value: function onChangeComparator(event) {\n if (this.refs.numberFilter.value === \"\") {\n return;\n }\n this.props.filterHandler({ number: this.refs.numberFilter.value, comparator: event.target.value }, _Const2['default'].FILTER_TYPE.NUMBER);\n }\n }, {\n key: 'getComparatorOptions',\n value: function getComparatorOptions() {\n var optionTags = [];\n optionTags.push(_react2['default'].createElement('option', { key: '-1' }));\n for (var i = 0; i < this.numberComparators.length; i++) {\n optionTags.push(_react2['default'].createElement(\n 'option',\n { key: i, value: this.numberComparators[i] },\n this.numberComparators[i]\n ));\n };\n return optionTags;\n }\n }, {\n key: 'getNumberOptions',\n value: function getNumberOptions() {\n var optionTags = [];\n var options = this.props.options;\n\n optionTags.push(_react2['default'].createElement(\n 'option',\n { key: '-1', value: '' },\n this.props.placeholder || 'Select ' + this.props.columnName + '...'\n ));\n for (var i = 0; i < options.length; i++) {\n optionTags.push(_react2['default'].createElement(\n 'option',\n { key: i, value: options[i] },\n options[i]\n ));\n };\n return optionTags;\n }\n }, {\n key: 'componentDidMount',\n value: function componentDidMount() {\n if (this.refs.numberFilterComparator.value && this.refs.numberFilter.value) {\n this.props.filterHandler({ number: this.refs.numberFilter.value,\n comparator: this.refs.numberFilterComparator.value }, _Const2['default'].FILTER_TYPE.NUMBER);\n }\n }\n }, {\n key: 'componentWillUnmount',\n value: function componentWillUnmount() {\n clearTimeout(this.timeout);\n }\n }, {\n key: 'render',\n value: function render() {\n var selectClass = (0, _classnames2['default'])(\"select-filter\", \"number-filter-input\", \"form-control\", { \"placeholder-selected\": this.state.isPlaceholderSelected });\n\n return _react2['default'].createElement(\n 'div',\n { className: 'filter number-filter' },\n _react2['default'].createElement(\n 'select',\n { ref: 'numberFilterComparator',\n className: 'number-filter-comparator form-control',\n onChange: this.onChangeComparator,\n defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : \"\" },\n this.getComparatorOptions()\n ),\n this.props.options ? _react2['default'].createElement(\n 'select',\n { ref: 'numberFilter',\n className: selectClass,\n onChange: this.onChangeNumberSet,\n defaultValue: this.props.defaultValue ? this.props.defaultValue.number : \"\" },\n this.getNumberOptions()\n ) : _react2['default'].createElement('input', { ref: 'numberFilter',\n type: 'number',\n className: 'number-filter-input form-control',\n placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',\n onChange: this.onChangeNumber,\n defaultValue: this.props.defaultValue ? this.props.defaultValue.number : \"\" })\n );\n }\n }]);\n\n return NumberFilter;\n})(_react2['default'].Component);\n\n;\n\nNumberFilter.propTypes = {\n filterHandler: _react2['default'].PropTypes.func.isRequired,\n options: _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.number),\n defaultValue: _react2['default'].PropTypes.shape({\n number: _react2['default'].PropTypes.number,\n comparator: _react2['default'].PropTypes.oneOf(legalComparators)\n }),\n delay: _react2['default'].PropTypes.number,\n numberComparators: function numberComparators(props, propName) {\n if (!props[propName]) {\n return;\n }\n for (var i = 0; i < props[propName].length; i++) {\n var comparatorIsValid = false;\n for (var j = 0; j < legalComparators.length; j++) {\n if (legalComparators[j] === props[propName][i]) {\n comparatorIsValid = true;\n break;\n }\n }\n if (!comparatorIsValid) {\n return new Error('Number comparator provided is not supported. Use only ' + legalComparators);\n }\n }\n },\n placeholder: _react2['default'].PropTypes.string,\n columnName: _react2['default'].PropTypes.string\n};\n\nNumberFilter.defaultProps = {\n delay: _Const2['default'].FILTER_DELAY\n};\n\nexports['default'] = NumberFilter;\nmodule.exports = exports['default'];\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvZmlsdGVycy9OdW1iZXIuanM/ZmVkZCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7O2lDQUFrQixDQUFPOzs7O3NDQUNKLENBQVk7Ozs7aUNBQ2YsQ0FBVTs7OztBQUU1QixJQUFNLGdCQUFnQixHQUFHLENBQUMsR0FBRyxFQUFFLEdBQUcsRUFBRSxJQUFJLEVBQUU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gICAgICB9O1xuICAgICAgICByZXR1cm4gb3B0aW9uVGFncztcbiAgICB9XG5cbiAgICBjb21wb25lbnREaWRNb3VudCgpIHtcbiAgICAgICAgaWYgKHRoaXMucmVmcy5udW1iZXJGaWx0ZXJDb21wYXJhdG9yLnZhbHVlICYmIHRoaXMucmVmcy5udW1iZXJGaWx0ZXIudmFsdWUpIHtcbiAgICAgICAgICAgIHRoaXMucHJvcHMuZmlsdGVySGFuZGxlcih7bnVtYmVyOiB0aGlzLnJlZnMubnVtYmVyRmlsdGVyLnZhbHVlLFxuICAgICAgICAgICAgICAgIGNvbXBhcmF0b3I6IHRoaXMucmVmcy5udW1iZXJGaWx0ZXJDb21wYXJhdG9yLnZhbHVlfSxcbiAgICAgICAgICAgICAgICBDb25zdC5GSUxURVJfVFlQRS5OVU1CRVIpO1xuICAgICAgICB9XG4gICAgfVxuXG4gICAgY29tcG9uZW50V2lsbFVubW91bnQoKSB7XG4gICAgICAgIGNsZWFyVGltZW91dCh0aGlzLnRpbWVvdXQpO1xuICAgIH1cblxuICAgIHJlbmRlcigpIHtcbiAgICAgICAgdmFyIHNlbGVjdENsYXNzID0gY2xhc3NTZXQoXCJzZWxlY3QtZmlsdGVyXCIsIFwibnVtYmVyLWZpbHRlci1pbnB1dFwiLCBcImZvcm0tY29udHJvbFwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHsgXCJwbGFjZWhvbGRlci1zZWxlY3RlZFwiOiB0aGlzLnN0YXRlLmlzUGxhY2Vob2xkZXJTZWxlY3RlZCB9KTtcblxuICAgICAgICByZXR1cm4gKFxuICAgICAgICAgICAgPGRpdiBjbGFzc05hbWU9XCJmaWx0ZXIgbnVtYmVyLWZpbHRlclwiPlxuICAgICAgICAgICAgICAgIDxzZWxlY3QgcmVmPVwibnVtYmVyRmlsdGVyQ29tcGFyYXRvclwiXG4gICAgICAgICAgICAgICAgICAgICAgICBjbGFzc05hbWU9XCJudW1iZXItZmlsdGVyLWNvbXBhcmF0b3IgZm9ybS1jb250cm9sXCJcbiAgICAgICAgICAgICAgICAgICAgICAgIG9uQ2hhbmdlPXt0aGlzLm9uQ2hhbmdlQ29tcGFyYXRvcn1cbiAgICAgICAgICAgICAgICAgICAgICAgIGRlZmF1bHRWYWx1ZT17KHRoaXMucHJvcHMuZGVmYXVsdFZhbHVlKSA/IHRoaXMucHJvcHMuZGVmYXVsdFZhbHVlLmNvbXBhcmF0b3IgOiBcIlwifT5cbiAgICAgICAgICAgICAgICAgICAge3RoaXMuZ2V0Q29tcGFyYXRvck9wdGlvbnMoKX1cbiAgICAgICAgICAgICAgICA8L3NlbGVjdD5cbiAgICAgICAgICAgICAgICB7KHRoaXMucHJvcHMub3B0aW9ucykgPyA8c2VsZWN0IHJlZj1cIm51bWJlckZpbHRlclwiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjbGFzc05hbWU9e3NlbGVjdENsYXNzfVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgb25DaGFuZ2U9e3RoaXMub25DaGFuZ2VOdW1iZXJTZXR9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBkZWZhdWx0VmFsdWU9eyh0aGlzLnByb3BzLmRlZmF1bHRWYWx1ZSkgP1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucHJvcHMuZGVmYXVsdFZhbHVlLm51bWJlciA6XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcIn0+XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHt0aGlzLmdldE51bWJlck9wdGlvbnMoKX1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8L3NlbGVjdD4gOlxuXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPGlucHV0IHJlZj1cIm51bWJlckZpbHRlclwiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU9XCJudW1iZXJcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjbGFzc05hbWU9XCJudW1iZXItZmlsdGVyLWlucHV0IGZvcm0tY29udHJvbFwiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHBsYWNlaG9sZGVyPXt0aGlzLnByb3BzLnBsYWNlaG9sZGVyIHx8IGBFbnRlciAke3RoaXMucHJvcHMuY29sdW1uTmFtZX0uLi5gfVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBvbkNoYW5nZT17dGhpcy5vbkNoYW5nZU51bWJlcn1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZGVmYXVsdFZhbHVlPXsodGhpcy5wcm9wcy5kZWZhdWx0VmFsdWUpID9cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLnByb3BzLmRlZmF1bHRWYWx1ZS5udW1iZXIgOlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwiXCJ9IC8+fVxuICAgICAgICAgICAgPC9kaXY+XG4gICAgICAgICk7XG4gICAgfVxufTtcblxuTnVtYmVyRmlsdGVyLnByb3BUeXBlcyA9IHtcbiAgICBmaWx0ZXJIYW5kbGVyOiBSZWFjdC5Qcm9wVHlwZXMuZnVuYy5pc1JlcXVpcmVkLFxuICAgIG9wdGlvbnM6IFJlYWN0LlByb3BUeXBlcy5hcnJheU9mKFJlYWN0LlByb3BUeXBlcy5udW1iZXIpLFxuICAgIGRlZmF1bHRWYWx1ZTogUmVhY3QuUHJvcFR5cGVzLnNoYXBlKHtcbiAgICAgICAgbnVtYmVyOiBSZWFjdC5Qcm9wVHlwZXMubnVtYmVyLFxuICAgICAgICBjb21wYXJhdG9yOiBSZWFjdC5Qcm9wVHlwZXMub25lT2YobGVnYWxDb21wYXJhdG9ycylcbiAgICB9KSxcbiAgICBkZWxheTogUmVhY3QuUHJvcFR5cGVzLm51bWJlcixcbiAgICBudW1iZXJDb21wYXJhdG9yczogZnVuY3Rpb24ocHJvcHMsIHByb3BOYW1lKSB7XG4gICAgICAgIGlmICghcHJvcHNbcHJvcE5hbWVdKSB7XG4gICAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cbiAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBwcm9wc1twcm9wTmFtZV0ubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgIGxldCBjb21wYXJhdG9ySXNWYWxpZCA9IGZhbHNlO1xuICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCBsZWdhbENvbXBhcmF0b3JzLmxlbmd0aDsgaisrKSB7XG4gICAgICAgICAgICAgICAgaWYgKGxlZ2FsQ29tcGFyYXRvcnNbal0gPT09IHByb3BzW3Byb3BOYW1lXVtpXSkge1xuICAgICAgICAgICAgICAgICAgICBjb21wYXJhdG9ySXNWYWxpZCA9IHRydWU7XG4gICAgICAgICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICghY29tcGFyYXRvcklzVmFsaWQpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gbmV3IEVycm9yKGBOdW1iZXIgY29tcGFyYXRvciBwcm92aWRlZCBpcyBub3Qgc3VwcG9ydGVkLiBVc2Ugb25seSAke2xlZ2FsQ29tcGFyYXRvcnN9YCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9LFxuICAgIHBsYWNlaG9sZGVyOiBSZWFjdC5Qcm9wVHlwZXMuc3RyaW5nLFxuICAgIGNvbHVtbk5hbWU6IFJlYWN0LlByb3BUeXBlcy5zdHJpbmdcbn07XG5cbk51bWJlckZpbHRlci5kZWZhdWx0UHJvcHMgPSB7XG4gICAgZGVsYXk6IENvbnN0LkZJTFRFUl9ERUxBWVxufTtcblxuZXhwb3J0IGRlZmF1bHQgTnVtYmVyRmlsdGVyO1xuXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogLi9zcmMvZmlsdGVycy9OdW1iZXIuanNcbiAqKi8iXSwic291cmNlUm9vdCI6IiJ9");
}])});
|
tests/index.js
|
KeywordBrain/redbox-react
|
import React from 'react'
import test from 'tape'
import {createComponent} from './utils'
import errorStackParserMock from './errorStackParserMock'
import framesStub from './framesStub.json'
import framesStubAbsoluteFilenames from './framesStubAbsoluteFilenames.json'
import framesStubMissingFilename from './framesStubMissingFilename.json'
import RedBox, {RedBoxError, __RewireAPI__} from '../src'
import style from '../src/style'
import './lib';
// There’s no DOM available during the tests and the error stack is just a stub
// that don’t need to be mapped.
RedBoxError.prototype.mapOnConstruction = function(error) {
this.state = { error, mapped: true }
}
RedBoxError.prototype.mapError = function(error) {
this.setState({ error, mapped: true })
}
const beforeEach = (framesStub) => {
__RewireAPI__.__Rewire__('ErrorStackParser', errorStackParserMock(framesStub))
}
const afterEach = () => {
__RewireAPI__.__ResetDependency__('ErrorStackParser')
}
// RedBox tests
test('RedBox static displayName', t => {
t.plan(1)
t.equal(
RedBox.displayName,
'RedBox',
'correct static displayName property on class RedBox'
)
})
// TODO: add missing new tests for RedBox "portal" component
// RedBoxError tests
test('RedBoxError static displayName', t => {
t.plan(1)
t.equal(
RedBoxError.displayName,
'RedBoxError',
'correct static displayName property on class RedBoxError'
)
})
test('RedBoxError error message', t => {
t.plan(3)
beforeEach(framesStub)
const ERR_MESSAGE = 'funny error name'
const error = new Error(ERR_MESSAGE)
const component = createComponent(RedBoxError, {error})
// renderedError = div.redbox > div.message > *
const renderedError = component
.props.children[0]
.props.children
t.equal(
renderedError[0],
'Error',
'Main error message begins with error type'
)
t.equal(
renderedError[1],
': ',
'Error type is followed by a colon and white space.'
)
t.equal(
renderedError[2],
ERR_MESSAGE,
'Main error message ends with message originally supplied to error constructor.'
)
afterEach()
})
test('RedBoxError stack trace', t => {
t.plan(1)
beforeEach(framesStub)
const error = new Error()
const component = createComponent(RedBoxError, {error})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./components/App.js?">webpack:///./components/App.js?:45:12</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with filename from react-transform-catch-errors', t => {
t.plan(1)
beforeEach(framesStub)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const component = createComponent(RedBoxError, {error, filename})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="file:///filename">/filename</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with filename and editorScheme', t => {
t.plan(1)
beforeEach(framesStub)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const editorScheme = 'subl'
const component = createComponent(RedBoxError, {error, filename, editorScheme})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///filename">/filename</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with filename and vscode like editorScheme', t => {
t.plan(1)
beforeEach(framesStub)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const editorScheme = 'vscode'
const component = createComponent(RedBoxError, {error, filename, editorScheme})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="vscode://file/filename">/filename</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?">webpack:///./~/react-hot-loader/~/react-hot-api/modules/makeAssimilatePrototype.js?:17:41</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with absolute filenames', t => {
t.plan(1)
beforeEach(framesStubAbsoluteFilenames)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const editorScheme = 'subl'
const component = createComponent(RedBoxError, {error, filename, editorScheme})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///components/App.js&line=45&column=12">/components/App.js:45:12</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js&line=17&column=41">/some-path/modules/makeAssimilatePrototype.js:17:41</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with absolute filenames but unreliable line numbers', t => {
t.plan(1)
beforeEach(framesStubAbsoluteFilenames)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const editorScheme = 'subl'
const useLines = false
const component = createComponent(RedBoxError, {error, filename, editorScheme, useLines})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///components/App.js">/components/App.js</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js">/some-path/modules/makeAssimilatePrototype.js</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with absolute filenames but unreliable column numbers', t => {
t.plan(1)
beforeEach(framesStubAbsoluteFilenames)
const error = new Error()
const filename = 'some-optional-webpack-loader!/filename'
const editorScheme = 'subl'
const useColumns = false
const component = createComponent(RedBoxError, {error, filename, editorScheme, useColumns})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///components/App.js&line=45">/components/App.js:45</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="subl://open?url=file:///some-path/modules/makeAssimilatePrototype.js&line=17">/some-path/modules/makeAssimilatePrototype.js:17</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError stack trace with missing filename', t => {
t.plan(1)
beforeEach(framesStubMissingFilename)
const error = new Error()
const component = createComponent(RedBoxError, {error})
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="webpack:///./components/App.js?">webpack:///./components/App.js?:45:12</a>
</div>
</div>
<div style={style.frame} key={1}>
<div>App.render</div>
<div style={style.file}>
<a style={style.linkToFile} href="file://">{''}</a>
</div>
</div>
</div>
)
afterEach()
})
test('RedBoxError with throwing stack trace parser', t => {
t.plan(3)
__RewireAPI__.__Rewire__('ErrorStackParser', {
parse: function () {
// This mimicks the former behavior of stacktracejs,
// see https://github.com/stacktracejs/stackframe/issues/11.
throw new TypeError("Line Number must be a Number")
}
})
const ERR_MESSAGE = "original error message"
const error = new TypeError(ERR_MESSAGE)
const component = createComponent(RedBoxError, {error})
const renderedError = component
.props.children[0]
.props.children
t.equal(
renderedError[0],
'TypeError',
'Main error message begins with error type of original error'
)
t.equal(
renderedError[2],
ERR_MESSAGE,
'Main error message ends with message originally supplied to error constructor.'
)
const renderedStack = component
.props.children[1]
t.deepEqual(
renderedStack,
<div style={style.stack}>
<div style={style.frame} key={0}>
<div>Failed to parse stack trace. Stack trace information unavailable.</div>
</div>
</div>
)
afterEach()
})
|
test/unit/app/components/Header/Header.spec.js
|
nabil-jazoul/react-starter
|
import React from 'react'
import configStore from 'redux-mock-store'
import { shallow } from 'enzyme'
import expect from 'expect'
import Header from 'App/components/Header'
describe('<Header />', () => {
const mockStore = configStore()
it('should render login link for guests', () => {
const store = mockStore()
const wrapper = shallow(<Header store={store} />).shallow()
expect(wrapper.find({ to: '/login' }).length).toBe(1)
})
it('should not render login link for logged in users', () => {
const store = mockStore({
user: {
username: 'username',
},
})
const wrapper = shallow(<Header store={store} />).shallow()
expect(wrapper.find({ to: '/login' }).length).toBe(0)
})
it('should not render users link for non-admin users', () => {
const store = mockStore({
user: {
username: 'username',
isAdmin: false,
},
})
const wrapper = shallow(<Header store={store} />).shallow()
expect(wrapper.find({ to: '/users' }).length).toBe(0)
})
it('should render users link for admin users', () => {
const store = mockStore({
user: {
username: 'username',
isAdmin: true,
},
})
const wrapper = shallow(<Header store={store} />).shallow()
expect(wrapper.find({ to: '/users' }).length).toBe(1)
})
})
|
ajax/libs/react-data-grid/1.0.56/react-data-grid.js
|
holtkamp/cdnjs
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactDataGrid"] = factory(require("react"), require("react-dom"));
else
root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (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 Grid = __webpack_require__(52);
var Row = __webpack_require__(17);
var Cell = __webpack_require__(22);
module.exports = Grid;
module.exports.Row = Row;
module.exports.Cell = Cell;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(30);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
function classNames() {
var classes = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (!arg) {
continue;
}
if ('string' === typeof arg || 'number' === typeof arg) {
classes += ' ' + arg;
} else if (Object.prototype.toString.call(arg) === '[object Array]') {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === typeof arg) {
for (var key in arg) {
if (!arg.hasOwnProperty(key) || !arg[key]) {
continue;
}
classes += ' ' + key;
}
}
}
return classes.substr(1);
}
// safely export classNames for node / browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
// safely export classNames for RequireJS
if (true) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
module.exports = {
getColumn: function getColumn(columns, idx) {
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
spliceColumn: function spliceColumn(metrics, idx, column) {
if (Array.isArray(metrics.columns)) {
metrics.columns.splice(idx, 1, column);
} else if (typeof Immutable !== 'undefined') {
metrics.columns = metrics.columns.splice(idx, 1, column);
}
return metrics;
},
getSize: function getSize(columns) {
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
// Logic extented to allow for functions to be passed down in column.editable
// this allows us to deicde whether we can be edting from a cell level
canEdit: function canEdit(col, rowData, enableCellSelect) {
if (col.editable != null && typeof col.editable === 'function') {
return enableCellSelect === true && col.editable(rowData);
}
return enableCellSelect === true && (!!col.editor || !!col.editable);
}
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumnShape = {
name: React.PropTypes.node.isRequired,
key: React.PropTypes.string.isRequired,
width: React.PropTypes.number.isRequired,
filterable: React.PropTypes.bool
};
module.exports = ExcelColumnShape;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(82),
getValue = __webpack_require__(93);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var PropTypes = __webpack_require__(1).PropTypes;
module.exports = {
selected: PropTypes.object.isRequired,
copied: PropTypes.object,
dragged: PropTypes.object,
onCellClick: PropTypes.func.isRequired,
onCellDoubleClick: PropTypes.func.isRequired,
onCommit: PropTypes.func.isRequired,
onCommitCancel: PropTypes.func.isRequired,
handleDragEnterRow: PropTypes.func.isRequired,
handleTerminateDrag: PropTypes.func.isRequired
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var shallowCloneObject = __webpack_require__(18);
var contextTypes = {
metricsComputator: React.PropTypes.object
};
var MetricsComputatorMixin = {
childContextTypes: contextTypes,
getChildContext: function getChildContext() {
return { metricsComputator: this };
},
getMetricImpl: function getMetricImpl(name) {
return this._DOMMetrics.metrics[name].value;
},
registerMetricsImpl: function registerMetricsImpl(component, metrics) {
var getters = {};
var s = this._DOMMetrics;
for (var name in metrics) {
if (s.metrics[name] !== undefined) {
throw new Error('DOM metric ' + name + ' is already defined');
}
s.metrics[name] = { component: component, computator: metrics[name].bind(component) };
getters[name] = this.getMetricImpl.bind(null, name);
}
if (s.components.indexOf(component) === -1) {
s.components.push(component);
}
return getters;
},
unregisterMetricsFor: function unregisterMetricsFor(component) {
var s = this._DOMMetrics;
var idx = s.components.indexOf(component);
if (idx > -1) {
s.components.splice(idx, 1);
var name = void 0;
var metricsToDelete = {};
for (name in s.metrics) {
if (s.metrics[name].component === component) {
metricsToDelete[name] = true;
}
}
for (name in metricsToDelete) {
if (metricsToDelete.hasOwnProperty(name)) {
delete s.metrics[name];
}
}
}
},
updateMetrics: function updateMetrics() {
var s = this._DOMMetrics;
var needUpdate = false;
for (var name in s.metrics) {
if (!s.metrics.hasOwnProperty(name)) continue;
var newMetric = s.metrics[name].computator();
if (newMetric !== s.metrics[name].value) {
needUpdate = true;
}
s.metrics[name].value = newMetric;
}
if (needUpdate) {
for (var i = 0, len = s.components.length; i < len; i++) {
if (s.components[i].metricsUpdated) {
s.components[i].metricsUpdated();
}
}
}
},
componentWillMount: function componentWillMount() {
this._DOMMetrics = {
metrics: {},
components: []
};
},
componentDidMount: function componentDidMount() {
if (window.addEventListener) {
window.addEventListener('resize', this.updateMetrics);
} else {
window.attachEvent('resize', this.updateMetrics);
}
this.updateMetrics();
},
componentWillUnmount: function componentWillUnmount() {
window.removeEventListener('resize', this.updateMetrics);
}
};
var MetricsMixin = {
contextTypes: contextTypes,
componentWillMount: function componentWillMount() {
if (this.DOMMetrics) {
this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics);
this.DOMMetrics = {};
for (var name in this._DOMMetricsDefs) {
if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue;
this.DOMMetrics[name] = function () {};
}
}
},
componentDidMount: function componentDidMount() {
if (this.DOMMetrics) {
this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs);
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.registerMetricsImpl) {
return this.context.metricsComputator.unregisterMetricsFor(this);
}
if (this.hasOwnProperty('DOMMetrics')) {
delete this.DOMMetrics;
}
},
registerMetrics: function registerMetrics(metrics) {
if (this.registerMetricsImpl) {
return this.registerMetricsImpl(this, metrics);
}
return this.context.metricsComputator.registerMetricsImpl(this, metrics);
},
getMetric: function getMetric(name) {
if (this.getMetricImpl) {
return this.getMetricImpl(name);
}
return this.context.metricsComputator.getMetricImpl(name);
}
};
module.exports = {
MetricsComputatorMixin: MetricsComputatorMixin,
MetricsMixin: MetricsMixin
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(103),
listCacheDelete = __webpack_require__(104),
listCacheGet = __webpack_require__(105),
listCacheHas = __webpack_require__(106),
listCacheSet = __webpack_require__(107);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(32);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(20),
getRawTag = __webpack_require__(91),
objectToString = __webpack_require__(116);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
value = Object(value);
return (symToStringTag && symToStringTag in value)
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(100);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ },
/* 15 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var shallowCloneObject = __webpack_require__(18);
var sameColumn = __webpack_require__(42);
var ColumnUtils = __webpack_require__(5);
var getScrollbarSize = __webpack_require__(26);
var isColumnsImmutable = __webpack_require__(66);
function setColumnWidths(columns, totalWidth) {
return columns.map(function (column) {
var colInfo = Object.assign({}, column);
if (column.width) {
if (/^([0-9]+)%$/.exec(column.width.toString())) {
colInfo.width = Math.floor(column.width / 100 * totalWidth);
}
}
return colInfo;
});
}
function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) {
var defferedColumns = columns.filter(function (c) {
return !c.width;
});
return columns.map(function (column) {
if (!column.width) {
if (unallocatedWidth <= 0) {
column.width = minColumnWidth;
} else {
column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns));
}
}
return column;
});
}
function setColumnOffsets(columns) {
var left = 0;
return columns.map(function (column) {
column.left = left;
left += column.width;
return column;
});
}
/**
* Update column metrics calculation.
*
* @param {ColumnMetricsType} metrics
*/
function recalculate(metrics) {
// compute width for columns which specify width
var columns = setColumnWidths(metrics.columns, metrics.totalWidth);
var unallocatedWidth = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w - column.width;
}, metrics.totalWidth);
unallocatedWidth -= getScrollbarSize();
var width = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w + column.width;
}, 0);
// compute width for columns which doesn't specify width
columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth);
// compute left offset
columns = setColumnOffsets(columns);
return {
columns: columns,
width: width,
totalWidth: metrics.totalWidth,
minColumnWidth: metrics.minColumnWidth
};
}
/**
* Update column metrics calculation by resizing a column.
*
* @param {ColumnMetricsType} metrics
* @param {Column} column
* @param {number} width
*/
function resizeColumn(metrics, index, width) {
var column = ColumnUtils.getColumn(metrics.columns, index);
var metricsClone = shallowCloneObject(metrics);
metricsClone.columns = metrics.columns.slice(0);
var updatedColumn = shallowCloneObject(column);
updatedColumn.width = Math.max(width, metricsClone.minColumnWidth);
metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn);
return recalculate(metricsClone);
}
function areColumnsImmutable(prevColumns, nextColumns) {
return isColumnsImmutable(prevColumns) && isColumnsImmutable(nextColumns);
}
function compareEachColumn(prevColumns, nextColumns, isSameColumn) {
var i = void 0;
var len = void 0;
var column = void 0;
var prevColumnsByKey = {};
var nextColumnsByKey = {};
if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) {
return false;
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
prevColumnsByKey[column.key] = column;
}
for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) {
column = nextColumns[i];
nextColumnsByKey[column.key] = column;
var prevColumn = prevColumnsByKey[column.key];
if (prevColumn === undefined || !isSameColumn(prevColumn, column)) {
return false;
}
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
var nextColumn = nextColumnsByKey[column.key];
if (nextColumn === undefined) {
return false;
}
}
return true;
}
function sameColumns(prevColumns, nextColumns, isSameColumn) {
if (areColumnsImmutable(prevColumns, nextColumns)) {
return prevColumns === nextColumns;
}
return compareEachColumn(prevColumns, nextColumns, isSameColumn);
}
module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns };
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(4);
var Cell = __webpack_require__(22);
var ColumnMetrics = __webpack_require__(16);
var ColumnUtilsMixin = __webpack_require__(5);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var CellExpander = React.createClass({
displayName: 'CellExpander',
render: function render() {
return React.createElement(Cell, this.props);
}
});
var Row = React.createClass({
displayName: 'Row',
propTypes: {
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
row: PropTypes.any.isRequired,
cellRenderer: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
isSelected: PropTypes.bool,
idx: PropTypes.number.isRequired,
expandedRows: PropTypes.arrayOf(PropTypes.object),
extraClasses: PropTypes.string,
forceUpdate: PropTypes.bool,
subRowDetails: PropTypes.object,
isRowHovered: PropTypes.bool
},
mixins: [ColumnUtilsMixin],
getDefaultProps: function getDefaultProps() {
return {
cellRenderer: Cell,
isSelected: false,
height: 35
};
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height || this.props.forceUpdate === true;
},
handleDragEnter: function handleDragEnter() {
var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow;
if (handleDragEnterRow) {
handleDragEnterRow(this.props.idx);
}
},
getSelectedColumn: function getSelectedColumn() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.idx) {
return this.getColumn(this.props.columns, selected.idx);
}
}
},
getCellRenderer: function getCellRenderer(columnKey) {
var CellRenderer = this.props.cellRenderer;
if (this.props.subRowDetails && this.props.subRowDetails.field === columnKey) {
return CellExpander;
}
return CellRenderer;
},
getCells: function getCells() {
var _this = this;
var cells = [];
var lockedCells = [];
var selectedColumn = this.getSelectedColumn();
if (this.props.columns) {
this.props.columns.forEach(function (column, i) {
var CellRenderer = _this.props.cellRenderer;
var cell = React.createElement(CellRenderer, {
ref: 'cell-' + i,
key: column.key + '-' + i,
idx: i,
rowIdx: _this.props.idx,
value: _this.getCellValue(column.key || i),
column: column,
height: _this.getRowHeight(),
formatter: column.formatter,
cellMetaData: _this.props.cellMetaData,
rowData: _this.props.row,
selectedColumn: selectedColumn,
isRowSelected: _this.props.isSelected,
expandableOptions: _this.getExpandableOptions(column.key) });
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
});
}
return cells.concat(lockedCells);
},
getRowHeight: function getRowHeight() {
var rows = this.props.expandedRows || null;
if (rows && this.props.idx) {
var row = rows[this.props.idx] || null;
if (row) {
return row.height;
}
}
return this.props.height;
},
getCellValue: function getCellValue(key) {
var val = void 0;
if (key === 'select-row') {
return this.props.isSelected;
} else if (typeof this.props.row.get === 'function') {
val = this.props.row.get(key);
} else {
val = this.props.row[key];
}
return val;
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this2 = this;
// vv
this.props.columns.forEach(function (column, i) {
if (column.locked) {
if (!_this2.refs['cell-' + i]) return;
_this2.refs['cell-' + i].setScrollLeft(scrollLeft);
}
});
},
doesRowContainSelectedCell: function doesRowContainSelectedCell(props) {
var selected = props.cellMetaData.selected;
if (selected && selected.rowIdx === props.idx) {
return true;
}
return false;
},
isContextMenuDisplayed: function isContextMenuDisplayed() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.contextMenuDisplayed && selected.rowIdx === this.props.idx) {
return true;
}
}
return false;
},
willRowBeDraggedOver: function willRowBeDraggedOver(props) {
var dragged = props.cellMetaData.dragged;
return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true);
},
hasRowBeenCopied: function hasRowBeenCopied() {
var copied = this.props.cellMetaData.copied;
return copied != null && copied.rowIdx === this.props.idx;
},
getExpandableOptions: function getExpandableOptions(columnKey) {
return { canExpand: this.props.subRowDetails && this.props.subRowDetails.field === columnKey, expanded: this.props.subRowDetails && this.props.subRowDetails.expanded, children: this.props.subRowDetails && this.props.subRowDetails.children, treeDepth: this.props.subRowDetails ? this.props.subRowDetails.treeDepth : 0 };
},
renderCell: function renderCell(props) {
if (typeof this.props.cellRenderer === 'function') {
this.props.cellRenderer.call(this, props);
}
if (React.isValidElement(this.props.cellRenderer)) {
return React.cloneElement(this.props.cellRenderer, props);
}
return this.props.cellRenderer(props);
},
render: function render() {
var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), {
'row-selected': this.props.isSelected,
'row-context-menu': this.isContextMenuDisplayed()
}, this.props.extraClasses);
var style = {
height: this.getRowHeight(this.props),
overflow: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }),
React.isValidElement(this.props.row) ? this.props.row : cells
);
}
});
module.exports = Row;
/***/ },
/* 18 */
/***/ function(module, exports) {
"use strict";
function shallowCloneObject(obj) {
var result = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
result[k] = obj[k];
}
}
return result;
}
module.exports = shallowCloneObject;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ },
/* 21 */
/***/ function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _isEqual = __webpack_require__(128);
var _isEqual2 = _interopRequireDefault(_isEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(4);
var EditorContainer = __webpack_require__(63);
var ExcelColumn = __webpack_require__(6);
var isFunction = __webpack_require__(25);
var CellMetaDataShape = __webpack_require__(8);
var SimpleCellFormatter = __webpack_require__(65);
var ColumnUtils = __webpack_require__(5);
var Cell = React.createClass({
displayName: 'Cell',
propTypes: {
rowIdx: React.PropTypes.number.isRequired,
idx: React.PropTypes.number.isRequired,
selected: React.PropTypes.shape({
idx: React.PropTypes.number.isRequired
}),
selectedColumn: React.PropTypes.object,
height: React.PropTypes.number,
tabIndex: React.PropTypes.number,
ref: React.PropTypes.string,
column: React.PropTypes.shape(ExcelColumn).isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
isExpanded: React.PropTypes.bool,
isRowSelected: React.PropTypes.bool,
cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired,
handleDragStart: React.PropTypes.func,
className: React.PropTypes.string,
cellControls: React.PropTypes.any,
rowData: React.PropTypes.object.isRequired,
forceUpdate: React.PropTypes.bool,
expandableOptions: React.PropTypes.object.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
tabIndex: -1,
isExpanded: false,
value: ''
};
},
getInitialState: function getInitialState() {
return {
isCellValueChanging: false
};
},
componentDidMount: function componentDidMount() {
this.checkFocus();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
isCellValueChanging: this.props.value !== nextProps.value
});
},
componentDidUpdate: function componentDidUpdate() {
this.checkFocus();
var dragged = this.props.cellMetaData.dragged;
if (dragged && dragged.complete === true) {
this.props.cellMetaData.handleTerminateDrag();
}
if (this.state.isCellValueChanging && this.props.selectedColumn != null) {
this.applyUpdateClass();
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value || this.props.forceUpdate === true || this.props.className !== nextProps.className || this.hasChangedDependentValues(nextProps);
},
onCellClick: function onCellClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellContextMenu: function onCellContextMenu() {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellContextMenu && typeof meta.onCellContextMenu === 'function') {
meta.onCellContextMenu({ rowIdx: this.props.rowIdx, idx: this.props.idx });
}
},
onCellDoubleClick: function onCellDoubleClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellDoubleClick && typeof meta.onCellDoubleClick === 'function') {
meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellExpand: function onCellExpand(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellExpand != null) {
meta.onCellExpand({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.props.rowData, expandArgs: this.props.expandableOptions });
}
},
onCellKeyDown: function onCellKeyDown(e) {
if (this.canExpand() && e.key === 'Enter') {
this.onCellExpand(e);
}
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onDragHandleDoubleClick && typeof meta.onDragHandleDoubleClick === 'function') {
meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData(), e: e });
}
},
onDragOver: function onDragOver(e) {
e.preventDefault();
},
getStyle: function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left
};
return style;
},
getFormatter: function getFormatter() {
var col = this.props.column;
if (this.isActive()) {
return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, value: this.props.value, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height });
}
return this.props.column.formatter;
},
getRowData: function getRowData() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
return props.rowData.toJSON ? props.rowData.toJSON() : props.rowData;
},
getFormatterDependencies: function getFormatterDependencies() {
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.getRowData(), this.props.column);
}
},
getCellClass: function getCellClass() {
var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null);
var extraClasses = joinClasses({
'row-selected': this.props.isRowSelected,
selected: this.isSelected() && !this.isActive() && this.isCellSelectEnabled(),
editing: this.isActive(),
copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(),
'active-drag-cell': this.isSelected() || this.isDraggedOver(),
'is-dragged-over-up': this.isDraggedOverUpwards(),
'is-dragged-over-down': this.isDraggedOverDownwards(),
'was-dragged-over': this.wasDraggedOver()
});
return joinClasses(className, extraClasses);
},
getUpdateCellClass: function getUpdateCellClass() {
return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : '';
},
isColumnSelected: function isColumnSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.idx === this.props.idx;
},
isSelected: function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx;
},
isActive: function isActive() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return this.isSelected() && meta.selected.active === true;
},
isCellSelectionChanging: function isCellSelectionChanging(nextProps) {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
var nextSelected = nextProps.cellMetaData.selected;
if (meta.selected && nextSelected) {
return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx;
}
return true;
},
isCellSelectEnabled: function isCellSelectEnabled() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.enableCellSelect;
},
hasChangedDependentValues: function hasChangedDependentValues(nextProps) {
var currentColumn = this.props.column;
var hasChangedDependentValues = false;
if (currentColumn.getRowMetaData) {
var currentRowMetaData = currentColumn.getRowMetaData(this.getRowData(), currentColumn);
var nextColumn = nextProps.column;
var nextRowMetaData = nextColumn.getRowMetaData(this.getRowData(nextProps), nextColumn);
hasChangedDependentValues = !(0, _isEqual2['default'])(currentRowMetaData, nextRowMetaData);
}
return hasChangedDependentValues;
},
applyUpdateClass: function applyUpdateClass() {
var updateCellClass = this.getUpdateCellClass();
// -> removing the class
if (updateCellClass != null && updateCellClass !== '') {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode.classList) {
cellDOMNode.classList.remove(updateCellClass);
// -> and re-adding the class
cellDOMNode.classList.add(updateCellClass);
} else if (cellDOMNode.className.indexOf(updateCellClass) === -1) {
// IE9 doesn't support classList, nor (I think) altering element.className
// without replacing it wholesale.
cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass;
}
}
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this
if (ctrl.isMounted()) {
var node = ReactDOM.findDOMNode(this);
var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.webkitTransform = transform;
node.style.transform = transform;
}
},
isCopied: function isCopied() {
var copied = this.props.cellMetaData.copied;
return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx;
},
isDraggedOver: function isDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx;
},
wasDraggedOver: function wasDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx;
},
isDraggedCellChanging: function isDraggedCellChanging(nextProps) {
var isChanging = void 0;
var dragged = this.props.cellMetaData.dragged;
var nextDragged = nextProps.cellMetaData.dragged;
if (dragged) {
isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx;
return isChanging;
}
return false;
},
isCopyCellChanging: function isCopyCellChanging(nextProps) {
var isChanging = void 0;
var copied = this.props.cellMetaData.copied;
var nextCopied = nextProps.cellMetaData.copied;
if (copied) {
isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx;
return isChanging;
}
return false;
},
isDraggedOverUpwards: function isDraggedOverUpwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx;
},
isDraggedOverDownwards: function isDraggedOverDownwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx;
},
checkFocus: function checkFocus() {
if (this.isSelected() && !this.isActive()) {
// determine the parent viewport element of this cell
var parentViewport = ReactDOM.findDOMNode(this);
while (parentViewport != null && parentViewport.className.indexOf('react-grid-Viewport') === -1) {
parentViewport = parentViewport.parentElement;
}
var focusInGrid = false;
// if the focus is on the body of the document, the user won't mind if we focus them on a cell
if (document.activeElement == null || document.activeElement.nodeName && typeof document.activeElement.nodeName === 'string' && document.activeElement.nodeName.toLowerCase() === 'body') {
focusInGrid = true;
// otherwise
} else {
// only pull focus if the currently focused element is contained within the viewport
if (parentViewport) {
var focusedParent = document.activeElement;
while (focusedParent != null) {
if (focusedParent === parentViewport) {
focusInGrid = true;
break;
}
focusedParent = focusedParent.parentElement;
}
}
}
if (focusInGrid) {
ReactDOM.findDOMNode(this).focus();
}
}
},
canEdit: function canEdit() {
return this.props.column.editor != null || this.props.column.editable;
},
canExpand: function canExpand() {
return this.props.expandableOptions && this.props.expandableOptions.canExpand;
},
createColumEventCallBack: function createColumEventCallBack(onColumnEvent, info) {
return function (e) {
onColumnEvent(e, info);
};
},
createCellEventCallBack: function createCellEventCallBack(gridEvent, columnEvent) {
return function (e) {
gridEvent(e);
columnEvent(e);
};
},
createEventDTO: function createEventDTO(gridEvents, columnEvents, onColumnEvent) {
var allEvents = Object.assign({}, gridEvents);
for (var eventKey in columnEvents) {
if (columnEvents.hasOwnProperty(eventKey)) {
var event = columnEvents[event];
var eventInfo = { rowIdx: this.props.rowIdx, idx: this.props.idx, name: eventKey };
var eventCallback = this.createColumEventCallBack(onColumnEvent, eventInfo);
if (allEvents.hasOwnProperty(eventKey)) {
var currentEvent = allEvents[eventKey];
allEvents[eventKey] = this.createCellEventCallBack(currentEvent, eventCallback);
} else {
allEvents[eventKey] = eventCallback;
}
}
}
return allEvents;
},
getEvents: function getEvents() {
var columnEvents = this.props.column ? Object.assign({}, this.props.column.events) : undefined;
var onColumnEvent = this.props.cellMetaData ? this.props.cellMetaData.onColumnEvent : undefined;
var gridEvents = {
onClick: this.onCellClick,
onDoubleClick: this.onCellDoubleClick,
onContextMenu: this.onCellContextMenu,
onDragOver: this.onDragOver
};
if (!columnEvents || !onColumnEvent) {
return gridEvents;
}
return this.createEventDTO(gridEvents, columnEvents, onColumnEvent);
},
renderCellContent: function renderCellContent(props) {
var CellContent = void 0;
var Formatter = this.getFormatter();
if (React.isValidElement(Formatter)) {
props.dependentValues = this.getFormatterDependencies();
CellContent = React.cloneElement(Formatter, props);
} else if (isFunction(Formatter)) {
CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() });
} else {
CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value });
}
var cellExpander = void 0;
var marginLeft = this.props.expandableOptions ? this.props.expandableOptions.treeDepth * 30 : 0;
if (this.canExpand()) {
cellExpander = React.createElement(
'span',
{ style: { float: 'left', marginLeft: marginLeft }, onClick: this.onCellExpand },
this.props.expandableOptions.expanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
);
}
return React.createElement(
'div',
{ className: 'react-grid-Cell__value' },
cellExpander,
React.createElement(
'span',
null,
CellContent
),
' ',
this.props.cellControls,
' '
);
},
render: function render() {
if (this.props.column.hidden) {
return null;
}
var style = this.getStyle();
var className = this.getCellClass();
var cellContent = this.renderCellContent({
value: this.props.value,
column: this.props.column,
rowIdx: this.props.rowIdx,
isExpanded: this.props.isExpanded
});
var dragHandle = !this.isActive() && ColumnUtils.canEdit(this.props.column, this.props.rowData, this.props.cellMetaData.enableCellSelect) ? React.createElement(
'div',
{ className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick },
React.createElement('span', { style: { display: 'none' } })
) : null;
var events = this.getEvents();
return React.createElement(
'div',
_extends({}, this.props, { className: className, style: style }, events),
cellContent,
dragHandle
);
}
});
module.exports = Cell;
/***/ },
/* 23 */
/***/ function(module, exports) {
'use strict';
var KeyboardHandlerMixin = {
onKeyDown: function onKeyDown(e) {
if (this.isCtrlKeyHeldDown(e)) {
this.checkAndCall('onPressKeyWithCtrl', e);
} else if (this.isKeyExplicitlyHandled(e.key)) {
// break up individual keyPress events to have their own specific callbacks
// this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing
var callBack = 'onPress' + e.key;
this.checkAndCall(callBack, e);
} else if (this.isKeyPrintable(e.keyCode)) {
this.checkAndCall('onPressChar', e);
}
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
this._keysDown[e.keyCode] = true;
if (this.props.onGridKeyDown && typeof this.props.onGridKeyDown === 'function') {
this.props.onGridKeyDown(e);
}
},
onKeyUp: function onKeyUp(e) {
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
delete this._keysDown[e.keyCode];
if (this.props.onGridKeyUp && typeof this.props.onGridKeyUp === 'function') {
this.props.onGridKeyUp(e);
}
},
isKeyDown: function isKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown;
},
isSingleKeyDown: function isSingleKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown && Object.keys(this._keysDown).length === 1;
},
// taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character
isKeyPrintable: function isKeyPrintable(keycode) {
var valid = keycode > 47 && keycode < 58 || // number keys
keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns)
keycode > 64 && keycode < 91 || // letter keys
keycode > 95 && keycode < 112 || // numpad keys
keycode > 185 && keycode < 193 || // ;=,-./` (in order)
keycode > 218 && keycode < 223; // [\]' (in order)
return valid;
},
isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) {
return typeof this['onPress' + key] === 'function';
},
isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) {
return e.ctrlKey === true && e.key !== 'Control';
},
checkAndCall: function checkAndCall(methodName, args) {
if (typeof this[methodName] === 'function') {
this[methodName](args);
}
}
};
module.exports = KeyboardHandlerMixin;
/***/ },
/* 24 */
/***/ function(module, exports) {
'use strict';
var RowUtils = {
get: function get(row, property) {
if (typeof row.get === 'function') {
return row.get(property);
}
return row[property];
},
isRowSelected: function isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx) {
if (indexes && Object.prototype.toString.call(indexes) === '[object Array]') {
return indexes.indexOf(rowIdx) > -1;
} else if (keys && keys.rowKey && keys.values && Object.prototype.toString.call(keys.values) === '[object Array]') {
return keys.values.indexOf(rowData[keys.rowKey]) > -1;
} else if (isSelectedKey && rowData && typeof isSelectedKey === 'string') {
return rowData[isSelectedKey];
}
return false;
}
};
module.exports = RowUtils;
/***/ },
/* 25 */
/***/ function(module, exports) {
'use strict';
var isFunction = function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
module.exports = isFunction;
/***/ },
/* 26 */
/***/ function(module, exports) {
'use strict';
var size = void 0;
function getScrollbarSize() {
if (size === undefined) {
var outer = document.createElement('div');
outer.style.width = '50px';
outer.style.height = '50px';
outer.style.position = 'absolute';
outer.style.top = '-200px';
outer.style.left = '-200px';
var inner = document.createElement('div');
inner.style.height = '100px';
inner.style.width = '100%';
outer.appendChild(inner);
document.body.appendChild(outer);
var outerWidth = outer.clientWidth;
outer.style.overflowY = 'scroll';
var innerWidth = inner.clientWidth;
document.body.removeChild(outer);
size = outerWidth - innerWidth;
}
return size;
}
module.exports = getScrollbarSize;
/***/ },
/* 27 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(108),
mapCacheDelete = __webpack_require__(109),
mapCacheGet = __webpack_require__(110),
mapCacheHas = __webpack_require__(111),
mapCacheSet = __webpack_require__(112);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(73),
arraySome = __webpack_require__(78),
cacheHas = __webpack_require__(87);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof (window) == 'object' && (window) && (window).Object === Object && (window);
module.exports = freeGlobal;
/***/ },
/* 31 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ },
/* 32 */
/***/ function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ },
/* 33 */
/***/ function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(130);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(39)(module)))
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(12),
isObject = __webpack_require__(21);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ },
/* 36 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(83),
baseUnary = __webpack_require__(86),
nodeUtil = __webpack_require__(115);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ },
/* 38 */
/***/ function(module, exports) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 39 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _keyMirror = __webpack_require__(68);
var _keyMirror2 = _interopRequireDefault(_keyMirror);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var constants = {
UpdateActions: (0, _keyMirror2['default'])({
CELL_UPDATE: null,
COLUMN_FILL: null,
COPY_PASTE: null,
CELL_DRAG: null
})
};
exports['default'] = constants;
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _shallowEqual = __webpack_require__(27);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _RowsContainer = __webpack_require__(55);
var _RowsContainer2 = _interopRequireDefault(_RowsContainer);
var _RowGroup = __webpack_require__(54);
var _RowGroup2 = _interopRequireDefault(_RowGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(4);
var PropTypes = React.PropTypes;
var ScrollShim = __webpack_require__(56);
var Row = __webpack_require__(17);
var cellMetaDataShape = __webpack_require__(8);
var RowUtils = __webpack_require__(24);
var Canvas = React.createClass({
displayName: 'Canvas',
mixins: [ScrollShim],
propTypes: {
rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
rowHeight: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
width: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
style: PropTypes.string,
className: PropTypes.string,
displayStart: PropTypes.number.isRequired,
displayEnd: PropTypes.number.isRequired,
rowsCount: PropTypes.number.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]),
expandedRows: PropTypes.array,
onRows: PropTypes.func,
onScroll: PropTypes.func,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired,
selectedRows: PropTypes.array,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowGroupRenderer: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
rowRenderer: Row,
onRows: function onRows() {},
selectedRows: [],
rowScrollTimeout: 0
};
},
getInitialState: function getInitialState() {
return {
displayStart: this.props.displayStart,
displayEnd: this.props.displayEnd,
scrollingTimeout: null
};
},
componentWillMount: function componentWillMount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidMount: function componentDidMount() {
this.onRows();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.displayStart !== this.state.displayStart || nextProps.displayEnd !== this.state.displayEnd) {
this.setState({
displayStart: nextProps.displayStart,
displayEnd: nextProps.displayEnd
});
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var shouldUpdate = nextState.displayStart !== this.state.displayStart || nextState.displayEnd !== this.state.displayEnd || nextState.scrollingTimeout !== this.state.scrollingTimeout || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !(0, _shallowEqual2['default'])(nextProps.style, this.props.style);
return shouldUpdate;
},
componentWillUnmount: function componentWillUnmount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidUpdate: function componentDidUpdate() {
if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) {
this.setScrollLeft(this._scroll.scrollLeft);
}
this.onRows();
},
onRows: function onRows() {
if (this._currentRowsRange !== { start: 0, end: 0 }) {
this.props.onRows(this._currentRowsRange);
this._currentRowsRange = { start: 0, end: 0 };
}
},
onScroll: function onScroll(e) {
var _this = this;
if (ReactDOM.findDOMNode(this) !== e.target) {
return;
}
this.appendScrollShim();
var scrollLeft = e.target.scrollLeft;
var scrollTop = e.target.scrollTop;
var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft };
// check how far we have scrolled, and if this means we are being taken out of range
var scrollYRange = Math.abs(this._scroll.scrollTop - scroll.scrollTop) / this.props.rowHeight;
var scrolledOutOfRange = scrollYRange > this.props.displayEnd - this.props.displayStart;
this._scroll = scroll;
this.props.onScroll(scroll);
// if we go out of range, we queue the actual render, just rendering cheap placeholders
// avoiding rendering anything expensive while a user scrolls down
if (scrolledOutOfRange && this.props.rowScrollTimeout > 0) {
var scrollTO = this.state.scrollingTimeout;
if (scrollTO) {
clearTimeout(scrollTO);
}
// queue up, and set state to clear the TO so we render the rows (not placeholders)
scrollTO = setTimeout(function () {
if (_this.state.scrollingTimeout !== null) {
_this.setState({ scrollingTimeout: null });
}
}, this.props.rowScrollTimeout);
this.setState({ scrollingTimeout: scrollTO });
}
},
getSubRows: function getSubRows(row) {
var subRowDetails = this.props.getSubRowDetails(row);
if (subRowDetails.expanded === true) {
return subRowDetails.children.map(function (r) {
return { row: r };
});
}
},
addSubRows: function addSubRows(rowsInput, row, i, displayEnd, treeDepth) {
var _this2 = this;
var subRowDetails = this.props.getSubRowDetails(row) || {};
var rows = rowsInput;
var increment = i;
if (increment < displayEnd) {
subRowDetails.treeDepth = treeDepth;
rows.push({ row: row, subRowDetails: subRowDetails });
increment++;
}
if (subRowDetails && subRowDetails.expanded) {
var subRows = this.getSubRows(row);
subRows.forEach(function (sr) {
var result = _this2.addSubRows(rows, sr.row, increment, displayEnd, treeDepth + 1);
rows = result.rows;
increment = result.increment;
});
}
return { rows: rows, increment: increment };
},
getRows: function getRows(displayStart, displayEnd) {
this._currentRowsRange = { start: displayStart, end: displayEnd };
if (Array.isArray(this.props.rowGetter)) {
return this.props.rowGetter.slice(displayStart, displayEnd);
}
var rows = [];
var rowFetchIndex = displayStart;
var i = displayStart;
while (i < displayEnd) {
var row = this.props.rowGetter(rowFetchIndex);
if (this.props.getSubRowDetails) {
var treeDepth = 0;
var result = this.addSubRows(rows, row, i, displayEnd, treeDepth);
rows = result.rows;
i = result.increment;
} else {
rows.push({ row: row });
i++;
}
rowFetchIndex++;
}
return rows;
},
getScrollbarWidth: function getScrollbarWidth() {
var scrollbarWidth = 0;
// Get the scrollbar width
var canvas = ReactDOM.findDOMNode(this);
scrollbarWidth = canvas.offsetWidth - canvas.clientWidth;
return scrollbarWidth;
},
getScroll: function getScroll() {
var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this),
scrollTop = _ReactDOM$findDOMNode.scrollTop,
scrollLeft = _ReactDOM$findDOMNode.scrollLeft;
return { scrollTop: scrollTop, scrollLeft: scrollLeft };
},
isRowSelected: function isRowSelected(idx, row) {
var _this3 = this;
// Use selectedRows if set
if (this.props.selectedRows !== null) {
var selectedRows = this.props.selectedRows.filter(function (r) {
var rowKeyValue = row.get ? row.get(_this3.props.rowKey) : row[_this3.props.rowKey];
return r[_this3.props.rowKey] === rowKeyValue;
});
return selectedRows.length > 0 && selectedRows[0].isSelected;
}
// Else use new rowSelection props
if (this.props.rowSelection) {
var _props$rowSelection = this.props.rowSelection,
keys = _props$rowSelection.keys,
indexes = _props$rowSelection.indexes,
isSelectedKey = _props$rowSelection.isSelectedKey;
return RowUtils.isRowSelected(keys, indexes, isSelectedKey, row, idx);
}
return false;
},
_currentRowsLength: 0,
_currentRowsRange: { start: 0, end: 0 },
_scroll: { scrollTop: 0, scrollLeft: 0 },
setScrollLeft: function setScrollLeft(scrollLeft) {
if (this._currentRowsLength !== 0) {
if (!this.refs) return;
for (var i = 0, len = this._currentRowsLength; i < len; i++) {
if (this.refs[i]) {
var row = this.getRowByRef(i);
if (row && row.setScrollLeft) {
row.setScrollLeft(scrollLeft);
}
}
}
}
},
getRowByRef: function getRowByRef(i) {
// check if wrapped with React DND drop target
var wrappedRow = this.refs[i].getDecoratedComponentInstance ? this.refs[i].getDecoratedComponentInstance(i) : null;
if (wrappedRow) {
return wrappedRow.refs.row;
}
return this.refs[i];
},
renderRow: function renderRow(props) {
var row = props.row;
if (row.__metaData && row.__metaData.isGroup) {
return React.createElement(_RowGroup2['default'], _extends({
key: props.key,
name: row.name
}, row.__metaData, {
row: props.row,
idx: props.idx,
height: props.height,
cellMetaData: this.props.cellMetaData,
renderer: this.props.rowGroupRenderer
}));
}
if (this.state.scrollingTimeout !== null) {
// in the midst of a rapid scroll, so we render placeholders
// the actual render is then queued (through a timeout)
// this avoids us redering a bunch of rows that a user is trying to scroll past
return this.renderScrollingPlaceholder(props);
}
var RowsRenderer = this.props.rowRenderer;
if (typeof RowsRenderer === 'function') {
return React.createElement(RowsRenderer, props);
}
if (React.isValidElement(this.props.rowRenderer)) {
return React.cloneElement(this.props.rowRenderer, props);
}
},
renderScrollingPlaceholder: function renderScrollingPlaceholder(props) {
// here we are just rendering empty cells
// we may want to allow a user to inject this, and/or just render the cells that are in view
// for now though we essentially are doing a (very lightweight) row + cell with empty content
var styles = {
row: { height: props.height, overflow: 'hidden' },
cell: { height: props.height, position: 'absolute' },
placeholder: { backgroundColor: 'rgba(211, 211, 211, 0.45)', width: '60%', height: Math.floor(props.height * 0.3) }
};
return React.createElement(
'div',
{ key: props.key, style: styles.row, className: 'react-grid-Row' },
this.props.columns.map(function (col, idx) {
return React.createElement(
'div',
{ style: Object.assign(styles.cell, { width: col.width, left: col.left }), key: idx, className: 'react-grid-Cell' },
React.createElement('div', { style: Object.assign(styles.placeholder, { width: Math.floor(col.width * 0.6) }) })
);
})
);
},
renderPlaceholder: function renderPlaceholder(key, height) {
// just renders empty cells
// if we wanted to show gridlines, we'd need classes and position as with renderScrollingPlaceholder
return React.createElement(
'div',
{ key: key, style: { height: height } },
this.props.columns.map(function (column, idx) {
return React.createElement('div', { style: { width: column.width }, key: idx });
})
);
},
render: function render() {
var _this4 = this;
var displayStart = this.state.displayStart;
var displayEnd = this.state.displayEnd;
var rowHeight = this.props.rowHeight;
var length = this.props.rowsCount;
var rows = this.getRows(displayStart, displayEnd).map(function (r, idx) {
return _this4.renderRow({
key: displayStart + idx,
ref: idx,
idx: displayStart + idx,
row: r.row,
height: rowHeight,
onMouseOver: _this4.onMouseOver,
columns: _this4.props.columns,
isSelected: _this4.isRowSelected(displayStart + idx, r.row, displayStart, displayEnd),
expandedRows: _this4.props.expandedRows,
cellMetaData: _this4.props.cellMetaData,
subRowDetails: r.subRowDetails
});
});
this._currentRowsLength = rows.length;
if (displayStart > 0) {
rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight));
}
if (length - displayEnd > 0) {
rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight));
}
var style = {
position: 'absolute',
top: 0,
left: 0,
overflowX: 'auto',
overflowY: 'scroll',
width: this.props.totalWidth,
height: this.props.height,
transform: 'translate3d(0, 0, 0)'
};
return React.createElement(
'div',
{
style: style,
onScroll: this.onScroll,
className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) },
React.createElement(_RowsContainer2['default'], {
width: this.props.width,
rows: rows,
contextMenu: this.props.contextMenu,
rowIdx: this.props.cellMetaData.selected.rowIdx,
idx: this.props.cellMetaData.selected.idx })
);
}
});
module.exports = Canvas;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isValidElement = __webpack_require__(1).isValidElement;
module.exports = function sameColumn(a, b) {
var k = void 0;
for (k in a) {
if (a.hasOwnProperty(k)) {
if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) {
continue;
}
if (!b.hasOwnProperty(k) || a[k] !== b[k]) {
return false;
}
}
}
for (k in b) {
if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) {
return false;
}
}
return true;
};
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ColumnMetrics = __webpack_require__(16);
var DOMMetrics = __webpack_require__(9);
Object.assign = __webpack_require__(38);
var PropTypes = __webpack_require__(1).PropTypes;
var ColumnUtils = __webpack_require__(5);
var Column = function Column() {
_classCallCheck(this, Column);
};
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
propTypes: {
columns: PropTypes.arrayOf(Column),
minColumnWidth: PropTypes.number,
columnEquality: PropTypes.func,
onColumnResize: PropTypes.func
},
DOMMetrics: {
gridWidth: function gridWidth() {
return _reactDom2['default'].findDOMNode(this).parentElement.offsetWidth;
}
},
getDefaultProps: function getDefaultProps() {
return {
minColumnWidth: 80,
columnEquality: ColumnMetrics.sameColumn
};
},
componentWillMount: function componentWillMount() {
this._mounted = true;
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.columns) {
if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) {
var columnMetrics = this.createColumnMetrics(nextProps);
this.setState({ columnMetrics: columnMetrics });
}
}
},
getTotalWidth: function getTotalWidth() {
var totalWidth = 0;
if (this._mounted) {
totalWidth = this.DOMMetrics.gridWidth();
} else {
totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth;
}
return totalWidth;
},
getColumnMetricsType: function getColumnMetricsType(metrics) {
var totalWidth = metrics.totalWidth || this.getTotalWidth();
var currentMetrics = {
columns: metrics.columns,
totalWidth: totalWidth,
minColumnWidth: metrics.minColumnWidth
};
var updatedMetrics = ColumnMetrics.recalculate(currentMetrics);
return updatedMetrics;
},
getColumn: function getColumn(idx) {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
getSize: function getSize() {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
metricsUpdated: function metricsUpdated() {
var columnMetrics = this.createColumnMetrics();
this.setState({ columnMetrics: columnMetrics });
},
createColumnMetrics: function createColumnMetrics() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var gridColumns = this.setupGridColumns(props);
return this.getColumnMetricsType({
columns: gridColumns,
minColumnWidth: this.props.minColumnWidth,
totalWidth: props.minWidth
});
},
onColumnResize: function onColumnResize(index, width) {
var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width);
this.setState({ columnMetrics: columnMetrics });
if (this.props.onColumnResize) {
this.props.onColumnResize(index, width);
}
}
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var Draggable = React.createClass({
displayName: 'Draggable',
propTypes: {
onDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrag: PropTypes.func,
component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor])
},
getDefaultProps: function getDefaultProps() {
return {
onDragStart: function onDragStart() {
return true;
},
onDragEnd: function onDragEnd() {},
onDrag: function onDrag() {}
};
},
getInitialState: function getInitialState() {
return {
drag: null
};
},
componentWillUnmount: function componentWillUnmount() {
this.cleanUp();
},
onMouseDown: function onMouseDown(e) {
var drag = this.props.onDragStart(e);
if (drag === null && e.button !== 0) {
return;
}
window.addEventListener('mouseup', this.onMouseUp);
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('touchend', this.onMouseUp);
window.addEventListener('touchmove', this.onMouseMove);
this.setState({ drag: drag });
},
onMouseMove: function onMouseMove(e) {
if (this.state.drag === null) {
return;
}
if (e.preventDefault) {
e.preventDefault();
}
this.props.onDrag(e);
},
onMouseUp: function onMouseUp(e) {
this.cleanUp();
this.props.onDragEnd(e, this.state.drag);
this.setState({ drag: null });
},
cleanUp: function cleanUp() {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
window.removeEventListener('touchmove', this.onMouseMove);
},
render: function render() {
return React.createElement('div', _extends({}, this.props, {
onMouseDown: this.onMouseDown,
onTouchStart: this.onMouseDown,
className: 'react-grid-HeaderCell__draggable' }));
}
});
module.exports = Draggable;
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var Header = __webpack_require__(47);
var Viewport = __webpack_require__(57);
var GridScrollMixin = __webpack_require__(46);
var DOMMetrics = __webpack_require__(9);
var cellMetaDataShape = __webpack_require__(8);
var Grid = React.createClass({
displayName: 'Grid',
propTypes: {
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
columnMetrics: PropTypes.object,
minHeight: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowHeight: PropTypes.number,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
emptyRowsView: PropTypes.func,
expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowsCount: PropTypes.number,
onRows: PropTypes.func,
sortColumn: React.PropTypes.string,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
rowOffsetHeight: PropTypes.number.isRequired,
onViewportKeydown: PropTypes.func.isRequired,
onViewportKeyup: PropTypes.func,
onViewportDragStart: PropTypes.func.isRequired,
onViewportDragEnd: PropTypes.func.isRequired,
onViewportDoubleClick: PropTypes.func.isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func,
rowGroupRenderer: PropTypes.func
},
mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin],
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 35,
minHeight: 350
};
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
outline: 0,
position: 'relative',
minHeight: this.props.minHeight
};
},
render: function render() {
var headerRows = this.props.headerRows || [{ ref: 'row' }];
var EmptyRowsView = this.props.emptyRowsView;
return React.createElement(
'div',
_extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }),
React.createElement(Header, {
ref: 'header',
columnMetrics: this.props.columnMetrics,
onColumnResize: this.props.onColumnResize,
height: this.props.rowHeight,
totalWidth: this.props.totalWidth,
headerRows: headerRows,
sortColumn: this.props.sortColumn,
sortDirection: this.props.sortDirection,
draggableHeaderCell: this.props.draggableHeaderCell,
onSort: this.props.onSort,
onScroll: this.onHeaderScroll,
getValidFilterValues: this.props.getValidFilterValues
}),
this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement(
'div',
{ ref: 'viewPortContainer', tabIndex: '0', onKeyDown: this.props.onViewportKeydown, onKeyUp: this.props.onViewportKeyup, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd },
React.createElement(Viewport, {
ref: 'viewport',
rowKey: this.props.rowKey,
width: this.props.columnMetrics.width,
rowHeight: this.props.rowHeight,
rowRenderer: this.props.rowRenderer,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columnMetrics: this.props.columnMetrics,
totalWidth: this.props.totalWidth,
onScroll: this.onScroll,
onRows: this.props.onRows,
cellMetaData: this.props.cellMetaData,
rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length,
minHeight: this.props.minHeight,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer
})
) : React.createElement(
'div',
{ ref: 'emptyView', className: 'react-grid-Empty' },
React.createElement(EmptyRowsView, null)
)
);
}
});
module.exports = Grid;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ReactDOM = __webpack_require__(2);
module.exports = {
componentDidMount: function componentDidMount() {
this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0;
this._onScroll();
},
componentDidUpdate: function componentDidUpdate() {
this._onScroll();
},
componentWillMount: function componentWillMount() {
this._scrollLeft = undefined;
},
componentWillUnmount: function componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll: function onScroll(props) {
if (this._scrollLeft !== props.scrollLeft) {
this._scrollLeft = props.scrollLeft;
this._onScroll();
}
},
onHeaderScroll: function onHeaderScroll(e) {
var scrollLeft = e.target.scrollLeft;
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this.refs.header.setScrollLeft(scrollLeft);
var canvas = ReactDOM.findDOMNode(this.refs.viewport.refs.canvas);
canvas.scrollLeft = scrollLeft;
this.refs.viewport.refs.canvas.setScrollLeft(scrollLeft);
}
},
_onScroll: function _onScroll() {
if (this._scrollLeft !== undefined) {
this.refs.header.setScrollLeft(this._scrollLeft);
if (this.refs.viewport) {
this.refs.viewport.setScrollLeft(this._scrollLeft);
}
}
}
};
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(4);
var shallowCloneObject = __webpack_require__(18);
var ColumnMetrics = __webpack_require__(16);
var ColumnUtils = __webpack_require__(5);
var HeaderRow = __webpack_require__(50);
var PropTypes = React.PropTypes;
var Header = React.createClass({
displayName: 'Header',
propTypes: {
columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
headerRows: PropTypes.array.isRequired,
sortColumn: PropTypes.string,
sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
onSort: PropTypes.func,
onColumnResize: PropTypes.func,
onScroll: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func
},
getInitialState: function getInitialState() {
return { resizing: null };
},
componentWillReceiveProps: function componentWillReceiveProps() {
this.setState({ resizing: null });
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
return update;
},
onColumnResize: function onColumnResize(column, width) {
var state = this.state.resizing || this.props;
var pos = this.getColumnPosition(column);
if (pos != null) {
var _resizing = {
columnMetrics: shallowCloneObject(state.columnMetrics)
};
_resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width);
// we don't want to influence scrollLeft while resizing
if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) {
_resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth;
}
_resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos);
this.setState({ resizing: _resizing });
}
},
onColumnResizeEnd: function onColumnResizeEnd(column, width) {
var pos = this.getColumnPosition(column);
if (pos !== null && this.props.onColumnResize) {
this.props.onColumnResize(pos, width || column.width);
}
},
getHeaderRows: function getHeaderRows() {
var _this = this;
var columnMetrics = this.getColumnMetrics();
var resizeColumn = void 0;
if (this.state.resizing) {
resizeColumn = this.state.resizing.column;
}
var headerRows = [];
this.props.headerRows.forEach(function (row, index) {
// To allow header filters to be visible
var rowHeight = 'auto';
if (row.rowType === 'filter') {
rowHeight = '500px';
}
var headerRowStyle = {
position: 'absolute',
top: _this.getCombinedHeaderHeights(index),
left: 0,
width: _this.props.totalWidth,
overflowX: 'hidden',
minHeight: rowHeight
};
headerRows.push(React.createElement(HeaderRow, {
key: row.ref,
ref: row.ref,
rowType: row.rowType,
style: headerRowStyle,
onColumnResize: _this.onColumnResize,
onColumnResizeEnd: _this.onColumnResizeEnd,
width: columnMetrics.width,
height: row.height || _this.props.height,
columns: columnMetrics.columns,
resizing: resizeColumn,
draggableHeaderCell: _this.props.draggableHeaderCell,
filterable: row.filterable,
onFilterChange: row.onFilterChange,
sortColumn: _this.props.sortColumn,
sortDirection: _this.props.sortDirection,
onSort: _this.props.onSort,
onScroll: _this.props.onScroll,
getValidFilterValues: _this.props.getValidFilterValues
}));
});
return headerRows;
},
getColumnMetrics: function getColumnMetrics() {
var columnMetrics = void 0;
if (this.state.resizing) {
columnMetrics = this.state.resizing.columnMetrics;
} else {
columnMetrics = this.props.columnMetrics;
}
return columnMetrics;
},
getColumnPosition: function getColumnPosition(column) {
var columnMetrics = this.getColumnMetrics();
var pos = -1;
columnMetrics.columns.forEach(function (c, idx) {
if (c.key === column.key) {
pos = idx;
}
});
return pos === -1 ? null : pos;
},
getCombinedHeaderHeights: function getCombinedHeaderHeights(until) {
var stopAt = this.props.headerRows.length;
if (typeof until !== 'undefined') {
stopAt = until;
}
var height = 0;
for (var index = 0; index < stopAt; index++) {
height += this.props.headerRows[index].height || this.props.height;
}
return height;
},
getStyle: function getStyle() {
return {
position: 'relative',
height: this.getCombinedHeaderHeights()
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this.refs.row);
node.scrollLeft = scrollLeft;
this.refs.row.setScrollLeft(scrollLeft);
if (this.refs.filterRow) {
var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow);
nodeFilters.scrollLeft = scrollLeft;
this.refs.filterRow.setScrollLeft(scrollLeft);
}
},
render: function render() {
var className = joinClasses({
'react-grid-Header': true,
'react-grid-Header--resizing': !!this.state.resizing
});
var headerRows = this.getHeaderRows();
return React.createElement(
'div',
_extends({}, this.props, { style: this.getStyle(), className: className }),
headerRows
);
}
});
module.exports = Header;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(4);
var ExcelColumn = __webpack_require__(6);
var ResizeHandle = __webpack_require__(53);
var PropTypes = React.PropTypes;
function simpleCellRenderer(objArgs) {
return React.createElement(
'div',
{ className: 'widget-HeaderCell__value' },
objArgs.column.name
);
}
var HeaderCell = React.createClass({
displayName: 'HeaderCell',
propTypes: {
renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired,
column: PropTypes.shape(ExcelColumn).isRequired,
onResize: PropTypes.func.isRequired,
height: PropTypes.number.isRequired,
onResizeEnd: PropTypes.func.isRequired,
className: PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
renderer: simpleCellRenderer
};
},
getInitialState: function getInitialState() {
return { resizing: false };
},
onDragStart: function onDragStart(e) {
this.setState({ resizing: true });
// need to set dummy data for FF
if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy');
},
onDrag: function onDrag(e) {
var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct
if (resize) {
var _width = this.getWidthFromMouseEvent(e);
if (_width > 0) {
resize(this.props.column, _width);
}
}
},
onDragEnd: function onDragEnd(e) {
var width = this.getWidthFromMouseEvent(e);
this.props.onResizeEnd(this.props.column, width);
this.setState({ resizing: false });
},
getWidthFromMouseEvent: function getWidthFromMouseEvent(e) {
var right = e.pageX || e.touches && e.touches[0] && e.touches[0].pageX || e.changedTouches && e.changedTouches[e.changedTouches.length - 1].pageX;
var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left;
return right - left;
},
getCell: function getCell() {
if (React.isValidElement(this.props.renderer)) {
return React.cloneElement(this.props.renderer, { column: this.props.column, height: this.props.height });
}
return this.props.renderer({ column: this.props.column });
},
getStyle: function getStyle() {
return {
width: this.props.column.width,
left: this.props.column.left,
display: 'inline-block',
position: 'absolute',
height: this.props.height,
margin: 0,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this);
node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
},
render: function render() {
var resizeHandle = void 0;
if (this.props.column.resizable) {
resizeHandle = React.createElement(ResizeHandle, {
onDrag: this.onDrag,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd
});
}
var className = joinClasses({
'react-grid-HeaderCell': true,
'react-grid-HeaderCell--resizing': this.state.resizing,
'react-grid-HeaderCell--locked': this.props.column.locked
});
className = joinClasses(className, this.props.className, this.props.column.cellClass);
var cell = this.getCell();
return React.createElement(
'div',
{ className: className, style: this.getStyle() },
cell,
resizeHandle
);
}
});
module.exports = HeaderCell;
/***/ },
/* 49 */
/***/ function(module, exports) {
"use strict";
var HeaderCellType = {
SORTABLE: 0,
FILTERABLE: 1,
NONE: 2,
CHECKBOX: 3
};
module.exports = HeaderCellType;
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var shallowEqual = __webpack_require__(27);
var BaseHeaderCell = __webpack_require__(48);
var getScrollbarSize = __webpack_require__(26);
var ExcelColumn = __webpack_require__(6);
var ColumnUtilsMixin = __webpack_require__(5);
var SortableHeaderCell = __webpack_require__(60);
var FilterableHeaderCell = __webpack_require__(59);
var HeaderCellType = __webpack_require__(49);
var PropTypes = React.PropTypes;
var HeaderRowStyle = {
overflow: React.PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: React.PropTypes.number,
position: React.PropTypes.string
};
var DEFINE_SORT = ['ASC', 'DESC', 'NONE'];
var HeaderRow = React.createClass({
displayName: 'HeaderRow',
propTypes: {
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
onColumnResize: PropTypes.func,
onSort: PropTypes.func.isRequired,
onColumnResizeEnd: PropTypes.func,
style: PropTypes.shape(HeaderRowStyle),
sortColumn: PropTypes.string,
sortDirection: React.PropTypes.oneOf(DEFINE_SORT),
cellRenderer: PropTypes.func,
headerCellRenderer: PropTypes.func,
filterable: PropTypes.bool,
onFilterChange: PropTypes.func,
resizing: PropTypes.object,
onScroll: PropTypes.func,
rowType: PropTypes.string,
draggableHeaderCell: PropTypes.func
},
mixins: [ColumnUtilsMixin],
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
},
getHeaderCellType: function getHeaderCellType(column) {
if (column.filterable) {
if (this.props.filterable) return HeaderCellType.FILTERABLE;
}
if (column.sortable) return HeaderCellType.SORTABLE;
return HeaderCellType.NONE;
},
getFilterableHeaderCell: function getFilterableHeaderCell(column) {
var FilterRenderer = FilterableHeaderCell;
if (column.filterRenderer !== undefined) {
FilterRenderer = column.filterRenderer;
}
return React.createElement(FilterRenderer, _extends({}, this.props, { onChange: this.props.onFilterChange }));
},
getSortableHeaderCell: function getSortableHeaderCell(column) {
var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE;
return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection });
},
getHeaderRenderer: function getHeaderRenderer(column) {
var renderer = void 0;
if (column.headerRenderer) {
renderer = column.headerRenderer;
} else {
var headerCellType = this.getHeaderCellType(column);
switch (headerCellType) {
case HeaderCellType.SORTABLE:
renderer = this.getSortableHeaderCell(column);
break;
case HeaderCellType.FILTERABLE:
renderer = this.getFilterableHeaderCell(column);
break;
default:
break;
}
}
return renderer;
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
width: '100%',
height: this.props.height,
position: 'absolute'
};
},
getCells: function getCells() {
var cells = [];
var lockedCells = [];
for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) {
var column = this.getColumn(this.props.columns, i);
var _renderer = this.getHeaderRenderer(column);
if (column.key === 'select-row' && this.props.rowType === 'filter') {
_renderer = React.createElement('div', null);
}
var _HeaderCell = column.draggable ? this.props.draggableHeaderCell : BaseHeaderCell;
var cell = React.createElement(_HeaderCell, {
ref: i,
key: i,
height: this.props.height,
column: column,
renderer: _renderer,
resizing: this.props.resizing === column,
onResize: this.props.onColumnResize,
onResizeEnd: this.props.onColumnResizeEnd
});
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
}
return cells.concat(lockedCells);
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
_this.refs[i].setScrollLeft(scrollLeft);
}
});
},
render: function render() {
var cellsStyle = {
width: this.props.width ? this.props.width + getScrollbarSize() : '100%',
height: this.props.height,
whiteSpace: 'nowrap',
overflowX: 'hidden',
overflowY: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.props, { className: 'react-grid-HeaderRow', onScroll: this.props.onScroll }),
React.createElement(
'div',
{ style: cellsStyle },
cells
)
);
}
});
module.exports = HeaderRow;
/***/ },
/* 51 */
/***/ function(module, exports) {
"use strict";
module.exports = {
Backspace: 8,
Tab: 9,
Enter: 13,
Shift: 16,
Ctrl: 17,
Alt: 18,
PauseBreak: 19,
CapsLock: 20,
Escape: 27,
PageUp: 33,
PageDown: 34,
End: 35,
Home: 36,
LeftArrow: 37,
UpArrow: 38,
RightArrow: 39,
DownArrow: 40,
Insert: 45,
Delete: 46,
0: 48,
1: 49,
2: 50,
3: 51,
4: 52,
5: 53,
6: 54,
7: 55,
8: 56,
9: 57,
a: 65,
b: 66,
c: 67,
d: 68,
e: 69,
f: 70,
g: 71,
h: 72,
i: 73,
j: 74,
k: 75,
l: 76,
m: 77,
n: 78,
o: 79,
p: 80,
q: 81,
r: 82,
s: 83,
t: 84,
u: 85,
v: 86,
w: 87,
x: 88,
y: 89,
z: 90,
LeftWindowKey: 91,
RightWindowKey: 92,
SelectKey: 93,
NumPad0: 96,
NumPad1: 97,
NumPad2: 98,
NumPad3: 99,
NumPad4: 100,
NumPad5: 101,
NumPad6: 102,
NumPad7: 103,
NumPad8: 104,
NumPad9: 105,
Multiply: 106,
Add: 107,
Subtract: 109,
DecimalPoint: 110,
Divide: 111,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F12: 123,
NumLock: 144,
ScrollLock: 145,
SemiColon: 186,
EqualSign: 187,
Comma: 188,
Dash: 189,
Period: 190,
ForwardSlash: 191,
GraveAccent: 192,
OpenBracket: 219,
BackSlash: 220,
CloseBracket: 221,
SingleQuote: 222
};
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _AppConstants = __webpack_require__(40);
var _AppConstants2 = _interopRequireDefault(_AppConstants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var BaseGrid = __webpack_require__(45);
var Row = __webpack_require__(17);
var ExcelColumn = __webpack_require__(6);
var KeyboardHandlerMixin = __webpack_require__(23);
var CheckboxEditor = __webpack_require__(61);
var DOMMetrics = __webpack_require__(9);
var ColumnMetricsMixin = __webpack_require__(43);
var RowUtils = __webpack_require__(24);
var ColumnUtils = __webpack_require__(5);
var KeyCodes = __webpack_require__(51);
if (!Object.assign) {
Object.assign = __webpack_require__(38);
}
var ReactDataGrid = React.createClass({
displayName: 'ReactDataGrid',
mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin],
propTypes: {
rowHeight: React.PropTypes.number.isRequired,
headerRowHeight: React.PropTypes.number,
minHeight: React.PropTypes.number.isRequired,
minWidth: React.PropTypes.number,
enableRowSelect: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]),
onRowUpdated: React.PropTypes.func,
rowGetter: React.PropTypes.func.isRequired,
rowsCount: React.PropTypes.number.isRequired,
toolbar: React.PropTypes.element,
enableCellSelect: React.PropTypes.bool,
columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired,
onFilter: React.PropTypes.func,
onCellCopyPaste: React.PropTypes.func,
onCellsDragged: React.PropTypes.func,
onAddFilter: React.PropTypes.func,
onGridSort: React.PropTypes.func,
onDragHandleDoubleClick: React.PropTypes.func,
onGridRowsUpdated: React.PropTypes.func,
onRowSelect: React.PropTypes.func,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
onClearFilters: React.PropTypes.func,
contextMenu: React.PropTypes.element,
cellNavigationMode: React.PropTypes.oneOf(['none', 'loopOverRow', 'changeRow']),
onCellSelected: React.PropTypes.func,
onCellDeSelected: React.PropTypes.func,
onCellExpand: React.PropTypes.func,
enableDragAndDrop: React.PropTypes.bool,
onRowExpandToggle: React.PropTypes.func,
draggableHeaderCell: React.PropTypes.func,
getValidFilterValues: React.PropTypes.func,
rowSelection: React.PropTypes.shape({
enableShiftSelect: React.PropTypes.bool,
onRowsSelected: React.PropTypes.func,
onRowsDeselected: React.PropTypes.func,
showCheckbox: React.PropTypes.bool,
selectBy: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]).isRequired
}),
onRowClick: React.PropTypes.func,
onGridKeyUp: React.PropTypes.func,
onGridKeyDown: React.PropTypes.func,
rowGroupRenderer: React.PropTypes.func,
rowActionsCell: React.PropTypes.func,
onCheckCellIsEditable: React.PropTypes.func
/* called before cell is set active, returns a boolean to determine whether cell is editable */
},
getDefaultProps: function getDefaultProps() {
return {
enableCellSelect: false,
tabIndex: -1,
rowHeight: 35,
enableRowSelect: false,
minHeight: 350,
rowKey: 'id',
rowScrollTimeout: 0,
cellNavigationMode: 'none'
};
},
getInitialState: function getInitialState() {
var columnMetrics = this.createColumnMetrics();
var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0, lastRowIdxUiSelected: -1 };
if (this.props.enableCellSelect) {
initialState.selected = { rowIdx: 0, idx: 0 };
} else {
initialState.selected = { rowIdx: -1, idx: -1 };
}
return initialState;
},
hasSelectedCellChanged: function hasSelectedCellChanged(selected) {
var previouslySelected = Object.assign({}, this.state.selected);
return previouslySelected.rowIdx !== selected.rowIdx || previouslySelected.idx !== selected.idx || previouslySelected.active === false;
},
onContextMenuHide: function onContextMenuHide() {
document.removeEventListener('click', this.onContextMenuHide);
var newSelected = Object.assign({}, this.state.selected, { contextMenuDisplayed: false });
this.setState({ selected: newSelected });
},
onColumnEvent: function onColumnEvent(ev, columnEvent) {
var idx = columnEvent.idx,
name = columnEvent.name;
if (name && typeof idx !== 'undefined') {
var column = this.getColumn(idx);
if (column && column.events && column.events[name] && typeof column.events[name] === 'function') {
var eventArgs = {
rowIdx: columnEvent.rowIdx,
idx: idx,
column: column
};
column.events[name](ev, eventArgs);
}
}
},
onSelect: function onSelect(selected) {
var _this = this;
if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) {
var _idx = selected.idx;
var _rowIdx = selected.rowIdx;
if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) {
(function () {
var oldSelection = _this.state.selected;
_this.setState({ selected: selected }, function () {
if (typeof _this.props.onCellDeSelected === 'function') {
_this.props.onCellDeSelected(oldSelection);
}
if (typeof _this.props.onCellSelected === 'function') {
_this.props.onCellSelected(selected);
}
});
})();
}
}
},
onCellClick: function onCellClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
if (this.props.onRowClick && typeof this.props.onRowClick === 'function') {
this.props.onRowClick(cell.rowIdx, this.props.rowGetter(cell.rowIdx));
}
},
onCellContextMenu: function onCellContextMenu(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx, contextMenuDisplayed: this.props.contextMenu });
if (this.props.contextMenu) {
document.addEventListener('click', this.onContextMenuHide);
}
},
onCellDoubleClick: function onCellDoubleClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
this.setActive('Enter');
},
onViewportDoubleClick: function onViewportDoubleClick() {
this.setActive();
},
onPressArrowUp: function onPressArrowUp(e) {
this.moveSelectedCell(e, -1, 0);
},
onPressArrowDown: function onPressArrowDown(e) {
this.moveSelectedCell(e, 1, 0);
},
onPressArrowLeft: function onPressArrowLeft(e) {
this.moveSelectedCell(e, 0, -1);
},
onPressArrowRight: function onPressArrowRight(e) {
this.moveSelectedCell(e, 0, 1);
},
onPressTab: function onPressTab(e) {
this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1);
},
onPressEnter: function onPressEnter(e) {
this.setActive(e.key);
},
onPressDelete: function onPressDelete(e) {
this.setActive(e.key);
},
onPressEscape: function onPressEscape(e) {
this.setInactive(e.key);
},
onPressBackspace: function onPressBackspace(e) {
this.setActive(e.key);
},
onPressChar: function onPressChar(e) {
if (this.isKeyPrintable(e.keyCode)) {
this.setActive(e.keyCode);
}
},
onPressKeyWithCtrl: function onPressKeyWithCtrl(e) {
var keys = {
KeyCode_c: 99,
KeyCode_C: 67,
KeyCode_V: 86,
KeyCode_v: 118
};
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) {
var _value = this.getSelectedValue();
this.handleCopy({ value: _value });
} else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) {
this.handlePaste();
}
}
},
onGridRowsUpdated: function onGridRowsUpdated(cellKey, fromRow, toRow, updated, action) {
var rowIds = [];
for (var i = fromRow; i <= toRow; i++) {
rowIds.push(this.props.rowGetter(i)[this.props.rowKey]);
}
this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, rowIds: rowIds, updated: updated, action: action });
},
onCellCommit: function onCellCommit(commit) {
var selected = Object.assign({}, this.state.selected);
selected.active = false;
if (commit.key === 'Tab') {
selected.idx += 1;
}
var expandedRows = this.state.expandedRows;
// if(commit.changed && commit.changed.expandedHeight){
// expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight);
// }
this.setState({ selected: selected, expandedRows: expandedRows });
if (this.props.onRowUpdated) {
this.props.onRowUpdated(commit);
}
var targetRow = commit.rowIdx;
if (this.props.onGridRowsUpdated) {
this.onGridRowsUpdated(commit.cellKey, targetRow, targetRow, commit.updated, _AppConstants2['default'].UpdateActions.CELL_UPDATE);
}
},
onDragStart: function onDragStart(e) {
var idx = this.state.selected.idx;
if (idx > -1) {
var _value2 = this.getSelectedValue();
this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: _value2 });
// need to set dummy data for FF
if (e && e.dataTransfer) {
if (e.dataTransfer.setData) {
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', 'dummy');
}
}
}
},
onToggleFilter: function onToggleFilter() {
var _this2 = this;
// setState() does not immediately mutate this.state but creates a pending state transition.
// Therefore if you want to do something after the state change occurs, pass it in as a callback function.
this.setState({ canFilter: !this.state.canFilter }, function () {
if (_this2.state.canFilter === false && _this2.props.onClearFilters) {
_this2.props.onClearFilters();
}
});
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
if (this.props.onDragHandleDoubleClick) {
this.props.onDragHandleDoubleClick(e);
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated;
var cellKey = this.getColumn(e.idx).key;
this.onGridRowsUpdated(cellKey, e.rowIdx, this.props.rowsCount - 1, (_onGridRowsUpdated = {}, _onGridRowsUpdated[cellKey] = e.rowData[cellKey], _onGridRowsUpdated), _AppConstants2['default'].UpdateActions.COLUMN_FILL);
}
},
onCellExpand: function onCellExpand(args) {
if (this.props.onCellExpand) {
this.props.onCellExpand(args);
}
},
onRowExpandToggle: function onRowExpandToggle(args) {
if (typeof this.props.onRowExpandToggle === 'function') {
this.props.onRowExpandToggle(args);
}
},
handleDragStart: function handleDragStart(dragged) {
if (!this.dragEnabled()) {
return;
}
var idx = dragged.idx;
var rowIdx = dragged.rowIdx;
if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) {
this.setState({ dragged: dragged });
}
},
handleDragEnd: function handleDragEnd() {
if (!this.dragEnabled()) {
return;
}
var selected = this.state.selected;
var dragged = this.state.dragged;
var cellKey = this.getColumn(this.state.selected.idx).key;
var fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
var toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
if (this.props.onCellsDragged) {
this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated2;
this.onGridRowsUpdated(cellKey, fromRow, toRow, (_onGridRowsUpdated2 = {}, _onGridRowsUpdated2[cellKey] = dragged.value, _onGridRowsUpdated2), _AppConstants2['default'].UpdateActions.CELL_DRAG);
}
this.setState({ dragged: { complete: true } });
},
handleDragEnter: function handleDragEnter(row) {
if (!this.dragEnabled() || this.state.dragged == null) {
return;
}
var dragged = this.state.dragged;
dragged.overRowIdx = row;
this.setState({ dragged: dragged });
},
handleTerminateDrag: function handleTerminateDrag() {
if (!this.dragEnabled()) {
return;
}
this.setState({ dragged: null });
},
handlePaste: function handlePaste() {
if (!this.copyPasteEnabled()) {
return;
}
var selected = this.state.selected;
var cellKey = this.getColumn(this.state.selected.idx).key;
var textToCopy = this.state.textToCopy;
var fromRow = this.state.copied.rowIdx;
var toRow = selected.rowIdx;
if (this.props.onCellCopyPaste) {
this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: toRow, value: textToCopy, fromRow: fromRow, toRow: toRow });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated3;
this.onGridRowsUpdated(cellKey, toRow, toRow, (_onGridRowsUpdated3 = {}, _onGridRowsUpdated3[cellKey] = textToCopy, _onGridRowsUpdated3), _AppConstants2['default'].UpdateActions.COPY_PASTE);
}
this.setState({ copied: null });
},
handleCopy: function handleCopy(args) {
if (!this.copyPasteEnabled()) {
return;
}
var textToCopy = args.value;
var selected = this.state.selected;
var copied = { idx: selected.idx, rowIdx: selected.rowIdx };
this.setState({ textToCopy: textToCopy, copied: copied });
},
handleSort: function handleSort(columnKey, direction) {
this.setState({ sortDirection: direction, sortColumn: columnKey }, function () {
this.props.onGridSort(columnKey, direction);
});
},
getSelectedRow: function getSelectedRow(rows, key) {
var _this3 = this;
var selectedRow = rows.filter(function (r) {
if (r[_this3.props.rowKey] === key) {
return true;
}
return false;
});
if (selectedRow.length > 0) {
return selectedRow[0];
}
},
useNewRowSelection: function useNewRowSelection() {
return this.props.rowSelection && this.props.rowSelection.selectBy;
},
// return false if not a shift select so can be handled as normal row selection
handleShiftSelect: function handleShiftSelect(rowIdx) {
if (this.state.lastRowIdxUiSelected > -1 && this.isSingleKeyDown(KeyCodes.Shift)) {
var _props$rowSelection$s = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s.keys,
indexes = _props$rowSelection$s.indexes,
isSelectedKey = _props$rowSelection$s.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, this.props.rowGetter(rowIdx), rowIdx);
if (isPreviouslySelected) return false;
var handled = false;
if (rowIdx > this.state.lastRowIdxUiSelected) {
var rowsSelected = [];
for (var i = this.state.lastRowIdxUiSelected + 1; i <= rowIdx; i++) {
rowsSelected.push({ rowIdx: i, row: this.props.rowGetter(i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(rowsSelected);
}
handled = true;
} else if (rowIdx < this.state.lastRowIdxUiSelected) {
var _rowsSelected = [];
for (var _i = rowIdx; _i <= this.state.lastRowIdxUiSelected - 1; _i++) {
_rowsSelected.push({ rowIdx: _i, row: this.props.rowGetter(_i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(_rowsSelected);
}
handled = true;
}
if (handled) {
this.setState({ lastRowIdxUiSelected: rowIdx });
}
return handled;
}
return false;
},
handleNewRowSelect: function handleNewRowSelect(rowIdx, rowData) {
var _props$rowSelection$s2 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s2.keys,
indexes = _props$rowSelection$s2.indexes,
isSelectedKey = _props$rowSelection$s2.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx);
this.setState({ lastRowIdxUiSelected: isPreviouslySelected ? -1 : rowIdx, selected: { rowIdx: rowIdx, idx: 0 } });
if (isPreviouslySelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
this.props.rowSelection.onRowsDeselected([{ rowIdx: rowIdx, row: rowData }]);
} else if (!isPreviouslySelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected([{ rowIdx: rowIdx, row: rowData }]);
}
},
// columnKey not used here as this function will select the whole row,
// but needed to match the function signature in the CheckboxEditor
handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) {
e.stopPropagation();
if (this.useNewRowSelection()) {
if (this.props.rowSelection.enableShiftSelect === true) {
if (!this.handleShiftSelect(rowIdx)) {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
// Fallback to old onRowSelect handler
var _selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0);
var selectedRow = this.getSelectedRow(_selectedRows, rowData[this.props.rowKey]);
if (selectedRow) {
selectedRow.isSelected = !selectedRow.isSelected;
} else {
rowData.isSelected = true;
_selectedRows.push(rowData);
}
this.setState({ selectedRows: _selectedRows, selected: { rowIdx: rowIdx, idx: 0 } });
if (this.props.onRowSelect) {
this.props.onRowSelect(_selectedRows.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
handleCheckboxChange: function handleCheckboxChange(e) {
var allRowsSelected = void 0;
if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) {
allRowsSelected = true;
} else {
allRowsSelected = false;
}
if (this.useNewRowSelection()) {
var _props$rowSelection$s3 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s3.keys,
indexes = _props$rowSelection$s3.indexes,
isSelectedKey = _props$rowSelection$s3.isSelectedKey;
if (allRowsSelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
var _selectedRows2 = [];
for (var i = 0; i < this.props.rowsCount; i++) {
var rowData = this.props.rowGetter(i);
if (!RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, i)) {
_selectedRows2.push({ rowIdx: i, row: rowData });
}
}
if (_selectedRows2.length > 0) {
this.props.rowSelection.onRowsSelected(_selectedRows2);
}
} else if (!allRowsSelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
var deselectedRows = [];
for (var _i2 = 0; _i2 < this.props.rowsCount; _i2++) {
var _rowData = this.props.rowGetter(_i2);
if (RowUtils.isRowSelected(keys, indexes, isSelectedKey, _rowData, _i2)) {
deselectedRows.push({ rowIdx: _i2, row: _rowData });
}
}
if (deselectedRows.length > 0) {
this.props.rowSelection.onRowsDeselected(deselectedRows);
}
}
} else {
var _selectedRows3 = [];
for (var _i3 = 0; _i3 < this.props.rowsCount; _i3++) {
var row = Object.assign({}, this.props.rowGetter(_i3), { isSelected: allRowsSelected });
_selectedRows3.push(row);
}
this.setState({ selectedRows: _selectedRows3 });
if (typeof this.props.onRowSelect === 'function') {
this.props.onRowSelect(_selectedRows3.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
getScrollOffSet: function getScrollOffSet() {
var scrollOffset = 0;
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
scrollOffset = canvas.offsetWidth - canvas.clientWidth;
}
this.setState({ scrollOffset: scrollOffset });
},
getRowOffsetHeight: function getRowOffsetHeight() {
var offsetHeight = 0;
this.getHeaderRows().forEach(function (row) {
return offsetHeight += parseFloat(row.height, 10);
});
return offsetHeight;
},
getHeaderRows: function getHeaderRows() {
var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight, rowType: 'header' }];
if (this.state.canFilter === true) {
rows.push({
ref: 'filterRow',
filterable: true,
onFilterChange: this.props.onAddFilter,
height: 45,
rowType: 'filter'
});
}
return rows;
},
getInitialSelectedRows: function getInitialSelectedRows() {
var selectedRows = [];
for (var i = 0; i < this.props.rowsCount; i++) {
selectedRows.push(false);
}
return selectedRows;
},
getRowSelectionProps: function getRowSelectionProps() {
if (this.props.rowSelection) {
return this.props.rowSelection.selectBy;
}
return null;
},
getSelectedRows: function getSelectedRows() {
if (this.props.rowSelection) {
return null;
}
return this.state.selectedRows.filter(function (r) {
return r.isSelected === true;
});
},
getSelectedValue: function getSelectedValue() {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
var cellKey = this.getColumn(idx).key;
var row = this.props.rowGetter(rowIdx);
return RowUtils.get(row, cellKey);
},
moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) {
// we need to prevent default as we control grid scroll
// otherwise it moves every time you left/right which is janky
e.preventDefault();
var rowIdx = void 0;
var idx = void 0;
var cellNavigationMode = this.props.cellNavigationMode;
if (cellNavigationMode !== 'none') {
var _calculateNextSelecti = this.calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta);
idx = _calculateNextSelecti.idx;
rowIdx = _calculateNextSelecti.rowIdx;
} else {
rowIdx = this.state.selected.rowIdx + rowDelta;
idx = this.state.selected.idx + cellDelta;
}
this.onSelect({ idx: idx, rowIdx: rowIdx });
},
getNbrColumns: function getNbrColumns() {
var _props = this.props,
columns = _props.columns,
enableRowSelect = _props.enableRowSelect;
return enableRowSelect ? columns.length + 1 : columns.length;
},
calculateNextSelectionPosition: function calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta) {
var _rowDelta = rowDelta;
var idx = this.state.selected.idx + cellDelta;
var nbrColumns = this.getNbrColumns();
if (cellDelta > 0) {
if (this.isAtLastCellInRow(nbrColumns)) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtLastRow() ? rowDelta : rowDelta + 1;
idx = this.isAtLastRow() ? idx : 0;
} else {
idx = 0;
}
}
} else if (cellDelta < 0) {
if (this.isAtFirstCellInRow()) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtFirstRow() ? rowDelta : rowDelta - 1;
idx = this.isAtFirstRow() ? 0 : nbrColumns - 1;
} else {
idx = nbrColumns - 1;
}
}
}
var rowIdx = this.state.selected.rowIdx + _rowDelta;
return { idx: idx, rowIdx: rowIdx };
},
isAtLastCellInRow: function isAtLastCellInRow(nbrColumns) {
return this.state.selected.idx === nbrColumns - 1;
},
isAtLastRow: function isAtLastRow() {
return this.state.selected.rowIdx === this.props.rowsCount - 1;
},
isAtFirstCellInRow: function isAtFirstCellInRow() {
return this.state.selected.idx === 0;
},
isAtFirstRow: function isAtFirstRow() {
return this.state.selected.rowIdx === 0;
},
openCellEditor: function openCellEditor(rowIdx, idx) {
var _this4 = this;
var row = this.props.rowGetter(rowIdx);
var col = this.getColumn(idx);
if (!ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
return;
}
var selected = { rowIdx: rowIdx, idx: idx };
if (this.hasSelectedCellChanged(selected)) {
this.setState({ selected: selected }, function () {
_this4.setActive('Enter');
});
} else {
this.setActive('Enter');
}
},
scrollToColumn: function scrollToColumn(colIdx) {
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
var left = 0;
var locked = 0;
for (var i = 0; i < colIdx; i++) {
var column = this.getColumn(i);
if (column) {
if (column.width) {
left += column.width;
}
if (column.locked) {
locked += column.width;
}
}
}
var selectedColumn = this.getColumn(colIdx);
if (selectedColumn) {
var scrollLeft = left - locked - canvas.scrollLeft;
var scrollRight = left + selectedColumn.width - canvas.scrollLeft;
if (scrollLeft < 0) {
canvas.scrollLeft += scrollLeft;
} else if (scrollRight > canvas.clientWidth) {
var scrollAmount = scrollRight - canvas.clientWidth;
canvas.scrollLeft += scrollAmount;
}
}
}
},
setActive: function setActive(keyPressed) {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var column = this.getColumn(idx);
if (ColumnUtils.canEdit(column, row, this.props.enableCellSelect) && !this.isActive()) {
var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed });
var showEditor = true;
if (typeof this.props.onCheckCellIsEditable === 'function') {
var args = Object.assign({}, { row: row, column: column }, _selected);
showEditor = this.props.onCheckCellIsEditable(args);
}
if (showEditor !== false) {
this.setState({ selected: _selected }, this.scrollToColumn(idx));
}
}
},
setInactive: function setInactive() {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect) && this.isActive()) {
var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false });
this.setState({ selected: _selected2 });
}
},
isActive: function isActive() {
return this.state.selected.active === true;
},
setupGridColumns: function setupGridColumns() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var cols = props.columns.slice(0);
var unshiftedCols = {};
if (this.props.rowActionsCell || props.enableRowSelect && !this.props.rowSelection || props.rowSelection && props.rowSelection.showCheckbox !== false) {
var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement(
'div',
{ className: 'react-grid-checkbox-container' },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: 'select-all-checkbox', id: 'select-all-checkbox', onChange: this.handleCheckboxChange }),
React.createElement('label', { htmlFor: 'select-all-checkbox', className: 'react-grid-checkbox-label' })
);
var Formatter = this.props.rowActionsCell ? this.props.rowActionsCell : CheckboxEditor;
var selectColumn = {
key: 'select-row',
name: '',
formatter: React.createElement(Formatter, { rowSelection: this.props.rowSelection }),
onCellChange: this.handleRowSelect,
filterable: false,
headerRenderer: headerRenderer,
width: 60,
locked: true,
getRowMetaData: function getRowMetaData(rowData) {
return rowData;
},
cellClass: this.props.rowActionsCell ? 'rdg-row-actions-cell' : ''
};
unshiftedCols = cols.unshift(selectColumn);
cols = unshiftedCols > 0 ? cols : unshiftedCols;
}
return cols;
},
copyPasteEnabled: function copyPasteEnabled() {
return this.props.onCellCopyPaste !== null;
},
dragEnabled: function dragEnabled() {
return this.props.onGridRowsUpdated !== undefined || this.props.onCellsDragged !== undefined;
},
renderToolbar: function renderToolbar() {
var Toolbar = this.props.toolbar;
if (React.isValidElement(Toolbar)) {
return React.cloneElement(Toolbar, { columns: this.props.columns, onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount });
}
},
render: function render() {
var cellMetaData = {
selected: this.state.selected,
dragged: this.state.dragged,
hoveredRowIdx: this.state.hoveredRowIdx,
onCellClick: this.onCellClick,
onCellContextMenu: this.onCellContextMenu,
onCellDoubleClick: this.onCellDoubleClick,
onCommit: this.onCellCommit,
onCommitCancel: this.setInactive,
copied: this.state.copied,
handleDragEnterRow: this.handleDragEnter,
handleTerminateDrag: this.handleTerminateDrag,
enableCellSelect: this.props.enableCellSelect,
onColumnEvent: this.onColumnEvent,
openCellEditor: this.openCellEditor,
onDragHandleDoubleClick: this.onDragHandleDoubleClick,
onCellExpand: this.onCellExpand,
onRowExpandToggle: this.onRowExpandToggle,
onRowHover: this.onRowHover
};
var toolbar = this.renderToolbar();
var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth();
var gridWidth = containerWidth - this.state.scrollOffset;
// depending on the current lifecycle stage, gridWidth() may not initialize correctly
// this also handles cases where it always returns undefined -- such as when inside a div with display:none
// eg Bootstrap tabs and collapses
if (typeof containerWidth === 'undefined' || isNaN(containerWidth) || containerWidth === 0) {
containerWidth = '100%';
}
if (typeof gridWidth === 'undefined' || isNaN(gridWidth) || gridWidth === 0) {
gridWidth = '100%';
}
return React.createElement(
'div',
{ className: 'react-grid-Container', style: { width: containerWidth } },
toolbar,
React.createElement(
'div',
{ className: 'react-grid-Main' },
React.createElement(BaseGrid, _extends({
ref: 'base'
}, this.props, {
rowKey: this.props.rowKey,
headerRows: this.getHeaderRows(),
columnMetrics: this.state.columnMetrics,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
rowHeight: this.props.rowHeight,
cellMetaData: cellMetaData,
selectedRows: this.getSelectedRows(),
rowSelection: this.getRowSelectionProps(),
expandedRows: this.state.expandedRows,
rowOffsetHeight: this.getRowOffsetHeight(),
sortColumn: this.state.sortColumn,
sortDirection: this.state.sortDirection,
onSort: this.handleSort,
minHeight: this.props.minHeight,
totalWidth: gridWidth,
onViewportKeydown: this.onKeyDown,
onViewportKeyup: this.onKeyUp,
onViewportDragStart: this.onDragStart,
onViewportDragEnd: this.handleDragEnd,
onViewportDoubleClick: this.onViewportDoubleClick,
onColumnResize: this.onColumnResize,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu }))
)
);
}
});
module.exports = ReactDataGrid;
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var Draggable = __webpack_require__(44);
var ResizeHandle = React.createClass({
displayName: 'ResizeHandle',
style: {
position: 'absolute',
top: 0,
right: 0,
width: 6,
height: '100%'
},
render: function render() {
return React.createElement(Draggable, _extends({}, this.props, {
className: 'react-grid-HeaderCell__resizeHandle',
style: this.style
}));
}
});
module.exports = ResizeHandle;
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = __webpack_require__(4);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RowGroup = function (_Component) {
_inherits(RowGroup, _Component);
function RowGroup() {
_classCallCheck(this, RowGroup);
var _this = _possibleConstructorReturn(this, _Component.call(this));
_this.checkFocus = _this.checkFocus.bind(_this);
_this.isSelected = _this.isSelected.bind(_this);
_this.onClick = _this.onClick.bind(_this);
_this.onRowExpandToggle = _this.onRowExpandToggle.bind(_this);
_this.onKeyDown = _this.onKeyDown.bind(_this);
_this.onRowExpandClick = _this.onRowExpandClick.bind(_this);
return _this;
}
RowGroup.prototype.componentDidMount = function componentDidMount() {
this.checkFocus();
};
RowGroup.prototype.componentDidUpdate = function componentDidUpdate() {
this.checkFocus();
};
RowGroup.prototype.isSelected = function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.idx;
};
RowGroup.prototype.onClick = function onClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.idx, idx: 0 }, e);
}
};
RowGroup.prototype.onKeyDown = function onKeyDown(e) {
if (e.key === 'ArrowLeft') {
this.onRowExpandToggle(false);
}
if (e.key === 'ArrowRight') {
this.onRowExpandToggle(true);
}
if (e.key === 'Enter') {
this.onRowExpandToggle(!this.props.isExpanded);
}
};
RowGroup.prototype.onRowExpandClick = function onRowExpandClick() {
this.onRowExpandToggle(!this.props.isExpanded);
};
RowGroup.prototype.onRowExpandToggle = function onRowExpandToggle(expand) {
var shouldExpand = expand == null ? !this.props.isExpanded : expand;
var meta = this.props.cellMetaData;
if (meta != null && meta.onRowExpandToggle && typeof meta.onRowExpandToggle === 'function') {
meta.onRowExpandToggle({ rowIdx: this.props.idx, shouldExpand: shouldExpand, columnGroupName: this.props.columnGroupName, name: this.props.name });
}
};
RowGroup.prototype.getClassName = function getClassName() {
return (0, _classnames2['default'])('react-grid-row-group', 'react-grid-Row', { 'row-selected': this.isSelected() });
};
RowGroup.prototype.checkFocus = function checkFocus() {
if (this.isSelected()) {
_reactDom2['default'].findDOMNode(this).focus();
}
};
RowGroup.prototype.render = function render() {
var style = {
height: '50px',
overflow: 'hidden',
border: '1px solid #dddddd',
paddingTop: '15px',
paddingLeft: '5px'
};
var rowGroupRendererProps = Object.assign({ onRowExpandClick: this.onRowExpandClick }, this.props);
return _react2['default'].createElement(
'div',
{ style: style, className: this.getClassName(), onClick: this.onClick, onKeyDown: this.onKeyDown, tabIndex: -1 },
_react2['default'].createElement(this.props.renderer, rowGroupRendererProps)
);
};
return RowGroup;
}(_react.Component);
RowGroup.propTypes = {
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
cellMetaData: _react.PropTypes.object,
idx: _react.PropTypes.number.isRequired,
renderer: _react.PropTypes.func
};
var DefaultRowGroupRenderer = function DefaultRowGroupRenderer(props) {
var treeDepth = props.treeDepth || 0;
var marginLeft = treeDepth * 20;
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'span',
{ className: 'row-expand-icon', style: { float: 'left', marginLeft: marginLeft, cursor: 'pointer' }, onClick: props.onRowExpandClick },
props.isExpanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
),
_react2['default'].createElement(
'strong',
null,
props.columnGroupName,
' : ',
props.name
)
);
};
DefaultRowGroupRenderer.propTypes = {
onRowExpandClick: _react.PropTypes.func.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired
};
RowGroup.defaultProps = {
renderer: DefaultRowGroupRenderer
};
exports['default'] = RowGroup;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.SimpleRowsContainer = undefined;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var SimpleRowsContainer = function SimpleRowsContainer(props) {
return _react2['default'].createElement(
'div',
{ style: { overflow: 'hidden' } },
props.rows
);
};
SimpleRowsContainer.propTypes = {
width: _react.PropTypes.number,
rows: _react.PropTypes.array
};
var RowsContainer = function (_React$Component) {
_inherits(RowsContainer, _React$Component);
function RowsContainer(props) {
_classCallCheck(this, RowsContainer);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.plugins = props.window ? props.window.ReactDataGridPlugins : window.ReactDataGridPlugins;
_this.hasContextMenu = _this.hasContextMenu.bind(_this);
_this.renderRowsWithContextMenu = _this.renderRowsWithContextMenu.bind(_this);
_this.getContextMenuContainer = _this.getContextMenuContainer.bind(_this);
_this.state = { ContextMenuContainer: _this.getContextMenuContainer(props) };
return _this;
}
RowsContainer.prototype.getContextMenuContainer = function getContextMenuContainer() {
if (this.hasContextMenu()) {
if (!this.plugins) {
throw new Error('You need to include ReactDataGrid UiPlugins in order to initialise context menu');
}
return this.plugins.Menu.ContextMenuLayer('reactDataGridContextMenu')(SimpleRowsContainer);
}
};
RowsContainer.prototype.hasContextMenu = function hasContextMenu() {
return this.props.contextMenu && _react2['default'].isValidElement(this.props.contextMenu);
};
RowsContainer.prototype.renderRowsWithContextMenu = function renderRowsWithContextMenu() {
var ContextMenuRowsContainer = this.state.ContextMenuContainer;
var newProps = { rowIdx: this.props.rowIdx, idx: this.props.idx };
var contextMenu = _react2['default'].cloneElement(this.props.contextMenu, newProps);
// Initialise the context menu if it is available
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(ContextMenuRowsContainer, this.props),
contextMenu
);
};
RowsContainer.prototype.render = function render() {
return this.hasContextMenu() ? this.renderRowsWithContextMenu() : _react2['default'].createElement(SimpleRowsContainer, this.props);
};
return RowsContainer;
}(_react2['default'].Component);
RowsContainer.propTypes = {
contextMenu: _react.PropTypes.element,
rowIdx: _react.PropTypes.number,
idx: _react.PropTypes.number,
window: _react.PropTypes.object
};
exports['default'] = RowsContainer;
exports.SimpleRowsContainer = SimpleRowsContainer;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var ScrollShim = {
appendScrollShim: function appendScrollShim() {
if (!this._scrollShim) {
var size = this._scrollShimSize();
var shim = document.createElement('div');
if (shim.classList) {
shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement
} else {
shim.className += ' react-grid-ScrollShim';
}
shim.style.position = 'absolute';
shim.style.top = 0;
shim.style.left = 0;
shim.style.width = size.width + 'px';
shim.style.height = size.height + 'px';
_reactDom2['default'].findDOMNode(this).appendChild(shim);
this._scrollShim = shim;
}
this._scheduleRemoveScrollShim();
},
_scrollShimSize: function _scrollShimSize() {
return {
width: this.props.width,
height: this.props.length * this.props.rowHeight
};
},
_scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() {
if (this._scheduleRemoveScrollShimTimer) {
clearTimeout(this._scheduleRemoveScrollShimTimer);
}
this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200);
},
_removeScrollShim: function _removeScrollShim() {
if (this._scrollShim) {
this._scrollShim.parentNode.removeChild(this._scrollShim);
this._scrollShim = undefined;
}
}
};
module.exports = ScrollShim;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var Canvas = __webpack_require__(41);
var ViewportScroll = __webpack_require__(58);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var Viewport = React.createClass({
displayName: 'Viewport',
mixins: [ViewportScroll],
propTypes: {
rowOffsetHeight: PropTypes.number.isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
columnMetrics: PropTypes.object.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
selectedRows: PropTypes.array,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
expandedRows: PropTypes.array,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
rowsCount: PropTypes.number.isRequired,
rowHeight: PropTypes.number.isRequired,
onRows: PropTypes.func,
onScroll: PropTypes.func,
minHeight: PropTypes.number,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowGroupRenderer: PropTypes.func
},
onScroll: function onScroll(scroll) {
this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount);
if (this.props.onScroll) {
this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft });
}
},
getScroll: function getScroll() {
return this.refs.canvas.getScroll();
},
setScrollLeft: function setScrollLeft(scrollLeft) {
this.refs.canvas.setScrollLeft(scrollLeft);
},
render: function render() {
var style = {
padding: 0,
bottom: 0,
left: 0,
right: 0,
overflow: 'hidden',
position: 'absolute',
top: this.props.rowOffsetHeight
};
return React.createElement(
'div',
{
className: 'react-grid-Viewport',
style: style },
React.createElement(Canvas, {
ref: 'canvas',
rowKey: this.props.rowKey,
totalWidth: this.props.totalWidth,
width: this.props.columnMetrics.width,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columns: this.props.columnMetrics.columns,
rowRenderer: this.props.rowRenderer,
displayStart: this.state.displayStart,
displayEnd: this.state.displayEnd,
cellMetaData: this.props.cellMetaData,
height: this.state.height,
rowHeight: this.props.rowHeight,
onScroll: this.onScroll,
onRows: this.props.onRows,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer
})
);
}
});
module.exports = Viewport;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var DOMMetrics = __webpack_require__(9);
var min = Math.min;
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
DOMMetrics: {
viewportHeight: function viewportHeight() {
return ReactDOM.findDOMNode(this).offsetHeight;
}
},
propTypes: {
rowHeight: React.PropTypes.number,
rowsCount: React.PropTypes.number.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 30
};
},
getInitialState: function getInitialState() {
return this.getGridState(this.props);
},
getGridState: function getGridState(props) {
var canvasHeight = props.minHeight - props.rowOffsetHeight;
var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight);
var totalRowCount = min(renderedRowsCount * 2, props.rowsCount);
return {
displayStart: 0,
displayEnd: totalRowCount,
height: canvasHeight,
scrollTop: 0,
scrollLeft: 0
};
},
updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) {
var renderedRowsCount = ceil(height / rowHeight);
var visibleStart = floor(scrollTop / rowHeight);
var visibleEnd = min(visibleStart + renderedRowsCount, length);
var displayStart = max(0, visibleStart - renderedRowsCount * 2);
var displayEnd = min(visibleStart + renderedRowsCount * 2, length);
var nextScrollState = {
visibleStart: visibleStart,
visibleEnd: visibleEnd,
displayStart: displayStart,
displayEnd: displayEnd,
height: height,
scrollTop: scrollTop,
scrollLeft: scrollLeft
};
this.setState(nextScrollState);
},
metricsUpdated: function metricsUpdated() {
var height = this.DOMMetrics.viewportHeight();
if (height) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight) {
this.setState(this.getGridState(nextProps));
} else if (this.props.rowsCount !== nextProps.rowsCount) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount);
// Added to fix the hiding of the bottom scrollbar when showing the filters.
} else if (this.props.rowOffsetHeight !== nextProps.rowOffsetHeight) {
// The value of height can be positive or negative and will be added to the current height to cater for changes in the header height (due to the filer)
var _height = this.props.rowOffsetHeight - nextProps.rowOffsetHeight;
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height + _height, nextProps.rowHeight, nextProps.rowsCount);
}
}
};
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumn = __webpack_require__(6);
var FilterableHeaderCell = React.createClass({
displayName: 'FilterableHeaderCell',
propTypes: {
onChange: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn)
},
getInitialState: function getInitialState() {
return { filterTerm: '' };
},
handleChange: function handleChange(e) {
var val = e.target.value;
this.setState({ filterTerm: val });
this.props.onChange({ filterTerm: val, column: this.props.column });
},
renderInput: function renderInput() {
if (this.props.column.filterable === false) {
return React.createElement('span', null);
}
var inputKey = 'header-filter-' + this.props.column.key;
return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange });
},
render: function render() {
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'form-group' },
this.renderInput()
)
);
}
});
module.exports = FilterableHeaderCell;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(4);
var DEFINE_SORT = {
ASC: 'ASC',
DESC: 'DESC',
NONE: 'NONE'
};
var SortableHeaderCell = React.createClass({
displayName: 'SortableHeaderCell',
propTypes: {
columnKey: React.PropTypes.string.isRequired,
column: React.PropTypes.shape({ name: React.PropTypes.node }),
onSort: React.PropTypes.func.isRequired,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE'])
},
onClick: function onClick() {
var direction = void 0;
switch (this.props.sortDirection) {
default:
case null:
case undefined:
case DEFINE_SORT.NONE:
direction = DEFINE_SORT.ASC;
break;
case DEFINE_SORT.ASC:
direction = DEFINE_SORT.DESC;
break;
case DEFINE_SORT.DESC:
direction = DEFINE_SORT.NONE;
break;
}
this.props.onSort(this.props.columnKey, direction);
},
getSortByText: function getSortByText() {
var unicodeKeys = {
ASC: '9650',
DESC: '9660',
NONE: ''
};
return String.fromCharCode(unicodeKeys[this.props.sortDirection]);
},
render: function render() {
var className = joinClasses({
'react-grid-HeaderCell-sortable': true,
'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC',
'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC'
});
return React.createElement(
'div',
{ className: className,
onClick: this.onClick,
style: { cursor: 'pointer' } },
this.props.column.name,
React.createElement(
'span',
{ className: 'pull-right' },
this.getSortByText()
)
);
}
});
module.exports = SortableHeaderCell;
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var CheckboxEditor = React.createClass({
displayName: 'CheckboxEditor',
propTypes: {
value: React.PropTypes.bool,
rowIdx: React.PropTypes.number,
column: React.PropTypes.shape({
key: React.PropTypes.string,
onCellChange: React.PropTypes.func
}),
dependentValues: React.PropTypes.object
},
handleChange: function handleChange(e) {
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e);
},
render: function render() {
var checked = this.props.value != null ? this.props.value : false;
var checkboxName = 'checkbox' + this.props.rowIdx;
return React.createElement(
'div',
{ className: 'react-grid-checkbox-container', onClick: this.handleChange },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }),
React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' })
);
}
});
module.exports = CheckboxEditor;
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var ExcelColumn = __webpack_require__(6);
var EditorBase = function (_React$Component) {
_inherits(EditorBase, _React$Component);
function EditorBase() {
_classCallCheck(this, EditorBase);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
EditorBase.prototype.getStyle = function getStyle() {
return {
width: '100%'
};
};
EditorBase.prototype.getValue = function getValue() {
var updated = {};
updated[this.props.column.key] = this.getInputNode().value;
return updated;
};
EditorBase.prototype.getInputNode = function getInputNode() {
var domNode = ReactDOM.findDOMNode(this);
if (domNode.tagName === 'INPUT') {
return domNode;
}
return domNode.querySelector('input:not([type=hidden])');
};
EditorBase.prototype.inheritContainerStyles = function inheritContainerStyles() {
return true;
};
return EditorBase;
}(React.Component);
EditorBase.propTypes = {
onKeyDown: React.PropTypes.func.isRequired,
value: React.PropTypes.any.isRequired,
onBlur: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn).isRequired,
commit: React.PropTypes.func.isRequired
};
module.exports = EditorBase;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(4);
var keyboardHandlerMixin = __webpack_require__(23);
var SimpleTextEditor = __webpack_require__(64);
var isFunction = __webpack_require__(25);
var EditorContainer = React.createClass({
displayName: 'EditorContainer',
mixins: [keyboardHandlerMixin],
propTypes: {
rowIdx: React.PropTypes.number,
rowData: React.PropTypes.object.isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
cellMetaData: React.PropTypes.shape({
selected: React.PropTypes.object.isRequired,
copied: React.PropTypes.object,
dragged: React.PropTypes.object,
onCellClick: React.PropTypes.func,
onCellDoubleClick: React.PropTypes.func,
onCommitCancel: React.PropTypes.func,
onCommit: React.PropTypes.func
}).isRequired,
column: React.PropTypes.object.isRequired,
height: React.PropTypes.number.isRequired
},
changeCommitted: false,
getInitialState: function getInitialState() {
return { isInvalid: false };
},
componentDidMount: function componentDidMount() {
var inputNode = this.getInputNode();
if (inputNode !== undefined) {
this.setTextInputFocus();
if (!this.getEditor().disableContainerStyles) {
inputNode.className += ' editor-main';
inputNode.style.height = this.props.height - 1 + 'px';
}
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.changeCommitted && !this.hasEscapeBeenPressed()) {
this.commit({ key: 'Enter' });
}
},
createEditor: function createEditor() {
var _this = this;
var editorRef = function editorRef(c) {
return _this.editor = c;
};
var editorProps = {
ref: editorRef,
column: this.props.column,
value: this.getInitialValue(),
onCommit: this.commit,
rowMetaData: this.getRowMetaData(),
rowData: this.props.rowData,
height: this.props.height,
onBlur: this.commit,
onOverrideKeyDown: this.onKeyDown
};
var CustomEditor = this.props.column.editor;
// return custom column editor or SimpleEditor if none specified
if (React.isValidElement(CustomEditor)) {
return React.cloneElement(CustomEditor, editorProps);
}
if (isFunction(CustomEditor)) {
return React.createElement(CustomEditor, _extends({ ref: editorRef }, editorProps));
}
return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} });
},
onPressEnter: function onPressEnter() {
this.commit({ key: 'Enter' });
},
onPressTab: function onPressTab() {
this.commit({ key: 'Tab' });
},
onPressEscape: function onPressEscape(e) {
if (!this.editorIsSelectOpen()) {
this.props.cellMetaData.onCommitCancel();
} else {
// prevent event from bubbling if editor has results to select
e.stopPropagation();
}
},
onPressArrowDown: function onPressArrowDown(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowUp: function onPressArrowUp(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowLeft: function onPressArrowLeft(e) {
// prevent event propogation. this disables left cell navigation
if (!this.isCaretAtBeginningOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowRight: function onPressArrowRight(e) {
// prevent event propogation. this disables right cell navigation
if (!this.isCaretAtEndOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
editorHasResults: function editorHasResults() {
if (isFunction(this.getEditor().hasResults)) {
return this.getEditor().hasResults();
}
return false;
},
editorIsSelectOpen: function editorIsSelectOpen() {
if (isFunction(this.getEditor().isSelectOpen)) {
return this.getEditor().isSelectOpen();
}
return false;
},
getRowMetaData: function getRowMetaData() {
// clone row data so editor cannot actually change this
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.props.rowData, this.props.column);
}
},
getEditor: function getEditor() {
return this.editor;
},
getInputNode: function getInputNode() {
return this.getEditor().getInputNode();
},
getInitialValue: function getInitialValue() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
if (keyCode === 'Delete' || keyCode === 'Backspace') {
return '';
} else if (keyCode === 'Enter') {
return this.props.value;
}
var text = keyCode ? String.fromCharCode(keyCode) : this.props.value;
return text;
},
getContainerClass: function getContainerClass() {
return joinClasses({
'has-error': this.state.isInvalid === true
});
},
commit: function commit(args) {
var opts = args || {};
var updated = this.getEditor().getValue();
if (this.isNewValueValid(updated)) {
this.changeCommitted = true;
var cellKey = this.props.column.key;
this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key });
}
},
isNewValueValid: function isNewValueValid(value) {
if (isFunction(this.getEditor().validate)) {
var isValid = this.getEditor().validate(value);
this.setState({ isInvalid: !isValid });
return isValid;
}
return true;
},
setCaretAtEndOfInput: function setCaretAtEndOfInput() {
var input = this.getInputNode();
// taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element
var txtLength = input.value.length;
if (input.setSelectionRange) {
input.setSelectionRange(txtLength, txtLength);
} else if (input.createTextRange) {
var fieldRange = input.createTextRange();
fieldRange.moveStart('character', txtLength);
fieldRange.collapse();
fieldRange.select();
}
},
isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0;
},
isCaretAtEndOfInput: function isCaretAtEndOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.value.length;
},
isBodyClicked: function isBodyClicked(e) {
return e.relatedTarget === null;
},
isViewportClicked: function isViewportClicked(e) {
return e.relatedTarget.classList.contains('react-grid-Viewport');
},
isClickInisdeEditor: function isClickInisdeEditor(e) {
return e.currentTarget.contains(e.relatedTarget) || e.relatedTarget.classList.contains('editing') || e.relatedTarget.classList.contains('react-grid-Cell');
},
handleBlur: function handleBlur(e) {
e.stopPropagation();
if (this.isBodyClicked(e)) {
this.commit(e);
}
if (!this.isBodyClicked(e)) {
// prevent null reference
if (this.isViewportClicked(e) || !this.isClickInisdeEditor(e)) {
this.commit(e);
}
}
},
setTextInputFocus: function setTextInputFocus() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
var inputNode = this.getInputNode();
inputNode.focus();
if (inputNode.tagName === 'INPUT') {
if (!this.isKeyPrintable(keyCode)) {
inputNode.focus();
inputNode.select();
} else {
inputNode.select();
}
}
},
hasEscapeBeenPressed: function hasEscapeBeenPressed() {
var pressed = false;
var escapeKey = 27;
if (window.event) {
if (window.event.keyCode === escapeKey) {
pressed = true;
} else if (window.event.which === escapeKey) {
pressed = true;
}
}
return pressed;
},
renderStatusIcon: function renderStatusIcon() {
if (this.state.isInvalid === true) {
return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' });
}
},
render: function render() {
return React.createElement(
'div',
{ className: this.getContainerClass(), onBlur: this.handleBlur, onKeyDown: this.onKeyDown, commit: this.commit },
this.createEditor(),
this.renderStatusIcon()
);
}
});
module.exports = EditorContainer;
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var React = __webpack_require__(1);
var EditorBase = __webpack_require__(62);
var SimpleTextEditor = function (_EditorBase) {
_inherits(SimpleTextEditor, _EditorBase);
function SimpleTextEditor() {
_classCallCheck(this, SimpleTextEditor);
return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments));
}
SimpleTextEditor.prototype.render = function render() {
return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value });
};
return SimpleTextEditor;
}(EditorBase);
module.exports = SimpleTextEditor;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var SimpleCellFormatter = React.createClass({
displayName: 'SimpleCellFormatter',
propTypes: {
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
},
render: function render() {
return React.createElement(
'div',
{ title: this.props.value },
this.props.value
);
}
});
module.exports = SimpleCellFormatter;
/***/ },
/* 66 */
/***/ function(module, exports) {
'use strict';
module.exports = function isColumnsImmutable(columns) {
return typeof Immutable !== 'undefined' && columns instanceof Immutable.List;
};
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (false) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(67);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? false ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(94),
hashDelete = __webpack_require__(95),
hashGet = __webpack_require__(96),
hashHas = __webpack_require__(97),
hashSet = __webpack_require__(98);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(28),
setCacheAdd = __webpack_require__(118),
setCacheHas = __webpack_require__(119);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(10),
stackClear = __webpack_require__(121),
stackDelete = __webpack_require__(122),
stackGet = __webpack_require__(123),
stackHas = __webpack_require__(124),
stackSet = __webpack_require__(125);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(85),
isArguments = __webpack_require__(126),
isArray = __webpack_require__(33),
isBuffer = __webpack_require__(34),
isIndex = __webpack_require__(99),
isTypedArray = __webpack_require__(37);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ },
/* 78 */
/***/ function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(12),
isObjectLike = __webpack_require__(15);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(81),
isObject = __webpack_require__(21),
isObjectLike = __webpack_require__(15);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @param {boolean} [bitmask] The bitmask of comparison flags.
* The bitmask may be composed of the following flags:
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
module.exports = baseIsEqual;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(74),
equalArrays = __webpack_require__(29),
equalByTag = __webpack_require__(89),
equalObjects = __webpack_require__(90),
getTag = __webpack_require__(92),
isArray = __webpack_require__(33),
isBuffer = __webpack_require__(34),
isTypedArray = __webpack_require__(37);
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG = 2;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparisons.
* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
: equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
}
if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
}
module.exports = baseIsEqualDeep;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(35),
isMasked = __webpack_require__(101),
isObject = __webpack_require__(21),
toSource = __webpack_require__(31);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(12),
isLength = __webpack_require__(36),
isObjectLike = __webpack_require__(15);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(102),
nativeKeys = __webpack_require__(114);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ },
/* 85 */
/***/ function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ },
/* 86 */
/***/ function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ },
/* 87 */
/***/ function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(20),
Uint8Array = __webpack_require__(75),
eq = __webpack_require__(32),
equalArrays = __webpack_require__(29),
mapToArray = __webpack_require__(113),
setToArray = __webpack_require__(120);
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= UNORDERED_COMPARE_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
var keys = __webpack_require__(129);
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG = 2;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(20);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(69),
Map = __webpack_require__(19),
Promise = __webpack_require__(71),
Set = __webpack_require__(72),
WeakMap = __webpack_require__(76),
baseGetTag = __webpack_require__(12),
toSource = __webpack_require__(31);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ },
/* 93 */
/***/ function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(14);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ },
/* 95 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(14);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(14);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(14);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ },
/* 99 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ },
/* 100 */
/***/ function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(88);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ },
/* 102 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ },
/* 103 */
/***/ function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(11);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(11);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(11);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(11);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(70),
ListCache = __webpack_require__(10),
Map = __webpack_require__(19);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(13);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(13);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(13);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(13);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ },
/* 113 */
/***/ function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(117);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(30);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(39)(module)))
/***/ },
/* 116 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ },
/* 117 */
/***/ function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ },
/* 118 */
/***/ function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ },
/* 119 */
/***/ function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ },
/* 120 */
/***/ function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(10);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ },
/* 122 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ },
/* 123 */
/***/ function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(10),
Map = __webpack_require__(19),
MapCache = __webpack_require__(28);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(79),
isObjectLike = __webpack_require__(15);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(35),
isLength = __webpack_require__(36);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(80);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are **not** supported.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(77),
baseKeys = __webpack_require__(84),
isArrayLike = __webpack_require__(127);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ },
/* 130 */
/***/ function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }
/******/ ])
});
;
|
src/ModalHeader.js
|
wjb12/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
class ModalHeader extends React.Component {
render() {
return (
<div
{...this.props}
className={classNames(this.props.className, this.props.modalClassName)}>
{ this.props.closeButton &&
<button
className="close"
onClick={this.props.onHide}>
<span aria-hidden="true">
×
</span>
</button>
}
{ this.props.children }
</div>
);
}
}
// used in liue of parent contexts right now to auto wire the close button
ModalHeader.__isModalHeader = true;
ModalHeader.propTypes = {
/**
* The 'aria-label' attribute is used to define a string that labels the current element.
* It is used for Assistive Technology when the label text is not visible on screen.
*/
'aria-label': React.PropTypes.string,
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string,
/**
* Specify whether the Component should contain a close button
*/
closeButton: React.PropTypes.bool,
/**
* A Callback fired when the close button is clicked. If used directly inside a Modal component, the onHide will automatically
* be propagated up to the parent Modal `onHide`.
*/
onHide: React.PropTypes.func
};
ModalHeader.defaultProps = {
'aria-label': 'Close',
modalClassName: 'modal-header',
closeButton: false
};
export default ModalHeader;
|
src/components/GuitarApp/parts/Fretguide/index.js
|
jesusGalan/fretboardApp
|
import React, { Component } from 'react';
import {TransparentDiv} from './styled'
import {Row} from 'components/common/Template'
class Fretguide extends Component {
render() {
let frets = []
let x = 0
for (x = 0; x < 12; x++) {
frets.push(x)
}
return (
<Row>
{frets.map(this.renderTransparentDivs.bind(this))}
</Row>
);
}
renderTransparentDivs(x) {
if (x === 0 || x === 3 || x === 5 || x === 7) {
return(
<TransparentDiv key={x} number={x.toString()}>{x}</TransparentDiv>
)
}
else {
return(
<TransparentDiv key={x} number={x.toString()}></TransparentDiv>
)
}
}
}
export default Fretguide;
|
misc/webgui/src/components/Statedevice.js
|
ChainsAutomation/chains
|
import React from 'react';
// Per service render
export default class StateDevice extends React.Component {
render() {
/*
console.log("StateDevice");
console.log(this.props);
//*/
const ddata = this.props.ddata;
let devData = [];
for (var dev in ddata['data']) {
const dItem = dev;
let dVal = ddata['data'][dev]['value'];
if (typeof(dVal) != 'string')
dVal = JSON.stringify(dVal);
const attr = <div key={dItem}><div className="header">{dItem}</div><div className="meta">{dVal}</div></div>;
//console.log(attr);
devData.push(attr);
}
return (
<div className="ui raised card">
<div className="content">
<div className="header">{this.props.name}</div>
<div className="meta">
<span className="category">{ddata.class}</span>
</div>
<div className="description">
{devData}
</div>
</div>
<div className="extra content">
<div className="right floated author">
<img className="ui avatar image" src={ddata.icon} /> {ddata.type}
</div>
</div>
</div>
);
}
}
/*
<div className="card">
<div className="image">
<img src="http://mrg.bz/IxQIgC" />
</div>
<div className="content">
{devData}
</div>
<div className="ui bottom attached basic buttons">
<button className="ui button"><i className="pencil icon"></i></button>
<button className="ui button"><i className="trash icon"></i></button>
</div>
</div>
*/
|
ajax/libs/rxjs/2.3.9/rx.lite.js
|
kentucky-roberts/cdnjs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable =
SerialDisposable = Rx.SerialDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var s = state;
var id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
}(Scheduler.prototype));
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throw(new Error('Error'));
* var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && observer.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
activeCount === 0 && observer.onCompleted();
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
*
* @example
* var res = source.takeLast(5);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
if (!subject.isDisposed) {
subject.onNext(value);
subject.onCompleted();
}
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, subject.subscribe.bind(subject));
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* 1 - res = Rx.Observable.timer(new Date());
* 2 - res = Rx.Observable.timer(new Date(), 1000);
* 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);
*
* 5 - res = Rx.Observable.timer(5000);
* 6 - res = Rx.Observable.timer(5000, 1000);
* 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
other || (other = observableThrow(new Error('Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
observer.onNext(next.value);
}
}
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
});
};
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
previousShouldFire = results.shouldFire;
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this));
|
client/src/component/toolbar/ToolbarLeft.js
|
Hacktus/react-ui-builder
|
'use strict';
var React = require('react/addons');
var ModalProgressTrigger = require('../modal/ModalProgressTrigger.js');
var ModalProgressTriggerAction = require('../../action/modal/ModalProgressTriggerActions.js');
var ModalProjectSettingsTriggerActions = require('../../action/modal/ModalProjectSettingsTriggerActions.js');
var ModalFileListUploadTriggerActions = require('../../action/modal/ModalFileListUploadTriggerActions.js');
var Button = require('react-bootstrap').Button;
var DeskAction = require('../../action/desk/DeskActions.js');
var ApplicationActions = require('../../action/application/ApplicationActions.js');
var DeskPageFrameActions = require('../../action/desk/DeskPageFrameActions.js');
var cx = React.addons.classSet;
var ToolbarLeft = React.createClass({
componentDidMount: function(){
},
render: function(){
var leftSideStyle = {
'position': 'absolute',
'top': 0,
'left': 0,
'bottom': 0
};
var leftSideStyleInner = {
'position': 'relative',
'minWidth': '4em',
'width': '4em',
'padding': '0 0.5em 0 0.5em'
};
var btnGroupStyle = {
'width': '100%',
'textAlign': 'center'
};
return (
<div style={leftSideStyle}>
<div style={leftSideStyleInner}>
<div className="btn-group" style={btnGroupStyle}>
<a href="#" className="dropdown-toggle" data-toggle="dropdown">
<span className="fa fa-bars" style={{fontSize: 32}} />
</a>
<ul className="dropdown-menu" role="menu">
<li><a href="#" onClick={this._handleProjectSettings}>
<span className="fa fa-gears fa-fw" /> Project settings</a>
</li>
<li><a href="#" onClick={this._handlePublishProject}>
<span className="fa fa-cloud-upload fa-fw" /> Publish project</a>
</li>
<li className="divider" />
<li><a href="https://groups.google.com/forum/#!forum/react-ui-builder" target="_blank">
<span className="fa fa-comments-o fa-fw"></span> Forum / Help</a>
</li>
<li className="divider" />
<li><a href="#" onClick={ApplicationActions.goToStartPage}>
<span className="fa fa-sign-out fa-fw" /> Close project</a>
</li>
</ul>
</div>
<Button
bsStyle={this.props.isAvailableComponentsButtonActive ? 'primary' : 'default'}
style={{marginTop: '1em', width: '100%'}}
disabled={!this.props.isEditMode}
onClick={DeskAction.toggleAvailableComponents}>
<span className="fa fa-plus" />
</Button>
<Button
bsStyle={this.props.isComponentsHierarchyButtonActive ? 'primary' : 'default'}
style={{marginTop: '0.25em', width: '100%'}}
disabled={!this.props.isEditMode}
onClick={DeskAction.toggleComponentsHierarchy}>
<span className="fa fa-code" />
</Button>
<Button
bsStyle={this.props.isStyleOptionsButtonActive ? 'primary' : 'default'}
style={{marginTop: '0.25em', width: '100%'}}
disabled={!this.props.isEditMode}
onClick={DeskAction.toggleStyleOptions}>
<span className="fa fa-paint-brush" />
</Button>
<Button
bsStyle={this.props.isEditMode ? 'primary' : 'default'}
style={{marginTop: '1em', width: '100%'}}
onClick={DeskAction.startEditMode}>
<span className="fa fa-wrench" />
</Button>
<Button
bsStyle={this.props.isLivePreviewMode ? 'primary' : 'default'}
style={{marginTop: '0.25em', width: '100%'}}
onClick={DeskAction.startLivePreviewMode}>
<span className="fa fa-eye" />
</Button>
<div style={{marginTop: '0.25em', width: '100%', height: '2em'}} />
</div>
</div>
)
},
_handleDummy: function(e){
e.stopPropagation();
e.preventDefault();
},
_handlePublishProject: function(e){
e.stopPropagation();
e.preventDefault();
ModalFileListUploadTriggerActions.showModal();
},
_handleProjectSettings: function(e){
e.stopPropagation();
e.preventDefault();
ModalProjectSettingsTriggerActions.showModal();
},
_handleShowProjectComponents: function(e){
e.stopPropagation();
e.preventDefault();
DeskPageFrameActions.showProjectComponents();
}
});
module.exports = ToolbarLeft;
|
src/svg-icons/editor/format-color-reset.js
|
xmityaz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatColorReset = (props) => (
<SvgIcon {...props}>
<path d="M18 14c0-4-6-10.8-6-10.8s-1.33 1.51-2.73 3.52l8.59 8.59c.09-.42.14-.86.14-1.31zm-.88 3.12L12.5 12.5 5.27 5.27 4 6.55l3.32 3.32C6.55 11.32 6 12.79 6 14c0 3.31 2.69 6 6 6 1.52 0 2.9-.57 3.96-1.5l2.63 2.63 1.27-1.27-2.74-2.74z"/>
</SvgIcon>
);
EditorFormatColorReset = pure(EditorFormatColorReset);
EditorFormatColorReset.displayName = 'EditorFormatColorReset';
EditorFormatColorReset.muiName = 'SvgIcon';
export default EditorFormatColorReset;
|
ajax/libs/react-redux/4.0.4/react-redux.min.js
|
BitsyCode/cdnjs
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("redux")):"function"==typeof define&&define.amd?define(["react","redux"],t):"object"==typeof exports?exports.ReactRedux=t(require("react"),require("redux")):e.ReactRedux=t(e.React,e.Redux)}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.connect=t.Provider=void 0;var o=r(3),s=n(o),i=r(4),u=n(i);t.Provider=s.default,t.connect=u.default},function(t,r){t.exports=e},function(e,t,r){"use strict";t.__esModule=!0;var n=r(1);t.default=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(){f||(f=!0,console.error("<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/rackt/react-redux/releases/tag/v2.0.0 for the migration instructions."))}t.__esModule=!0,t.default=void 0;var a=r(1),c=r(2),p=n(c),f=!1,d=function(e){function t(r,n){o(this,t);var i=s(this,e.call(this,r,n));return i.store=r.store,i}return i(t,e),t.prototype.getChildContext=function(){return{store:this.store}},t.prototype.componentWillReceiveProps=function(e){var t=this.store,r=e.store;t!==r&&u()},t.prototype.render=function(){var e=this.props.children;return a.Children.only(e)},t}(a.Component);t.default=d,d.propTypes={store:p.default.isRequired,children:a.PropTypes.element.isRequired},d.childContextTypes={store:p.default.isRequired}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){return e.displayName||e.name||"Component"}function a(e,t,r){function n(e,t){var r=e.getState(),n=j?m(r,t):m(r);return(0,w.default)((0,b.default)(n),"`mapStateToProps` must return an object. Instead received %s.",n),n}function a(e,t){var r=e.dispatch,n=R?g(r,t):g(r);return(0,w.default)((0,b.default)(n),"`mapDispatchToProps` must return an object. Instead received %s.",n),n}function f(e,t,r){var n=x(e,t,r);return(0,w.default)((0,b.default)(n),"`mergeProps` must return an object. Instead received %s.",n),n}var l=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],y=Boolean(e),m=e||C,g=(0,b.default)(t)?(0,v.default)(t):t||S,x=r||O,j=1!==m.length,R=1!==g.length,T=l.pure,E=void 0===T?!0:T,M=l.withRef,I=void 0===M?!1:M,q=_++;return function(e){var t=function(t){function r(e,n){o(this,r);var i=s(this,t.call(this,e,n));i.version=q,i.store=e.store||n.store,(0,w.default)(i.store,'Could not find "store" in either the context or '+('props of "'+i.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+i.constructor.displayName+'".'));var u=i.store.getState();return i.state={storeState:u},i.clearCache(),i}return i(r,t),r.prototype.shouldComponentUpdate=function(){return!E||this.haveOwnPropsChanged||this.hasStoreStateChanged},r.prototype.updateStatePropsIfNeeded=function(){var e=n(this.store,this.props);return this.stateProps&&(0,h.default)(e,this.stateProps)?!1:(this.stateProps=e,!0)},r.prototype.updateDispatchPropsIfNeeded=function(){var e=a(this.store,this.props);return this.dispatchProps&&(0,h.default)(e,this.dispatchProps)?!1:(this.dispatchProps=e,!0)},r.prototype.updateMergedProps=function(){this.mergedProps=f(this.stateProps,this.dispatchProps,this.props)},r.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},r.prototype.trySubscribe=function(){y&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},r.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},r.prototype.componentDidMount=function(){this.trySubscribe()},r.prototype.componentWillReceiveProps=function(e){E&&(0,h.default)(e,this.props)||(this.haveOwnPropsChanged=!0)},r.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},r.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.renderedElement=null},r.prototype.handleChange=function(){if(this.unsubscribe){var e=this.state.storeState,t=this.store.getState();E&&e===t||(this.hasStoreStateChanged=!0,this.setState({storeState:t}))}},r.prototype.getWrappedInstance=function(){return(0,w.default)(I,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},r.prototype.render=function(){var t=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.renderedElement;this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1;var o=!0,s=!0;E&&n&&(o=r||t&&j,s=t&&R);var i=!1,u=!1;o&&(i=this.updateStatePropsIfNeeded()),s&&(u=this.updateDispatchPropsIfNeeded());var a=!0;return i||u||t?this.updateMergedProps():a=!1,!a&&n?n:(I?this.renderedElement=(0,p.createElement)(e,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,p.createElement)(e,this.mergedProps),this.renderedElement)},r}(p.Component);return t.displayName="Connect("+u(e)+")",t.WrappedComponent=e,t.contextTypes={store:d.default},t.propTypes={store:d.default},(0,P.default)(t,e)}}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.__esModule=!0,t.default=a;var p=r(1),f=r(2),d=n(f),l=r(6),h=n(l),y=r(5),b=n(y),m=r(7),v=n(m),g=r(8),P=n(g),x=r(9),w=n(x),C=function(){return{}},S=function(e){return{dispatch:e}},O=function(e,t,r){return c({},r,e,t)},_=0},function(e,t){"use strict";function r(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function n(e){if(!e||"object"!==("undefined"==typeof e?"undefined":r(e)))return!1;var t="function"==typeof e.constructor?Object.getPrototypeOf(e):Object.prototype;if(null===t)return!0;var n=t.constructor;return"function"==typeof n&&n instanceof n&&o(n)===o(Object)}t.__esModule=!0,t.default=n;var o=function(e){return Function.prototype.toString.call(e)}},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var o=Object.prototype.hasOwnProperty,s=0;s<r.length;s++)if(!o.call(t,r[s])||e[r[s]]!==t[r[s]])return!1;return!0}t.__esModule=!0,t.default=r},function(e,t,r){"use strict";function n(e){return function(t){return(0,o.bindActionCreators)(e,t)}}t.__esModule=!0,t.default=n;var o=r(10)},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0};e.exports=function(e,t){for(var o=Object.getOwnPropertyNames(t),s=0;s<o.length;++s)r[o[s]]||n[o[s]]||(e[o[s]]=t[o[s]]);return e}},function(e,t,r){"use strict";var n=function(e,t,r,n,o,s,i,u){if(!e){var a;if(void 0===t)a=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,o,s,i,u],p=0;a=new Error(t.replace(/%s/g,function(){return c[p++]})),a.name="Invariant Violation"}throw a.framesToPop=1,a}};e.exports=n},function(e,r){e.exports=t}])});
|
examples/js/pagination/custom-pagination-table.js
|
rolandsusans/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(100);
export default class CustomPaginationTable extends React.Component {
renderShowsTotal(start, to, total) {
return (
<p style={ { color: 'blue' } }>
From { start } to { to }, totals is { total } (its a customize text)
</p>
);
}
render() {
const options = {
page: 2, // which page you want to show as default
sizePerPageList: [ {
text: '5', value: 5
}, {
text: '10', value: 10
}, {
text: 'All', value: products.length
} ], // you can change the dropdown list for size per page
sizePerPage: 5, // which size per page you want to locate as default
pageStartIndex: 0, // where to start counting the pages
paginationSize: 3, // the pagination bar size.
prePage: 'Prev', // Previous page button text
nextPage: 'Next', // Next page button text
firstPage: 'First', // First page button text
lastPage: 'Last', // Last page button text
paginationShowsTotal: this.renderShowsTotal // Accept bool or function
// hideSizePerPage: true > You can hide the dropdown for sizePerPage
};
return (
<BootstrapTable data={ products } pagination={ true } options={ options }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/svg-icons/navigation/chevron-right.js
|
tan-jerene/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationChevronRight = (props) => (
<SvgIcon {...props}>
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</SvgIcon>
);
NavigationChevronRight = pure(NavigationChevronRight);
NavigationChevronRight.displayName = 'NavigationChevronRight';
NavigationChevronRight.muiName = 'SvgIcon';
export default NavigationChevronRight;
|
src/svg-icons/av/not-interested.js
|
hwo411/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvNotInterested = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/>
</SvgIcon>
);
AvNotInterested = pure(AvNotInterested);
AvNotInterested.displayName = 'AvNotInterested';
AvNotInterested.muiName = 'SvgIcon';
export default AvNotInterested;
|
lib/dropdown/index.js
|
jasonleibowitz/react-toolbox
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Dropdown = undefined;
var _reactCssThemr = require('react-css-themr');
var _identifiers = require('../identifiers.js');
var _Dropdown = require('./Dropdown.js');
var _input = require('../input');
var _theme = require('./theme.scss');
var _theme2 = _interopRequireDefault(_theme);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Dropdown = (0, _Dropdown.dropdownFactory)(_input.Input);
var ThemedDropdown = (0, _reactCssThemr.themr)(_identifiers.DROPDOWN, _theme2.default)(Dropdown);
exports.default = ThemedDropdown;
exports.Dropdown = ThemedDropdown;
|
resolvers/subschema-resolver-transition/test/transition-test.js
|
jspears/subschema-devel
|
import React from 'react';
import { expect } from 'chai';
import { newSubschemaContext } from 'subschema-core';
import transitions from 'subschema-transitions';
import loaderFactory from 'subschema-loader';
import {transition} from 'subschema-resolver-transition';
describe("resolvers/transition", function () {
let loader;
before(function () {
loader = loaderFactory();
loader.addLoader(transitions);
});
it('should resolve transition, slideLeft no appear', function () {
const timeout = 500;
const { Transition, ...resp } = transition.handleTransition('slideLeft',
'stuff', {},
{ loader });
expect(resp).to.eql({
"timeout" : {enter: 500, appear: 500, exit: 500},
"classNames": {
"enter" : "transitions__slideLeftEnter___3b_Rw",
"enterActive" : "transitions__slideLeftEnterActive___1AI3C",
"appear" : "transitions__slideLeftAppear___1Hfkk",
"appearActive": "transitions__slideLeftAppearActive___AfFFk",
"exit" : "transitions__slideLeftLeave___3_25V",
"exitActive" : "transitions__slideLeftLeaveActive___3H6Pk"
},
"className" : "transitions__slideLeftHeight___iynS8"
});
});
it('should resolve transition, slideLeft with appear', function () {
const timeout = 500;
const { Transition, ...resp } = transition.handleTransition(
{ transition: 'slideLeft', on: ['appear'] }, 'stuff', {},
{ loader });
expect(resp).to.eql({
"timeout" : {enter: 500, appear: 500, exit: 500},
"classNames": {
"enter" : "transitions__slideLeftEnter___3b_Rw",
"enterActive" : "transitions__slideLeftEnterActive___1AI3C",
"appear" : "transitions__slideLeftAppear___1Hfkk",
"appearActive": "transitions__slideLeftAppearActive___AfFFk",
"exit" : "transitions__slideLeftLeave___3_25V",
"exitActive" : "transitions__slideLeftLeaveActive___3H6Pk"
},
"className" : "transitions__slideLeftHeight___iynS8"
});
});
it('should resolve transition, slideLeft with appear with custom timeout',
function () {
const timeout = 200;
const { Transition, ...resp } = transition.handleTransition({
transition : 'slideLeft',
transitionAppearTimeout: timeout,
on : ['appear']
}, 'stuff', {}, { loader });
expect(resp).to.eql({
"timeout": {enter: 500, appear: 500, exit: 500},
"classNames": {
"enter": "transitions__slideLeftEnter___3b_Rw",
"enterActive": "transitions__slideLeftEnterActive___1AI3C",
"appear": "transitions__slideLeftAppear___1Hfkk",
"appearActive": "transitions__slideLeftAppearActive___AfFFk",
"exit": "transitions__slideLeftLeave___3_25V",
"exitActive": "transitions__slideLeftLeaveActive___3H6Pk"
},
"className": "transitions__slideLeftHeight___iynS8"
});
});
});
|
files/jparallax/2.0.3/jquery.parallax_1.0.js
|
vuejs/jsdelivr
|
// jquery.parallax.js
// 1.1
// Stephen Band
//
// Project and documentation site:
// webdev.stephband.info/jparallax/
//
// Repository:
// github.com/stephband/jparallax
//
// Dependencies:
// jquery.event.frame
// webdev.stephband.info/events/frame/
(function(jQuery, undefined) {
// Debug
var debug = true;
// VAR
var options = {
mouseport: 'body', // jQuery object or selector of DOM node to use as mouse detector
xparallax: true, // boolean | 0-1 | 'npx' | 'n%' - Sets axis of reaction and by how much they react
yparallax: true, //
xorigin: 0.5, // 0-1 - Sets default alignment. Only has effect when parallax values are something other than 1 (or true, or '100%')
yorigin: 0.5, //
decay: 0.66, // 0-1 (0 instant, 1 forever) - Sets rate of decay curve for catching up with target mouse position
frameDuration: 30, // Int (milliseconds)
freezeClass: 'freeze' // String - Class added to layer when frozen
},
value = {
left: 0,
top: 0,
middle: 0.5,
center: 0.5,
right: 1,
bottom: 1
},
regex = {
px: /^\d+\s?px$/,
percent: /^\d+\s?%$/
},
frameEvent = 'frame.parallax',
abs = Math.abs,
pointer = [0, 0];
// FUNCTIONS
function parseValue(value) { return this.lib[value]; }
parseValue.lib = value;
// Converts numbers or numbers in strings to boolean
function parseBool(x) {
return typeof x === "boolean" ? x : !!( parseFloat(x) ) ;
}
function parseCoord(x) {
return (regex.percent.exec(x)) ? parseFloat(x)/100 : x;
}
// CONSTRUCTORS
function Mouse(xparallax, yparallax, decay, pointer){
// Convert parallax options to boolean values
var parallax = [xparallax, yparallax];
this.ontarget = false;
this.decay = decay;
this.pointer = pointer || [0.5, 0.5];
this.update = function(pointer, threshold){
var lagPointer, x;
// Pointer is already on target
if (this.ontarget) {
this.pointer = pointer;
}
// Pointer has arrived within the target thresholds
else if ((!parallax[0] || abs(pointer[0] - this.pointer[0]) < threshold[0]) &&
(!parallax[1] || abs(pointer[1] - this.pointer[1]) < threshold[1])) {
this.ontarget = true;
this.pointer = pointer;
}
// Pointer is nowhere near the target
else {
lagPointer = [];
x = 2;
while (x--) {
if ( parallax[x] ) {
lagPointer[x] = pointer[x] + this.decay * (this.pointer[x] - pointer[x]);
}
}
this.pointer = lagPointer;
}
};
}
function Port(object, options){
var self = this,
elem = object instanceof jQuery ? object : jQuery(object) ,
// Convert parallax options to boolean values
parallax = [parseBool(options.xparallax), parseBool(options.yparallax)],
// State of mouse position (0 - outside, 1 - inside, 2 - just gone outside)
inside = 0,
// Stores mouse position on mouseleave event
leaveCoords;
this.pointer = [0, 0];
this.active = false;
this.activeOutside = (options && options.activeOutside) || false;
this.update = function(coords){
var pos = this.pos,
size = this.size,
pointer = [],
x = 2;
// Is mouse inside port?
// Yes.
if ( inside > 0 ) {
// But it just went outside, so make this the last move
// Use leaveCoords stored by mouseleave event
if ( inside === 2 ) {
inside = 0;
if (leaveCoords) {
coords = leaveCoords
};
}
while (x--) {
if ( parallax[x] ) {
pointer[x] = (coords[x] - pos[x]) / size[x] ;
pointer[x] = pointer[x] < 0 ? 0 : pointer[x] > 1 ? 1 : pointer[x] ;
}
}
this.active = true;
this.pointer = pointer;
}
// No.
else {
this.active = false;
}
};
this.updateSize = function(){
var width = elem.width(),
height = elem.height();
self.size = [width, height];
self.threshold = [ 1/width, 1/height ];
};
this.updatePos = function(){
var offset = elem.offset() || {left: 0, top: 0},
left = parseInt(elem.css('borderLeftWidth')) + parseInt(elem.css('paddingLeft')),
top = parseInt(elem.css('borderTopWidth')) + parseInt(elem.css('paddingTop'));
self.pos = [offset.left + left, offset.top + top];
};
// Update mouseport dimensions on window resize
jQuery(window)
.bind('resize.parallax', self.updateSize)
.bind('resize.parallax', self.updatePos);
// Detect entry and exit of mouse
elem
.bind('mouseenter.parallax', function(e){
inside = 1;
})
.bind('mouseleave.parallax', function(e){
inside = 2;
leaveCoords = [e.pageX, e.pageY];
});
// Set up layer
this.updateSize();
this.updatePos();
}
function Layer(elem, options){
var px = [],
parallax = [],
offset = [],
position = [];
this.update = function(pointer){
var pos = [],
cssPosition,
cssMargin,
x = 2,
css = {};
while (x--) {
if ( parallax[x] ) {
pos[x] = parallax[x] * pointer[x] + offset[x];
// We're working in pixels
if ( px[x] ) {
cssPosition = position[x];
cssMargin = pos[x] * -1;
}
// We're working by ratio
else {
cssPosition = pos[x] * 100 + '%';
cssMargin = pos[x] * this.size[x] * -1;
}
// Fill in css object
if ( x === 0 ) {
css.left = cssPosition;
css.marginLeft = cssMargin;
}
else {
css.top = cssPosition;
css.marginTop = cssMargin;
}
}
}
// Set css
elem.css(css);
};
this.setParallax = function(xp, yp, xo, yo){
var p = [ xp || options.xparallax, yp || options.yparallax ],
origin = [ xo || options.xorigin, yo || options.yorigin ],
i = 2,
css = {};
while (i--) {
// Set px flag
px[i] = regex.px.test(p[i]);
// Convert origin to numbers
if (typeof origin[i] === 'string') {
origin[i] = origin[i] === undefined ? 1 :
value[ origin[i] ] || parseCoord(origin[i]) ;
}
// We're dealing with pixel dimensions
if ( px[i] ) {
// Set parallax
parallax[i] = parseInt(p[i]);
// Set offset
offset[i] = origin[i] * ( this.size[i] - parallax[i] );
// Set css position constant
position[i] = origin[i] * 100 + '%';
}
// We're dealing with ratios
else {
// Set parallax, converting to ratio where necessary
parallax[i] = p[i] === true ? 1 : parseCoord(p[i]);
// Set offset
offset[i] = parallax[i] ? origin[i] * ( 1 - parallax[i] ) : 0 ;
}
}
};
this.getPointer = function(){
var viewport = elem.offsetParent(),
pos = elem.position(),
position = [],
pointer = [],
i = 2;
// Reverse calculate ratio from layer's current position
while (i--) {
if ( px[i] ) {
// TODO: reverse calculation for pixel case
position[i] = 0;
}
else {
position[i] = pos[ i === 0 ? 'left' : 'top' ] / (viewport[ i === 0 ? 'outerWidth' : 'outerHeight' ]() - this.size[i]) ;
}
pointer[i] = (position[i] - offset[i]) / parallax[i] ;
}
return pointer;
};
this.setSize = function(x, y){
this.size = [ x || elem.outerWidth(), y || elem.outerHeight() ];
};
this.setSize(options.width, options.height);
this.setParallax(options.xparallax, options.yparallax, options.xorigin, options.yorigin);
}
// EVENT HANDLERS
function update(e){
var elem = jQuery(this),
global = e.data.global || e.data,
local = e.data.local || elem.data('parallax'),
port = global.port,
mouse = global.mouse,
localmouse = local.mouse;
if(debug) { console.log('jquery.parallax update'); }
// Global objects have yet to be processed for this frame
if (global.timeStamp !== e.timeStamp) {
// Set timeStamp to current time
global.timeStamp = e.timeStamp;
// Process mouseport
port.update(pointer);
// Process mouse
if ( port.active || !mouse.ontarget ) {
mouse.update(port.pointer, port.threshold);
}
}
// Layer has it's own mouse
if ( localmouse ) {
// Process mouse
localmouse.update( local.freeze ? local.freeze.pointer : port.pointer, port.threshold );
// If it hits target
if ( localmouse.ontarget ) {
delete local.mouse;
// Stop animating frozen layers
if (local.freeze) {
elem
.unbind(frameEvent)
.addClass(global.freezeClass);
}
}
// Use localmouse in place of mouse
mouse = localmouse;
}
// Layer is responding to global mouse
else {
// When no longer active, unbind
if ( mouse.ontarget && !port.active ) {
elem.unbind(frameEvent);
}
}
local.layer.update(mouse.pointer);
}
jQuery.fn.parallax = function(o){
var global = jQuery.extend({}, jQuery.fn.parallax.options, o),
args = arguments,
layers = this,
optionsArray = [];
if (undefined === jQuery.event.special.frame) {
throw new Error("jquery.parallax requires jquery.event.frame.");
}
// Turn mouseport into jQuery obj
if ( !(global.mouseport instanceof jQuery) ) {
global.mouseport = jQuery(global.mouseport);
}
global.port = new Port(global.mouseport, global);
global.mouse = new Mouse(parseBool(global.xparallax), parseBool(global.yparallax), global.decay);
global.mouseport
.bind("mouseenter", function(e){
var i = layers.length,
layer;
global.mouse.ontarget = false;
// Animate unfrozen layers
while (i--) {
layer = layers[i];
if (!jQuery.data(layer, 'parallax').freeze) {
jQuery.event.add(this, frameEvent, update, {
global: global,
local: optionsArray[i]
});
};
}
});
return layers.each(function(i){
var elem = jQuery(this),
// Construct layer options from extra arguments
layerOptions = args[i+1] ? jQuery.extend({}, global, args[i+1]) : global ,
// Set up layer data. Give it a local mouse
// initialises it to start smoothly from current position
layer = new Layer(elem, layerOptions),
local = {
layer: layer,
mouse: new Mouse(parseBool(layerOptions.xparallax), parseBool(layerOptions.yparallax), layerOptions.decay, layer.getPointer())
};
elem.data('parallax', local);
optionsArray.push(local);
// Bind freeze and unfreeze actions directly to layers using
// jQuery.event.add(node, type, fn, data)
jQuery.event.add(this, 'freeze', function(e){
var elem = jQuery(this),
global = e.data.global,
local = e.data.local,
mouse = local.mouse || local.freeze || global.mouse,
coords = coords = [
e.x === undefined ? mouse.pointer[0] : parseCoord(e.x),
e.y === undefined ? mouse.pointer[1] : parseCoord(e.y)
],
decay = e.decay;
// Store position
local.freeze = { pointer: coords };
// Create local mouse, passing in current pointer with options
local.mouse = new Mouse(parseBool(global.xparallax), parseBool(global.yparallax), global.decay, mouse.pointer);
if (decay !== undefined) { local.mouse.decay = decay; }
// Start animating
jQuery.event.add(this, frameEvent, update, global);
}, {
global: global,
local: local
});
jQuery.event.add( this, 'unfreeze', function(e){
var elem = jQuery(this),
global = e.data.global,
local = e.data.local,
decay = e.decay,
pointer;
if (!local.freeze) { return; }
// Create local mouse, passing local freeze pointer with options
pointer = local.mouse ? local.mouse.pointer : local.freeze.pointer ;
local.mouse = new Mouse(parseBool(global.xparallax), parseBool(global.yparallax), global);
local.mouse.pointer = pointer;
// Override decay with decay passed as e.decay
if (decay !== undefined) local.mouse.decay = decay;
// Destroy local.freeze
delete local.freeze;
// Remove freeze class and start animating
elem.removeClass(options.freezeClass);
// Start animating
jQuery.event.add(this, frameEvent, update, global);
}, {
global: global,
local: local
});
});
};
// EXPOSE
jQuery.fn.parallax.options = options;
// RUN
jQuery(document).ready(function(){
// Pick up and store mouse position on jQuery(document)
// IE does not register mousemove on jQuery(window)
jQuery(document)
.mousemove(function(e){
pointer = [e.pageX, e.pageY];
});
});
}(jQuery));
|
app/javascript/mastodon/features/lists/components/new_list_form.js
|
musashino205/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { changeListEditorTitle, submitListEditor } from '../../../actions/lists';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' },
title: { id: 'lists.new.create', defaultMessage: 'Add list' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'title']),
disabled: state.getIn(['listEditor', 'isSubmitting']),
});
const mapDispatchToProps = dispatch => ({
onChange: value => dispatch(changeListEditorTitle(value)),
onSubmit: () => dispatch(submitListEditor(true)),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class NewListForm extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
disabled: PropTypes.bool,
intl: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleSubmit = e => {
e.preventDefault();
this.props.onSubmit();
}
handleClick = () => {
this.props.onSubmit();
}
render () {
const { value, disabled, intl } = this.props;
const label = intl.formatMessage(messages.label);
const title = intl.formatMessage(messages.title);
return (
<form className='column-inline-form' onSubmit={this.handleSubmit}>
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={value}
disabled={disabled}
onChange={this.handleChange}
placeholder={label}
/>
</label>
<IconButton
disabled={disabled || !value}
icon='plus'
title={title}
onClick={this.handleClick}
/>
</form>
);
}
}
|
test/js/AR/release_test/ARImageTrackingTest.js
|
viromedia/viro
|
/**
* Copyright (c) 2017-present, Viro Media, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroARScene,
ViroARPlane,
ViroImage,
ViroARPlaneSelector,
ViroQuad,
ViroConstants,
ViroNode,
ViroBox,
ViroOmniLight,
ViroText,
ViroUtils,
ViroARTrackingTargets,
ViroARImageMarker,
} from 'react-viro';
var createReactClass = require('create-react-class');
let polarToCartesian = ViroUtils.polarToCartesian;
var ARImageTrackingTest = createReactClass({
getInitialState: function() {
return {
target : "variety",
pauseUpdates : false,
};
},
componentDidMount: function() {
this.props.arSceneNavigator.viroAppProps.toggleNumberOfTrackedImages();
},
render: function() {
return (
<ViroARScene>
<ViroARImageMarker target={"variety"}
onAnchorFound={()=>{console.log("ARImageMarkerTest found marker!")}}
onAnchorUpdated={()=>{console.log("ARImageMarkerTest updated marker!")}}
onAnchorRemoved={()=>{console.log("ARImageMarkerTest removed marker!")}} >
<ViroBox scale={[.189, .1, 0.245]} position={[0, .05, 0]}/>
</ViroARImageMarker>
{/* Release Menu */}
<ViroText position={polarToCartesian([6, -30, -15])} text={"Release Menu"}
style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
transformBehaviors={["billboard"]}/>
</ViroARScene>
);
},
});
var styles = StyleSheet.create({
instructionText: {
fontFamily: 'Arial',
fontSize: 25,
width: 2,
color: '#cccccc',
flex: 1,
textAlignVertical: 'center',
textAlign: 'center',
},
});
ViroARTrackingTargets.createTargets({
variety : {
source : require("./res/ar_targets/variety_magazine.jpg"),
orientation : "Up",
physicalWidth : 0.189,
height : .245,
},
});
module.exports = ARImageTrackingTest;
|
packages/es-components/src/components/containers/tooltip/Tooltip.specs.js
|
TWExchangeSolutions/es-components
|
/* eslint-env jest */
import React from 'react';
import { fireEvent, waitFor } from '@testing-library/react';
import Tooltip from './Tooltip';
import { renderWithTheme } from '../../util/test-utils';
it('displays when the mouse enters the target and hides when the mouse leaves the target', async () => {
const instance = renderWithTheme(
<Tooltip name="test" content="this is the tooltip">
this is the target
</Tooltip>
);
const { queryByText, queryByRole } = instance;
const target = queryByText('this is the target');
fireEvent.mouseEnter(target);
const toolTip = queryByRole('tooltip');
await waitFor(() => {
expect(toolTip).toBeVisible();
});
fireEvent.mouseLeave(target);
await waitFor(() => {
expect(toolTip).not.toBeInTheDocument();
});
});
it('is displayed on mouseDown if disableHover is true', async () => {
const { getByText, queryByRole } = renderWithTheme(
<Tooltip name="test" content="this is the tooltip" disableHover>
this is the target
</Tooltip>
);
const target = getByText('this is the target');
fireEvent.mouseEnter(target);
await waitFor(() => {
expect(queryByRole('tooltip')).not.toBeInTheDocument();
});
fireEvent.click(target);
await waitFor(() => {
expect(queryByRole('tooltip')).toBeInTheDocument();
});
fireEvent.click(target);
await waitFor(() => {
expect(queryByRole('tooltip')).not.toBeInTheDocument();
});
});
it('is displayed/hidden on focus/blur of target', async () => {
const instance = renderWithTheme(
<Tooltip name="test" content="this is the tooltip" disableHover>
this is the target
</Tooltip>
);
const { getByText, queryByRole } = instance;
const target = getByText('this is the target');
fireEvent.focus(target);
const toolTip = queryByRole('tooltip');
await waitFor(() => {
expect(toolTip).toBeVisible();
});
fireEvent.blur(target);
await waitFor(() => {
expect(toolTip).not.toBeInTheDocument();
});
});
it('is hidden when ESC is pressed', async () => {
const { getByText, queryByRole } = renderWithTheme(
<Tooltip name="test" content="this is the tooltip" disableHover>
this is the target
</Tooltip>
);
const target = getByText('this is the target');
fireEvent.click(target);
const toolTip = queryByRole('tooltip');
await waitFor(() => {
expect(toolTip).toBeVisible();
});
fireEvent.keyDown(target, { keyCode: 27 });
await waitFor(() => {
expect(toolTip).not.toBeInTheDocument();
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.